47 lines
959 B
Go
47 lines
959 B
Go
|
package fusenrender
|
||
|
|
||
|
import "bytes"
|
||
|
|
||
|
// An Slice is something we manage in a priority queue.
|
||
|
type Slice[T any] struct {
|
||
|
Key []byte // 键
|
||
|
Value T // 值
|
||
|
// 索引是在容器中的位置
|
||
|
index int
|
||
|
}
|
||
|
|
||
|
// A PriorityQueue implements heap.Interface and holds Items.
|
||
|
type PriorityQueue[T any] []*Slice[T]
|
||
|
|
||
|
func (pq PriorityQueue[T]) Len() int { return len(pq) }
|
||
|
|
||
|
func (pq PriorityQueue[T]) Less(i, j int) bool {
|
||
|
// 使用字节数组键比较
|
||
|
return bytes.Compare(pq[i].Key, pq[j].Key) < 0
|
||
|
}
|
||
|
|
||
|
func (pq PriorityQueue[T]) Swap(i, j int) {
|
||
|
pq[i], pq[j] = pq[j], pq[i]
|
||
|
pq[i].index = i
|
||
|
pq[j].index = j
|
||
|
}
|
||
|
|
||
|
func (pq *PriorityQueue[T]) Push(x any) {
|
||
|
n := len(*pq)
|
||
|
item := x.(*Slice[T])
|
||
|
item.index = n
|
||
|
*pq = append(*pq, item)
|
||
|
}
|
||
|
|
||
|
func (pq *PriorityQueue[T]) Pop() any {
|
||
|
old := *pq
|
||
|
n := len(old)
|
||
|
item := old[n-1]
|
||
|
old[n-1] = nil
|
||
|
item.index = -1
|
||
|
*pq = old[0 : n-1]
|
||
|
return item.Value
|
||
|
}
|
||
|
|
||
|
// 这样就可以支持基于[]byte键的优先队列操作了
|