Scoop API

scoop:scoop.std:0.1.0

src/collections/hash_map.scoop

Selected production source · src/collections/hash_map.scoop

1package scoop.collections
3internal enum HashProbe {
4 Found(Long, ULong),
5 Absent(Long, ULong)
6}
8/**
9 * A mutable hash table using key equality and hash codes. Keys must retain consistent equality and
10 * hashes while stored; iteration order is unspecified.
11 */
12public class HashMap<K, V> public constructor(): MutableMap<K, V>
13where K: Equals<K>, K: Hash {
14 private var storage: HashStorage<K, V> = HashStorage<K, V>(8L)
15 private var elementCount: Long = 0L
16 private var occupied: Long = 0L
17 private val changes: ModificationCounter = ModificationCounter()
18 private val structure: ModificationCounter = ModificationCounter()
20 /**
21 * The number of key-value associations.
22 */
23 public override val size: Long get() = elementCount
24 /**
25 * A read-only view of the map's current keys.
26 */
27 public override val keys: Set<K> get() = MapKeys<K, V>(this)
28 /**
29 * A read-only view of current values, retaining duplicates.
30 */
31 public override val values: Collection<V> get() = MapValues<K, V>(this)
32 /**
33 * A read-only view of current key-value entries.
34 */
35 public override val entries: Collection<Map.Entry<K, V>> get() = MapEntries<K, V>(this)
37 internal fun locate(key: K): HashProbe {
38 val stamp = changes.snapshot()
39 val mixedHash = hashMixed(key.hash())
40 changes.check(stamp)
41 val h2 = hashH2(mixedHash)
42 var group = storage.startGroup(mixedHash)
43 var step = 0L
44 var visited = 0L
45 var firstDeleted = -1L
46 while (visited < storage.groupCount) {
47 val controls = storage.word(group)
48 var candidates = hashControlMatches(controls, h2)
49 while (candidates != 0uL) {
50 val offset = hashLowestMatch(candidates)
51 candidates = candidates and (candidates - 1uL)
52 if (hashControlAt(controls, offset) == h2) {
53 val index = storage.index(group, offset)
54 val entry = storage.read(index)
55 if (entry.mixedHash != mixedHash)
56 continue
57 val equal = entry.key == key
58 changes.check(stamp)
59 if (equal)
60 return HashProbe.Found(index, mixedHash)
61 }
62 }
63 if (firstDeleted < 0L) {
64 val deleted = hashControlMatches(controls, 0xfeuL)
65 if (deleted != 0uL)
66 firstDeleted = storage.index(group, hashLowestMatch(deleted))
67 }
68 val empty = hashControlMatches(controls, 0x80uL)
69 if (empty != 0uL) {
70 val vacant =
71 if (firstDeleted >= 0L)
72 firstDeleted
73 else
74 storage.index(group, hashLowestMatch(empty))
75 return HashProbe.Absent(vacant, mixedHash)
76 }
77 step += 1L
78 group = (group + step) and storage.groupMask
79 visited += 1L
80 }
81 if (firstDeleted >= 0L)
82 return HashProbe.Absent(firstDeleted, mixedHash)
83 throw IllegalStateException(Some("hash table has no vacant slot"))
84 }
86 /**
87 * Returns the value associated with the key, or None when absent.
88 */
89 public override operator fun get(key: K): V? {
90 return when (val probe = locate(key)) {
91 case HashProbe.Found(val index, _) -> Some(storage.read(index).value)
92 case HashProbe.Absent(_, _) -> None
93 }
94 }
96 /**
97 * Tests whether the key has an association.
98 */
99 public override fun containsKey(key: K): Boolean =
100 when (locate(key)) {
101 case HashProbe.Found(_, _) -> true
102 case HashProbe.Absent(_, _) -> false
103 }
105 private fun prepareVacant(index: Long, mixedHash: ULong): (Long, Boolean) {
106 if (storage.isDeleted(index))
107 return (index, false)
108 val capacity = storage.capacity
109 if (occupied < capacity - capacity / 4L)
110 return (index, true)
111 val nextCapacity =
112 if (elementCount < capacity / 2L)
113 capacity
114 else {
115 if (capacity > Long.MAX_VALUE / 2L)
116 throw ArithmeticException()
117 capacity * 2L
118 }
119 storage = storage.rehashed(nextCapacity)
120 occupied = elementCount
121 return (storage.vacant(mixedHash), true)
122 }
124 /**
125 * Associates the value with the key and returns the previous value, or None for a new key.
126 */
127 public override fun put(key: K, value: V): V? = putEntry(key, value, true)
129 internal fun putIfAbsent(key: K, value: V): V? = putEntry(key, value, false)
131 private fun putEntry(key: K, value: V, replace: Boolean): V? {
132 return when (val probe = locate(key)) {
133 case HashProbe.Found(val index, _) -> {
134 val old = storage.read(index)
135 if (replace) {
136 storage.replace(index, HashEntry<K, V>(old.key, value, old.mixedHash))
137 changes.advance()
138 }
139 Some(old.value)
140 }
141 case HashProbe.Absent(val index, val mixedHash) -> {
142 insertAbsent(key, value, index, mixedHash)
143 None
144 }
145 }
146 }
148 // The caller has completed lookup; no user callbacks run while committing.
149 internal fun insertAbsent(key: K, value: V, index: Long, mixedHash: ULong) {
150 val(target, consumesEmpty) = prepareVacant(index, mixedHash)
151 if (consumesEmpty)
152 occupied += 1L
153 storage.write(target, HashEntry<K, V>(key, value, mixedHash))
154 elementCount += 1L
155 changes.advance()
156 structure.advance()
157 }
159 /**
160 * Removes the key and returns its former value, or None if absent.
161 */
162 public override fun remove(key: K): V? {
163 return when (val probe = locate(key)) {
164 case HashProbe.Found(val index, _) -> Some(removeAt(index))
165 case HashProbe.Absent(_, _) -> None
166 }
167 }
169 internal fun valueAt(index: Long): V = storage.read(index).value
171 internal fun removeAt(index: Long): V {
172 val value = storage.read(index).value
173 if (storage.erase(index))
174 occupied -= 1L
175 elementCount -= 1L
176 changes.advance()
177 structure.advance()
178 return value
179 }
181 /**
182 * Removes every association.
183 */
184 public override fun clear() {
185 if (elementCount == 0L)
186 return
187 storage.cleared()
188 elementCount = 0L
189 occupied = 0L
190 changes.advance()
191 structure.advance()
192 }
194 /**
195 * Iterates key-value entries in this map's order; structural changes invalidate the iterator.
196 */
197 public override operator fun iterator(): Iterator<Map.Entry<K, V>> =
198 HashIterator<K, V>(this, structure)
200 internal val table: HashStorage<K, V> get() = storage
202 /**
203 * Serialization through component companions or explicit key/value codecs.
204 */
205 public companion object {
206 /**
207 * Encodes entries or elements in iteration order using the supplied component codecs.
208 */
209 public fun encoder(key: ValueEncoder<K>, value: ValueEncoder<V>): ValueEncoder<
210 HashMap<K, V>
211 > =
212 ValueEncoderFunction<HashMap<K, V>> {
213 values,
214 encoder -> encodeMap(values, key, value, encoder)
215 }
216 /**
217 * Decodes entries or elements into a new collection using the supplied component codecs
218 * and comparator where required.
219 */
220 public fun decoder(key: ValueDecoder<K>, value: ValueDecoder<V>): ValueDecoder<
221 HashMap<K, V>
222 > =
223 ValueDecoderFunction<HashMap<K, V>> {
224 decoder ->
225 val result = HashMap<K, V>()
226 decodeMapInto(decoder, key, value, result)
227 result
228 }
230 override interface ValueEncoder<HashMap<K, V>>
231 where K.Companion: ValueEncoder<K>, V.Companion: ValueEncoder<V> {
232 /**
233 * Encodes entries using the key and value companions in iteration order.
234 */
235 public override fun encode(value: HashMap<K, V>, encoder: Encoder): Unit =
236 encodeMap(value, K.Companion, V.Companion, encoder)
237 }
239 override interface ValueDecoder<HashMap<K, V>>
240 where K.Companion: ValueDecoder<K>, V.Companion: ValueDecoder<V> {
241 /**
242 * Decodes entries using the key and value companions into a new map.
243 */
244 public override fun decode(decoder: Decoder): HashMap<K, V> {
245 val result = HashMap<K, V>()
246 decodeMapInto(decoder, K.Companion, V.Companion, result)
247 return result
248 }
249 }
250 }
253internal class HashIterator<K, V> internal constructor(
254 private val source: HashMap<K, V>,
255 private val structure: ModificationCounter
256): Iterator<Map.Entry<K, V>> where K: Equals<K>, K: Hash {
257 private val stamp: RevisionStamp = structure.snapshot()
258 private var index: Long = 0L
259 private var controls: ULong = 0uL
260 private var exhausted: Boolean = false
262 public override fun next(): Map.Entry<K, V>? {
263 if (exhausted)
264 return None
265 structure.check(stamp)
266 val storage = source.table
267 while (index < storage.capacity) {
268 val current = index
269 val offset = current % 8L
270 if (offset == 0L)
271 controls = storage.word(current / 8L)
272 index += 1L
273 if (hashControlAt(controls, offset) < 0x80uL) {
274 val entry = storage.read(current)
275 return Some(Map.Entry<K, V>(entry.key, entry.value))
276 }
277 }
278 exhausted = true
279 return None
280 }