github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/storage/tree/labels_cache.go (about) 1 package tree 2 3 // sample type -> labels hash -> entry 4 type LabelsCache map[int64]map[uint64]*LabelsCacheEntry 5 6 type LabelsCacheEntry struct { 7 Labels 8 *Tree 9 } 10 11 func NewCacheEntry(l Labels) *LabelsCacheEntry { 12 return &LabelsCacheEntry{Tree: New(), Labels: CopyLabels(l)} 13 } 14 15 func (c LabelsCache) GetOrCreateTree(sampleType int64, l Labels) *LabelsCacheEntry { 16 p, ok := c[sampleType] 17 if !ok { 18 e := NewCacheEntry(l) 19 c[sampleType] = map[uint64]*LabelsCacheEntry{l.Hash(): e} 20 return e 21 } 22 h := l.Hash() 23 e, found := p[h] 24 if !found { 25 e = NewCacheEntry(l) 26 p[h] = e 27 } 28 return e 29 } 30 31 func (c LabelsCache) GetOrCreateTreeByHash(sampleType int64, l Labels, h uint64) *LabelsCacheEntry { 32 p, ok := c[sampleType] 33 if !ok { 34 e := NewCacheEntry(l) 35 c[sampleType] = map[uint64]*LabelsCacheEntry{h: e} 36 return e 37 } 38 e, found := p[h] 39 if !found { 40 e = NewCacheEntry(l) 41 p[h] = e 42 } 43 return e 44 } 45 46 func (c LabelsCache) Get(sampleType int64, h uint64) (*LabelsCacheEntry, bool) { 47 p, ok := c[sampleType] 48 if !ok { 49 return nil, false 50 } 51 x, ok := p[h] 52 return x, ok 53 } 54 55 func (c LabelsCache) Put(sampleType int64, e *LabelsCacheEntry) { 56 p, ok := c[sampleType] 57 if !ok { 58 p = make(map[uint64]*LabelsCacheEntry) 59 c[sampleType] = p 60 } 61 p[e.Hash()] = e 62 } 63 64 func (c LabelsCache) Remove(sampleType int64, h uint64) { 65 p, ok := c[sampleType] 66 if !ok { 67 return 68 } 69 delete(p, h) 70 if len(p) == 0 { 71 delete(c, sampleType) 72 } 73 } 74 75 func CopyLabels(labels Labels) Labels { 76 l := make(Labels, len(labels)) 77 for i, v := range labels { 78 l[i] = CopyLabel(v) 79 } 80 return l 81 } 82 83 // CutLabel creates a copy of labels without label i. 84 func CutLabel(labels Labels, i int) Labels { 85 c := make(Labels, 0, len(labels)-1) 86 for j, label := range labels { 87 if i != j { 88 c = append(c, CopyLabel(label)) 89 } 90 } 91 return c 92 } 93 94 func CopyLabel(label *Label) *Label { 95 return &Label{ 96 Key: label.Key, 97 Str: label.Str, 98 Num: label.Num, 99 NumUnit: label.NumUnit, 100 } 101 }