github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/structs/cappedarr/cappedarr.go (about) 1 package cappedarr 2 3 import ( 4 "sort" 5 ) 6 7 type CappedArray struct { 8 len int 9 maxSize int 10 values []uint64 11 } 12 13 func New(maxSize int) *CappedArray { 14 return &CappedArray{ 15 len: 0, 16 maxSize: maxSize, 17 values: make([]uint64, maxSize), 18 } 19 } 20 21 func (ca *CappedArray) MinValue() uint64 { 22 if ca.len == 0 { 23 return 0 24 } 25 return ca.values[ca.maxSize-ca.len] 26 } 27 28 func (ca *CappedArray) Push(v uint64) bool { 29 i := sort.Search(ca.len, func(i int) bool { 30 return ca.values[ca.maxSize-ca.len+i] >= v 31 }) 32 33 // log.Debug("---") 34 35 if i < 0 { 36 return false 37 } 38 39 if ca.len < ca.maxSize { 40 ca.len++ 41 } 42 43 // log.Debugf("maxSize %d len %d i %d v %d first val %d", ca.maxSize, ca.len, i, v, ca.values[0]) 44 45 if i >= ca.maxSize { 46 // log.Debug("case 1") 47 copy(ca.values[:i-1], ca.values[1:i]) 48 ca.values[i-1] = v 49 } else { 50 if i == 0 && v <= ca.values[0] { 51 // log.Debug("case 2") 52 return false 53 } 54 if v > ca.values[ca.maxSize-ca.len+i] { 55 // log.Debug("case 3") 56 if i != 0 { 57 l := ca.maxSize - ca.len 58 r := l + i 59 copy(ca.values[l:r], ca.values[l+1:r+1]) 60 } 61 ca.values[ca.maxSize-ca.len+i] = v 62 } else { 63 // log.Debug("case 4") 64 copy(ca.values[:i-1], ca.values[1:i]) 65 ca.values[ca.maxSize-ca.len+i-1] = v 66 } 67 } 68 // log.Debug("ca.values", ca.values) 69 70 // log.Debug(i) 71 72 // if i >= ca.len && ca.len < len(ca.values)-1 { 73 // ca.len += 1 74 // copy(ca.values[i+1:ca.len], ca.values[i:ca.len-1]) 75 // } else { 76 // copy(ca.values[:i-1], ca.values[1:i]) 77 // } 78 79 // ca.values[i] = v 80 return true 81 }