registry.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package registry
  2. import (
  3. "errors"
  4. )
  5. // Registry error.
  6. var (
  7. ErrKeyLocked = errors.New("key is locked")
  8. )
  9. // Registry is a simple interface allowing untyped common values to be shared across packages.
  10. // This is particularly useful for resolving import cycles.
  11. type Registry struct {
  12. data map[string]any
  13. locks map[string]bool
  14. }
  15. // Get the value of a key.
  16. // This function returns nil if no value exists.
  17. func (reg *Registry) Get(key string) any {
  18. return reg.data[key]
  19. }
  20. // Has checks whether a key is non-nil.
  21. func (reg *Registry) Has(key string) bool {
  22. return reg.data[key] == nil
  23. }
  24. // Lock a key.
  25. // This prevents the value being overwritten by Set.
  26. func (reg *Registry) Lock(key string) {
  27. reg.locks[key] = true
  28. }
  29. // Set the value for a key.
  30. // This function returns an error if the key is locked.
  31. func (reg *Registry) Set(key string, value any) error {
  32. if reg.locks[key] {
  33. return ErrKeyLocked
  34. }
  35. reg.data[key] = value
  36. return nil
  37. }
  38. // New creates a new registry.
  39. func New() *Registry {
  40. return &Registry{
  41. data: map[string]any{},
  42. locks: map[string]bool{},
  43. }
  44. }