-
Notifications
You must be signed in to change notification settings - Fork 16
/
fasttags.go
41 lines (33 loc) · 930 Bytes
/
fasttags.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
package goforit
import (
"sync"
"sync/atomic"
)
// fastTags is a structure for fast access to read-mostly default tags.
// It supports lockless reads and synchronized updates.
type fastTags struct {
tags atomic.Pointer[map[string]string]
writerLock sync.Mutex
}
func newFastTags() *fastTags {
return new(fastTags)
}
// Load returns a map of default tags. This map MUST only be read, not written to.
func (ft *fastTags) Load() map[string]string {
if tags := ft.tags.Load(); tags != nil {
return *tags
}
return nil
}
// Set replaces the default tags.
func (ft *fastTags) Set(tags map[string]string) {
ft.writerLock.Lock()
defer ft.writerLock.Unlock()
// copy argument into a new map to ensure caller can't mistakenly
// hold on to a reference and cause a concurrent map modification panic
newTags := make(map[string]string, len(tags))
for k, v := range tags {
newTags[k] = v
}
ft.tags.Store(&newTags)
}