github.com/yankunsam/loki/v2@v2.6.3-0.20220817130409-389df5235c27/pkg/storage/stores/tsdb/index/postingsstats.go (about) 1 // Copyright 2019 The Prometheus Authors 2 // Licensed under the Apache License, Version 2.0 (the "License"); 3 // you may not use this file except in compliance with the License. 4 // You may obtain a copy of the License at 5 // 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package index 15 16 import ( 17 "math" 18 "sort" 19 ) 20 21 // Stat holds values for a single cardinality statistic. 22 type Stat struct { 23 Name string 24 Count uint64 25 } 26 27 type maxHeap struct { 28 maxLength int 29 minValue uint64 30 minIndex int 31 Items []Stat 32 } 33 34 func (m *maxHeap) init(len int) { 35 m.maxLength = len 36 m.minValue = math.MaxUint64 37 m.Items = make([]Stat, 0, len) 38 } 39 40 func (m *maxHeap) push(item Stat) { 41 if len(m.Items) < m.maxLength { 42 if item.Count < m.minValue { 43 m.minValue = item.Count 44 m.minIndex = len(m.Items) 45 } 46 m.Items = append(m.Items, item) 47 return 48 } 49 if item.Count < m.minValue { 50 return 51 } 52 53 m.Items[m.minIndex] = item 54 m.minValue = item.Count 55 56 for i, stat := range m.Items { 57 if stat.Count < m.minValue { 58 m.minValue = stat.Count 59 m.minIndex = i 60 } 61 } 62 } 63 64 func (m *maxHeap) get() []Stat { 65 sort.Slice(m.Items, func(i, j int) bool { 66 return m.Items[i].Count > m.Items[j].Count 67 }) 68 return m.Items 69 }