blob: 3220d87be40396bc1a1b570022844f86511d91ea [file] [log] [blame]
khenaidoo5fc5cea2021-08-11 17:39:16 -04001/*
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
19// Package attributes defines a generic key/value store used in various gRPC
20// components.
21//
22// Experimental
23//
24// Notice: This package is EXPERIMENTAL and may be changed or removed in a
25// later release.
26package attributes
27
28import "fmt"
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.
33type Attributes struct {
34 m map[interface{}]interface{}
35}
36
37// New returns a new Attributes containing all key/value pairs in kvs. If the
38// same key appears multiple times, the last value overwrites all previous
39// values for that key. Panics if len(kvs) is not even.
40func New(kvs ...interface{}) *Attributes {
41 if len(kvs)%2 != 0 {
42 panic(fmt.Sprintf("attributes.New called with unexpected input: len(kvs) = %v", len(kvs)))
43 }
44 a := &Attributes{m: make(map[interface{}]interface{}, len(kvs)/2)}
45 for i := 0; i < len(kvs)/2; i++ {
46 a.m[kvs[i*2]] = kvs[i*2+1]
47 }
48 return a
49}
50
51// WithValues returns a new Attributes containing all key/value pairs in a and
52// kvs. Panics if len(kvs) is not even. If the same key appears multiple
53// times, the last value overwrites all previous values for that key. To
54// remove an existing key, use a nil value.
55func (a *Attributes) WithValues(kvs ...interface{}) *Attributes {
56 if a == nil {
57 return New(kvs...)
58 }
59 if len(kvs)%2 != 0 {
60 panic(fmt.Sprintf("attributes.New called with unexpected input: len(kvs) = %v", len(kvs)))
61 }
62 n := &Attributes{m: make(map[interface{}]interface{}, len(a.m)+len(kvs)/2)}
63 for k, v := range a.m {
64 n.m[k] = v
65 }
66 for i := 0; i < len(kvs)/2; i++ {
67 n.m[kvs[i*2]] = kvs[i*2+1]
68 }
69 return n
70}
71
72// Value returns the value associated with these attributes for key, or nil if
73// no value is associated with key.
74func (a *Attributes) Value(key interface{}) interface{} {
75 if a == nil {
76 return nil
77 }
78 return a.m[key]
79}