2019-11-04 18:06:13 -08:00
|
|
|
// Copyright 2019 The Prometheus Authors
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
2020-04-15 03:17:41 -07:00
|
|
|
|
2019-11-04 18:06:13 -08:00
|
|
|
package index
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math"
|
2023-07-02 15:16:26 -07:00
|
|
|
|
|
|
|
"golang.org/x/exp/slices"
|
2019-11-04 18:06:13 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
// Stat holds values for a single cardinality statistic.
|
|
|
|
type Stat struct {
|
|
|
|
Name string
|
|
|
|
Count uint64
|
|
|
|
}
|
|
|
|
|
|
|
|
type maxHeap struct {
|
|
|
|
maxLength int
|
|
|
|
minValue uint64
|
|
|
|
minIndex int
|
|
|
|
Items []Stat
|
|
|
|
}
|
|
|
|
|
2023-04-09 00:08:40 -07:00
|
|
|
func (m *maxHeap) init(length int) {
|
|
|
|
m.maxLength = length
|
2019-11-04 18:06:13 -08:00
|
|
|
m.minValue = math.MaxUint64
|
2023-04-09 00:08:40 -07:00
|
|
|
m.Items = make([]Stat, 0, length)
|
2019-11-04 18:06:13 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *maxHeap) push(item Stat) {
|
|
|
|
if len(m.Items) < m.maxLength {
|
|
|
|
if item.Count < m.minValue {
|
|
|
|
m.minValue = item.Count
|
|
|
|
m.minIndex = len(m.Items)
|
|
|
|
}
|
|
|
|
m.Items = append(m.Items, item)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if item.Count < m.minValue {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
m.Items[m.minIndex] = item
|
|
|
|
m.minValue = item.Count
|
|
|
|
|
|
|
|
for i, stat := range m.Items {
|
|
|
|
if stat.Count < m.minValue {
|
|
|
|
m.minValue = stat.Count
|
|
|
|
m.minIndex = i
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *maxHeap) get() []Stat {
|
2023-09-21 13:53:51 -07:00
|
|
|
slices.SortFunc(m.Items, func(a, b Stat) int { return int(b.Count - a.Count) })
|
2019-11-04 18:06:13 -08:00
|
|
|
return m.Items
|
|
|
|
}
|