arnaucube
arnaucube/gogame-oldPublic Self-hosted repository
gogame-old/queue/queue.go
queue/queue.goRaw
 1package queue
 2
 3import (
 4	"container/heap"
 5)
 6
 7// An Item is something we manage in a priority queue.
 8type Item struct {
 9	value    string // id of the item in the full db
10	priority int64  // timestamp of the item in the queue.
11	// The index is needed by update and is maintained by the heap.Interface methods.
12	index int // the index of the item in the heap.
13}
14
15// A PriorityQueue implements heap.Interface and holds Items.
16type PriorityQueue []*Item
17
18func (pq PriorityQueue) Len() int { return len(pq) }
19
20func (pq PriorityQueue) Less(i, j int) bool {
21	// We want Pop to give us the lowest, not highest, priority so we use smaller than here.
22	return pq[i].priority < pq[j].priority
23}
24
25func (pq PriorityQueue) Swap(i, j int) {
26	pq[i], pq[j] = pq[j], pq[i]
27	pq[i].index = i
28	pq[j].index = j
29}
30
31func (pq *PriorityQueue) Push(x interface{}) {
32	n := len(*pq)
33	item := x.(*Item)
34	item.index = n
35	*pq = append(*pq, item)
36}
37
38func (pq *PriorityQueue) Pop() interface{} {
39	old := *pq
40	n := len(old)
41	item := old[n-1]
42	item.index = -1 // for safety
43	*pq = old[0 : n-1]
44	return item
45}
46
47func (pq *PriorityQueue) Look() *Item {
48	if len(*pq) == 0 {
49		return nil
50	}
51	old := *pq
52	item := old[0]
53	return item
54}
55
56// update modifies the priority and value of an Item in the queue.
57func (pq *PriorityQueue) update(item *Item, value string, priority int64) {
58	item.value = value
59	item.priority = priority
60	heap.Fix(pq, item.index)
61}