2024-03-28 12:53:26 +00:00
|
|
|
package pilorama
|
|
|
|
|
|
|
|
import (
|
|
|
|
"container/heap"
|
2024-08-23 07:58:33 +00:00
|
|
|
"slices"
|
|
|
|
"strings"
|
2024-03-28 12:53:26 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type heapInfo struct {
|
2024-07-10 06:30:01 +00:00
|
|
|
id MultiNode
|
2024-03-28 12:53:26 +00:00
|
|
|
filename string
|
|
|
|
}
|
|
|
|
|
|
|
|
type filenameHeap []heapInfo
|
|
|
|
|
|
|
|
func (h filenameHeap) Len() int { return len(h) }
|
|
|
|
func (h filenameHeap) Less(i, j int) bool { return h[i].filename < h[j].filename }
|
|
|
|
func (h filenameHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
|
|
|
|
func (h *filenameHeap) Push(x any) {
|
|
|
|
*h = append(*h, x.(heapInfo))
|
|
|
|
}
|
2024-04-03 08:44:02 +00:00
|
|
|
|
2024-03-28 12:53:26 +00:00
|
|
|
func (h *filenameHeap) Pop() any {
|
|
|
|
old := *h
|
|
|
|
n := len(old)
|
|
|
|
x := old[n-1]
|
|
|
|
*h = old[0 : n-1]
|
|
|
|
return x
|
|
|
|
}
|
|
|
|
|
|
|
|
// fixedHeap maintains a fixed number of smallest elements started at some point.
|
|
|
|
type fixedHeap struct {
|
2024-08-23 07:58:33 +00:00
|
|
|
start *string
|
|
|
|
sorted bool
|
|
|
|
count int
|
|
|
|
h *filenameHeap
|
2024-03-28 12:53:26 +00:00
|
|
|
}
|
|
|
|
|
2024-04-04 07:40:21 +00:00
|
|
|
func newHeap(start *string, count int) *fixedHeap {
|
2024-03-28 12:53:26 +00:00
|
|
|
h := new(filenameHeap)
|
|
|
|
heap.Init(h)
|
|
|
|
|
|
|
|
return &fixedHeap{
|
|
|
|
start: start,
|
|
|
|
count: count,
|
|
|
|
h: h,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-23 07:58:33 +00:00
|
|
|
const amortizationMultiplier = 5
|
|
|
|
|
2024-07-10 06:30:01 +00:00
|
|
|
func (h *fixedHeap) push(id MultiNode, filename string) bool {
|
2024-04-04 07:40:21 +00:00
|
|
|
if h.start != nil && filename <= *h.start {
|
2024-03-28 12:53:26 +00:00
|
|
|
return false
|
|
|
|
}
|
2024-08-23 07:58:33 +00:00
|
|
|
|
|
|
|
*h.h = append(*h.h, heapInfo{id: id, filename: filename})
|
|
|
|
h.sorted = false
|
|
|
|
|
|
|
|
if h.h.Len() > h.count*amortizationMultiplier {
|
|
|
|
slices.SortFunc(*h.h, func(a, b heapInfo) int {
|
|
|
|
return strings.Compare(a.filename, b.filename)
|
|
|
|
})
|
|
|
|
*h.h = (*h.h)[:h.count]
|
2024-03-28 12:53:26 +00:00
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *fixedHeap) pop() (heapInfo, bool) {
|
2024-08-23 07:58:33 +00:00
|
|
|
if !h.sorted {
|
|
|
|
slices.SortFunc(*h.h, func(a, b heapInfo) int {
|
|
|
|
return strings.Compare(a.filename, b.filename)
|
|
|
|
})
|
|
|
|
if len(*h.h) > h.count {
|
|
|
|
*h.h = (*h.h)[:h.count]
|
|
|
|
}
|
|
|
|
h.sorted = true
|
|
|
|
}
|
|
|
|
if len(*h.h) != 0 {
|
|
|
|
info := (*h.h)[0]
|
|
|
|
*h.h = (*h.h)[1:]
|
|
|
|
return info, true
|
2024-03-28 12:53:26 +00:00
|
|
|
}
|
|
|
|
return heapInfo{}, false
|
|
|
|
}
|