attributes.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. /*
  2. *
  3. * Copyright 2019 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package attributes defines a generic key/value store used in various gRPC
  19. // components.
  20. //
  21. // # Experimental
  22. //
  23. // Notice: This package is EXPERIMENTAL and may be changed or removed in a
  24. // later release.
  25. package attributes
  26. import (
  27. "fmt"
  28. "strings"
  29. )
  30. // Attributes is an immutable struct for storing and retrieving generic
  31. // key/value pairs. Keys must be hashable, and users should define their own
  32. // types for keys. Values should not be modified after they are added to an
  33. // Attributes or if they were received from one. If values implement 'Equal(o
  34. // any) bool', it will be called by (*Attributes).Equal to determine whether
  35. // two values with the same key should be considered equal.
  36. type Attributes struct {
  37. m map[any]any
  38. }
  39. // New returns a new Attributes containing the key/value pair.
  40. func New(key, value any) *Attributes {
  41. return &Attributes{m: map[any]any{key: value}}
  42. }
  43. // WithValue returns a new Attributes containing the previous keys and values
  44. // and the new key/value pair. If the same key appears multiple times, the
  45. // last value overwrites all previous values for that key. To remove an
  46. // existing key, use a nil value. value should not be modified later.
  47. func (a *Attributes) WithValue(key, value any) *Attributes {
  48. if a == nil {
  49. return New(key, value)
  50. }
  51. n := &Attributes{m: make(map[any]any, len(a.m)+1)}
  52. for k, v := range a.m {
  53. n.m[k] = v
  54. }
  55. n.m[key] = value
  56. return n
  57. }
  58. // Value returns the value associated with these attributes for key, or nil if
  59. // no value is associated with key. The returned value should not be modified.
  60. func (a *Attributes) Value(key any) any {
  61. if a == nil {
  62. return nil
  63. }
  64. return a.m[key]
  65. }
  66. // Equal returns whether a and o are equivalent. If 'Equal(o any) bool' is
  67. // implemented for a value in the attributes, it is called to determine if the
  68. // value matches the one stored in the other attributes. If Equal is not
  69. // implemented, standard equality is used to determine if the two values are
  70. // equal. Note that some types (e.g. maps) aren't comparable by default, so
  71. // they must be wrapped in a struct, or in an alias type, with Equal defined.
  72. func (a *Attributes) Equal(o *Attributes) bool {
  73. if a == nil && o == nil {
  74. return true
  75. }
  76. if a == nil || o == nil {
  77. return false
  78. }
  79. if len(a.m) != len(o.m) {
  80. return false
  81. }
  82. for k, v := range a.m {
  83. ov, ok := o.m[k]
  84. if !ok {
  85. // o missing element of a
  86. return false
  87. }
  88. if eq, ok := v.(interface{ Equal(o any) bool }); ok {
  89. if !eq.Equal(ov) {
  90. return false
  91. }
  92. } else if v != ov {
  93. // Fallback to a standard equality check if Value is unimplemented.
  94. return false
  95. }
  96. }
  97. return true
  98. }
  99. // String prints the attribute map. If any key or values throughout the map
  100. // implement fmt.Stringer, it calls that method and appends.
  101. func (a *Attributes) String() string {
  102. var sb strings.Builder
  103. sb.WriteString("{")
  104. first := true
  105. for k, v := range a.m {
  106. if !first {
  107. sb.WriteString(", ")
  108. }
  109. sb.WriteString(fmt.Sprintf("%q: %q ", str(k), str(v)))
  110. first = false
  111. }
  112. sb.WriteString("}")
  113. return sb.String()
  114. }
  115. func str(x any) (s string) {
  116. if v, ok := x.(fmt.Stringer); ok {
  117. return fmt.Sprint(v)
  118. } else if v, ok := x.(string); ok {
  119. return v
  120. }
  121. return fmt.Sprintf("<%p>", x)
  122. }
  123. // MarshalJSON helps implement the json.Marshaler interface, thereby rendering
  124. // the Attributes correctly when printing (via pretty.JSON) structs containing
  125. // Attributes as fields.
  126. //
  127. // Is it impossible to unmarshal attributes from a JSON representation and this
  128. // method is meant only for debugging purposes.
  129. func (a *Attributes) MarshalJSON() ([]byte, error) {
  130. return []byte(a.String()), nil
  131. }