tendermint/common/heap.go

104 lines
1.9 KiB
Go
Raw Normal View History

2014-06-16 22:37:42 -07:00
package common
import (
2014-07-01 14:50:24 -07:00
"container/heap"
2014-06-16 22:37:42 -07:00
)
2014-08-10 16:35:08 -07:00
type Comparable interface {
Less(o interface{}) bool
}
//-----------------------------------------------------------------------------
2014-10-06 00:15:37 -07:00
/*
Example usage:
h := NewHeap()
h.Push(String("msg1"), 1)
h.Push(String("msg3"), 3)
h.Push(String("msg2"), 2)
fmt.Println(h.Pop())
fmt.Println(h.Pop())
fmt.Println(h.Pop())
*/
2014-06-16 22:37:42 -07:00
type Heap struct {
2014-07-01 14:50:24 -07:00
pq priorityQueue
2014-06-16 22:37:42 -07:00
}
func NewHeap() *Heap {
2014-07-01 14:50:24 -07:00
return &Heap{pq: make([]*pqItem, 0)}
2014-06-16 22:37:42 -07:00
}
func (h *Heap) Len() int64 {
2014-08-10 16:35:08 -07:00
return int64(len(h.pq))
2014-06-16 22:37:42 -07:00
}
2014-08-10 16:35:08 -07:00
func (h *Heap) Push(value interface{}, priority Comparable) {
2014-07-01 14:50:24 -07:00
heap.Push(&h.pq, &pqItem{value: value, priority: priority})
2014-06-16 22:37:42 -07:00
}
2014-08-10 16:35:08 -07:00
func (h *Heap) Peek() interface{} {
if len(h.pq) == 0 {
return nil
}
return h.pq[0].value
}
func (h *Heap) Update(value interface{}, priority Comparable) {
h.pq.Update(h.pq[0], value, priority)
}
2014-06-16 22:37:42 -07:00
func (h *Heap) Pop() interface{} {
2014-07-01 14:50:24 -07:00
item := heap.Pop(&h.pq).(*pqItem)
return item.value
2014-08-10 16:35:08 -07:00
}
//-----------------------------------------------------------------------------
2014-06-16 22:37:42 -07:00
///////////////////////
// From: http://golang.org/pkg/container/heap/#example__priorityQueue
type pqItem struct {
2014-07-01 14:50:24 -07:00
value interface{}
2014-08-10 16:35:08 -07:00
priority Comparable
2014-07-01 14:50:24 -07:00
index int
2014-06-16 22:37:42 -07:00
}
type priorityQueue []*pqItem
func (pq priorityQueue) Len() int { return len(pq) }
func (pq priorityQueue) Less(i, j int) bool {
2014-08-10 16:35:08 -07:00
return pq[i].priority.Less(pq[j].priority)
2014-06-16 22:37:42 -07:00
}
func (pq priorityQueue) Swap(i, j int) {
2014-07-01 14:50:24 -07:00
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
2014-06-16 22:37:42 -07:00
}
func (pq *priorityQueue) Push(x interface{}) {
2014-07-01 14:50:24 -07:00
n := len(*pq)
item := x.(*pqItem)
item.index = n
*pq = append(*pq, item)
2014-06-16 22:37:42 -07:00
}
func (pq *priorityQueue) Pop() interface{} {
2014-07-01 14:50:24 -07:00
old := *pq
n := len(old)
item := old[n-1]
item.index = -1 // for safety
*pq = old[0 : n-1]
return item
2014-06-16 22:37:42 -07:00
}
2014-08-10 16:35:08 -07:00
func (pq *priorityQueue) Update(item *pqItem, value interface{}, priority Comparable) {
2014-07-01 14:50:24 -07:00
item.value = value
item.priority = priority
heap.Fix(pq, item.index)
2014-06-16 22:37:42 -07:00
}