-
Notifications
You must be signed in to change notification settings - Fork 59
/
bag.go
54 lines (49 loc) · 1.17 KB
/
bag.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package lmdbsync
// Bag is a simple context object for Handlers. Bags are immutable, though by
// storing references in a Bag the contents themselves may be mutable.
type Bag interface {
// value returns a value associated with key in the Bag.
Value(key interface{}) interface{}
}
type bag struct {
b Bag
m map[interface{}]interface{}
}
func (b *bag) Value(key interface{}) interface{} {
v, ok := b.m[key]
if ok {
return v
}
if b.b == nil {
return nil
}
return b.b.Value(key)
}
// Background returns an empty Bag that can be used in future calls to BagWith.
func Background() Bag {
return &bag{}
}
// BagWith returns a new Bag that contains everything in b and associates key
// with value, possibly overriding a corresponding mapping in b.
func BagWith(b Bag, key, value interface{}) Bag {
var m map[interface{}]interface{}
if _b, ok := b.(*bag); !ok {
if value != nil {
m = map[interface{}]interface{}{key: value}
}
} else {
// collapse the bag value to reduce indirection
b = _b.b
m = make(map[interface{}]interface{}, len(_b.m)+1)
for k, v := range _b.m {
m[k] = v
}
if value != nil {
m[key] = value
}
}
return &bag{
b: b,
m: m,
}
}