attributes.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. // All APIs in this package are EXPERIMENTAL.
  22. package attributes
  23. import "fmt"
  24. // Attributes is an immutable struct for storing and retrieving generic
  25. // key/value pairs. Keys must be hashable, and users should define their own
  26. // types for keys.
  27. type Attributes struct {
  28. m map[interface{}]interface{}
  29. }
  30. // New returns a new Attributes containing all key/value pairs in kvs. If the
  31. // same key appears multiple times, the last value overwrites all previous
  32. // values for that key. Panics if len(kvs) is not even.
  33. func New(kvs ...interface{}) *Attributes {
  34. if len(kvs)%2 != 0 {
  35. panic(fmt.Sprintf("attributes.New called with unexpected input: len(kvs) = %v", len(kvs)))
  36. }
  37. a := &Attributes{m: make(map[interface{}]interface{}, len(kvs)/2)}
  38. for i := 0; i < len(kvs)/2; i++ {
  39. a.m[kvs[i*2]] = kvs[i*2+1]
  40. }
  41. return a
  42. }
  43. // WithValues returns a new Attributes containing all key/value pairs in a and
  44. // kvs. Panics if len(kvs) is not even. If the same key appears multiple
  45. // times, the last value overwrites all previous values for that key. To
  46. // remove an existing key, use a nil value.
  47. func (a *Attributes) WithValues(kvs ...interface{}) *Attributes {
  48. if len(kvs)%2 != 0 {
  49. panic(fmt.Sprintf("attributes.New called with unexpected input: len(kvs) = %v", len(kvs)))
  50. }
  51. n := &Attributes{m: make(map[interface{}]interface{}, len(a.m)+len(kvs)/2)}
  52. for k, v := range a.m {
  53. n.m[k] = v
  54. }
  55. for i := 0; i < len(kvs)/2; i++ {
  56. n.m[kvs[i*2]] = kvs[i*2+1]
  57. }
  58. return n
  59. }
  60. // Value returns the value associated with these attributes for key, or nil if
  61. // no value is associated with key.
  62. func (a *Attributes) Value(key interface{}) interface{} {
  63. return a.m[key]
  64. }