Scoop API

scoop:scoop.std:0.1.0

src/collections/priority_queue.scoop

Selected production source · src/collections/priority_queue.scoop

1package scoop.collections
3import scoop.comparisons.Comparator
5/**
6 * A binary min-heap ordered by its comparator. Removal returns the smallest element; iteration
7 * exposes heap order, not sorted order. Structural changes invalidate iterators.
8 */
9public class PriorityQueue<T> public constructor(
10 /**
11 * The comparator used for ordering and, for ordered maps/sets, equivalence.
12 */
13 public val comparator: Comparator<T>) : Collection<T> {
14 private var storage: ElementBuffer<T> = ElementBuffer<T>(8L)
15 private var elementCount: Long = 0L
16 private val structure: ModificationCounter = ModificationCounter()
17 /**
18 * The number of queued elements, including duplicates.
19 */
20 public override val size: Long get() = elementCount
22 internal fun elementAt(index: Long): T = storage.read(index)
24 private fun compare(left: T, right: T, stamp: RevisionStamp): Long {
25 val result = comparator.compare(left, right)
26 structure.check(stamp)
27 return result
28 }
30 private fun ensureRoom() {
31 if (elementCount < storage.capacity) return
32 val replacement = ElementBuffer<T>(expandedCollectionCapacity(storage.capacity))
33 var index = 0L
34 while (index < elementCount) { replacement.write(index, storage.read(index)); index += 1L }
35 storage = replacement
36 }
38 /**
39 * Inserts an element while preserving the heap ordering.
40 */
41 public fun add(element: T) {
42 val stamp = structure.snapshot()
43 var destination = elementCount
44 while (destination > 0L) {
45 val parent = (destination - 1L) / 2L
46 if (compare(element, storage.read(parent), stamp) >= 0L) break
47 destination = parent
48 }
49 ensureRoom()
50 var index = elementCount
51 while (index > destination) {
52 val parent = (index - 1L) / 2L
53 storage.write(index, storage.read(parent))
54 index = parent
55 }
56 storage.write(destination, element)
57 elementCount += 1L
58 structure.advance()
59 }
61 /**
62 * Returns the smallest element without removal; an empty queue throws NoSuchElementException.
63 */
64 public fun peek(): T {
65 if (elementCount == 0L) throw NoSuchElementException("empty priority queue")
66 return storage.read(0L)
67 }
69 /**
70 * Returns the smallest element without removal, or None when empty.
71 */
72 public fun peekOrNone(): T? = if (elementCount == 0L) None else Some(storage.read(0L))
73 /**
74 * Removes the smallest element, or returns None when empty.
75 */
76 public fun removeFirstOrNone(): T? = if (elementCount == 0L) None else Some(removeFirst())
78 /**
79 * Removes the smallest element; an empty queue throws NoSuchElementException.
80 */
81 public fun removeFirst(): T {
82 if (elementCount == 0L) throw NoSuchElementException("empty priority queue")
83 val result = storage.read(0L)
84 val remaining = elementCount - 1L
85 if (remaining > 0L) {
86 val last = storage.read(remaining)
87 val stamp = structure.snapshot()
88 var destination = 0L
89 var mask = 1L
90 while (destination < remaining / 2L) {
91 var child = destination * 2L + 1L
92 if (child + 1L < remaining && compare(storage.read(child + 1L), storage.read(child), stamp) < 0L) child += 1L
93 if (compare(last, storage.read(child), stamp) <= 0L) break
94 destination = child
95 mask *= 2L
96 }
97 // The bits of destination + 1 encode the root-to-node path.
98 var index = 0L
99 mask /= 2L
100 while (mask > 0L) {
101 val child = index * 2L + 1L + ((destination + 1L) / mask) % 2L
102 storage.write(index, storage.read(child))
103 index = child
104 mask /= 2L
105 }
106 storage.write(destination, last)
107 }
108 storage.erase(remaining)
109 elementCount = remaining
110 structure.advance()
111 return result
112 }
114 /**
115 * Removes all elements.
116 */
117 public fun clear() {
118 if (elementCount == 0L) return
119 var index = 0L
120 while (index < elementCount) { storage.erase(index); index += 1L }
121 elementCount = 0L
122 structure.advance()
123 }
125 /**
126 * Iterates in heap storage order, which is not sorted; structural changes invalidate the
127 * iterator.
128 */
129 public override operator fun iterator(): Iterator<T> = HeapIterator<T>(this, structure)
131 /**
132 * Serialization factories using explicit element or key/value codecs.
133 */
134 public companion object {
135 /**
136 * Encodes entries or elements in iteration order using the supplied component codecs.
137 */
138 public fun encoder(element: ValueEncoder<T>): ValueEncoder<PriorityQueue<T>> =
139 ValueEncoderFunction<PriorityQueue<T>> { values, encoder -> encodeElements(values, element, encoder) }
140 /**
141 * Decodes entries or elements into a new collection using the supplied component codecs
142 * and comparator where required.
143 */
144 public fun decoder(element: ValueDecoder<T>, comparator: Comparator<T>): ValueDecoder<PriorityQueue<T>> = ValueDecoderFunction<PriorityQueue<T>> { decoder ->
145 val result = PriorityQueue<T>(comparator)
146 decodeElements(decoder, element) { value -> result.add(value) }
147 result
148 }
149 }