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