github.com/dominant-strategies/go-quai@v0.28.2/common/prque/prque.go (about) 1 // CookieJar - A contestant's algorithm toolbox 2 // Copyright (c) 2013 Peter Szilagyi. All rights reserved. 3 // 4 // CookieJar is dual licensed: use of this source code is governed by a BSD 5 // license that can be found in the LICENSE file. Alternatively, the CookieJar 6 // toolbox may be used in accordance with the terms and conditions contained 7 // in a signed written agreement between you and the author(s). 8 9 // Package prque implements a priority queue data structure supporting arbitrary 10 // value types and int64 priorities. 11 // 12 // If you would like to use a min-priority queue, simply negate the priorities. 13 // 14 // Internally the queue is based on the standard heap package working on a 15 // sortable version of the block based stack. 16 package prque 17 18 import ( 19 "container/heap" 20 ) 21 22 // Priority queue data structure. 23 type Prque struct { 24 cont *sstack 25 } 26 27 // New creates a new priority queue. 28 func New(setIndex SetIndexCallback) *Prque { 29 return &Prque{newSstack(setIndex, false)} 30 } 31 32 // NewWrapAround creates a new priority queue with wrap-around priority handling. 33 func NewWrapAround(setIndex SetIndexCallback) *Prque { 34 return &Prque{newSstack(setIndex, true)} 35 } 36 37 // Pushes a value with a given priority into the queue, expanding if necessary. 38 func (p *Prque) Push(data interface{}, priority int64) { 39 heap.Push(p.cont, &item{data, priority}) 40 } 41 42 // Peek returns the value with the greates priority but does not pop it off. 43 func (p *Prque) Peek() (interface{}, int64) { 44 item := p.cont.blocks[0][0] 45 return item.value, item.priority 46 } 47 48 // Pops the value with the greates priority off the stack and returns it. 49 // Currently no shrinking is done. 50 func (p *Prque) Pop() (interface{}, int64) { 51 item := heap.Pop(p.cont).(*item) 52 return item.value, item.priority 53 } 54 55 // Pops only the item from the queue, dropping the associated priority value. 56 func (p *Prque) PopItem() interface{} { 57 return heap.Pop(p.cont).(*item).value 58 } 59 60 // Remove removes the element with the given index. 61 func (p *Prque) Remove(i int) interface{} { 62 if i < 0 { 63 return nil 64 } 65 return heap.Remove(p.cont, i) 66 } 67 68 // Checks whether the priority queue is empty. 69 func (p *Prque) Empty() bool { 70 return p.cont.Len() == 0 71 } 72 73 // Returns the number of element in the priority queue. 74 func (p *Prque) Size() int { 75 return p.cont.Len() 76 } 77 78 // Clears the contents of the priority queue. 79 func (p *Prque) Reset() { 80 *p = *New(p.cont.setIndex) 81 }