You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.4 KiB

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