properties.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package smithy
  2. import "maps"
  3. // PropertiesReader provides an interface for reading metadata from the
  4. // underlying metadata container.
  5. type PropertiesReader interface {
  6. Get(key any) any
  7. }
  8. // Properties provides storing and reading metadata values. Keys may be any
  9. // comparable value type. Get and Set will panic if a key is not comparable.
  10. //
  11. // The zero value for a Properties instance is ready for reads/writes without
  12. // any additional initialization.
  13. type Properties struct {
  14. values map[any]any
  15. }
  16. // Get attempts to retrieve the value the key points to. Returns nil if the
  17. // key was not found.
  18. //
  19. // Panics if key type is not comparable.
  20. func (m *Properties) Get(key any) any {
  21. m.lazyInit()
  22. return m.values[key]
  23. }
  24. // Set stores the value pointed to by the key. If a value already exists at
  25. // that key it will be replaced with the new value.
  26. //
  27. // Panics if the key type is not comparable.
  28. func (m *Properties) Set(key, value any) {
  29. m.lazyInit()
  30. m.values[key] = value
  31. }
  32. // Has returns whether the key exists in the metadata.
  33. //
  34. // Panics if the key type is not comparable.
  35. func (m *Properties) Has(key any) bool {
  36. m.lazyInit()
  37. _, ok := m.values[key]
  38. return ok
  39. }
  40. // SetAll accepts all of the given Properties into the receiver, overwriting
  41. // any existing keys in the case of conflicts.
  42. func (m *Properties) SetAll(other *Properties) {
  43. if other.values == nil {
  44. return
  45. }
  46. m.lazyInit()
  47. for k, v := range other.values {
  48. m.values[k] = v
  49. }
  50. }
  51. // Values returns a shallow clone of the property set's values.
  52. func (m *Properties) Values() map[any]any {
  53. return maps.Clone(m.values)
  54. }
  55. func (m *Properties) lazyInit() {
  56. if m.values == nil {
  57. m.values = map[any]any{}
  58. }
  59. }