github.com/MikyChow/arbitrum-go-ethereum@v0.0.0-20230306102812-078da49636de/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 // This is a duplicated and slightly modified version of "gopkg.in/karalabe/cookiejar.v2/collections/prque". 10 11 // Package prque implements a priority queue data structure supporting arbitrary 12 // value types and int64 priorities. 13 // 14 // If you would like to use a min-priority queue, simply negate the priorities. 15 // 16 // Internally the queue is based on the standard heap package working on a 17 // sortable version of the block based stack. 18 package prque 19 20 import ( 21 "container/heap" 22 ) 23 24 // Priority queue data structure. 25 type Prque struct { 26 cont *sstack 27 } 28 29 // New creates a new priority queue. 30 func New(setIndex SetIndexCallback) *Prque { 31 return &Prque{newSstack(setIndex, false)} 32 } 33 34 // NewWrapAround creates a new priority queue with wrap-around priority handling. 35 func NewWrapAround(setIndex SetIndexCallback) *Prque { 36 return &Prque{newSstack(setIndex, true)} 37 } 38 39 // Pushes a value with a given priority into the queue, expanding if necessary. 40 func (p *Prque) Push(data interface{}, priority int64) { 41 heap.Push(p.cont, &item{data, priority}) 42 } 43 44 // Peek returns the value with the greatest priority but does not pop it off. 45 func (p *Prque) Peek() (interface{}, int64) { 46 item := p.cont.blocks[0][0] 47 return item.value, item.priority 48 } 49 50 // Pops the value with the greatest priority off the stack and returns it. 51 // Currently no shrinking is done. 52 func (p *Prque) Pop() (interface{}, int64) { 53 item := heap.Pop(p.cont).(*item) 54 return item.value, item.priority 55 } 56 57 // Pops only the item from the queue, dropping the associated priority value. 58 func (p *Prque) PopItem() interface{} { 59 return heap.Pop(p.cont).(*item).value 60 } 61 62 // Remove removes the element with the given index. 63 func (p *Prque) Remove(i int) interface{} { 64 if i < 0 { 65 return nil 66 } 67 return heap.Remove(p.cont, i) 68 } 69 70 // Checks whether the priority queue is empty. 71 func (p *Prque) Empty() bool { 72 return p.cont.Len() == 0 73 } 74 75 // Returns the number of element in the priority queue. 76 func (p *Prque) Size() int { 77 return p.cont.Len() 78 } 79 80 // Clears the contents of the priority queue. 81 func (p *Prque) Reset() { 82 *p = *New(p.cont.setIndex) 83 }