Landin library reference discuss source
1import core/cmp
2import core/iter
3import core/mem
4
5slot_free: atom
6slot_used: atom
7slot_dead: atom
8slot_state: type = slot_free | slot_used | slot_dead
9
10--  Buckets are always initialized. Keys and values occupy two independent
11--  dense initialized prefixes, and each used/dead bucket names its prefix
12--  position. Used buckets also form a doubly linked walk in insertion order;
13--  the map's capacity is the end marker for every link. Reusing a tombstone
14--  replaces its dense position and appends it to that walk.
15bucket: type = struct
16    state: slot_state
17    dense_index: usize
18    previous_used: usize
19    next_used: usize
20end bucket
21
22map_value: type (key: type is cmp.hashable, item: type) = struct
23    buckets: mem.storage(bucket)
24    keys: mem.storage(key)
25    values: mem.storage(item)
26    count: usize
27    tombstones: usize
28    first_used: usize
29    last_used: usize
30    seed: cmp.hash_seed
31end map_value
32
33position_value: type = struct
34    next_slot: usize
35end position_value
36
37--  A representation of the module's own: spec.md's D354.
38--- Insertion-ordered hash map over slot metadata and dense key/value
39--- prefixes. Providers are supplied per operation. Its representation is the
40--- module's own, so nothing outside `core/map` can break the invariants its
41--- operations keep.
42---
43--- A map hashes its keys under the seed it was made with, and the hashes
44--- `core/cmp` ships are SipHash-1-3 keyed by it, so whoever does not know
45--- the seed cannot choose keys that share one probe chain. Seed a map
46--- keyed by outside data from entropy, as `random.hash_seed` draws one;
47--- a program without entropy gives a value its adversary cannot read. The
48--- seed changes nothing a lookup finds and not the order of a walk, only
49--- which slots the keys take, and so how many probes an operation makes
50--- and, after removals, whether a new key reuses a removed entry's slot
51--- or rebuilds the table, which `slots`, `removed` and `capacity` then
52--- report. A constant seed makes all of that the same on every run.
53public map: type (key: type is cmp.hashable, item: type) =
54    map_value(key, item)
55
56--- Position in an insertion-order entry walk. Start with `entries`; do not
57--- mutate the map during a walk.
58---
59--- A position is a manual live-bucket place, not an ownership or snapshot
60--- token: it has no map identity or generation check and is not
61--- transferable between maps. Any mutation, including insert, remove,
62--- rehash, clear and release, invalidates an active walk; callers must
63--- discard its position and restart.  Its slot is the module's own.
64public position: type = position_value
65
66--- A copied key/value pair returned by `next_entry`. References inside either
67--- value still depend on their original backing.
68public entry: type (key: type, item: type) = struct
69    key: key
70    item: item
71end entry
72
73empty_storage: (value: type) -> (result: mem.storage(value)) =
74    result = mem.empty_storage(item: value)
75end empty_storage
76
77--- Create an empty map without allocating backing, hashing its keys
78--- under `seed`.
79public new: (key: type is cmp.hashable, item: type, seed: cmp.hash_seed)
80            -> (result: map(key, item)) =
81    empty_buckets := empty_storage(value: bucket)
82    empty_keys := empty_storage(value: key)
83    empty_values := empty_storage(value: item)
84    result = (buckets: empty_buckets, keys: empty_keys,
85              values: empty_values, count: 0, tombstones: 0,
86              first_used: 0, last_used: 0, seed: seed)
87end new
88
89--- Return the number of live key/value entries.
90public length: (key: type is cmp.hashable, item: type,
91                value: map(key, item)) -> (count: usize) =
92    count = value.count
93end length
94
95--- Return how many entries the map holds before inserting a new key
96--- rebuilds it: three quarters of its hash slots. Removed entries occupy
97--- their slots until a rebuild, so after a removal the rebuild can come
98--- sooner.
99public capacity: (key: type is cmp.hashable, item: type,
100                  value: map(key, item)) -> (count: usize) =
101    count = crowding_threshold(slots(value))
102end capacity
103
104--- Return how many removed entries still hold their slots until the next
105--- rebuild, and so bring it sooner.
106public removed: (key: type is cmp.hashable, item: type,
107                 value: map(key, item)) -> (count: usize) =
108    count = value.tombstones
109end removed
110
111--- Return the number of hash slots, the table size `capacity` is three
112--- quarters of.
113public slots: (key: type is cmp.hashable, item: type,
114               value: map(key, item)) -> (count: usize) =
115    count = mem.capacity(value.buckets)
116end slots
117
118--- Create a position before the first entry. The walk follows current
119--- insertion order.
120public entries: () -> (at: position) =
121    --  This marker means "start at the map's head" until the first
122    --  `next_entry`. It is distinct from every possible bucket capacity and
123    --  from the exhausted marker, which is the capacity of the map being
124    --  walked.
125    at = (next_slot: 0 -% 1)
126end entries
127
128--  The slot a position names: the map's head for the marker `entries`
129--  makes.
130position_slot: (key: type is cmp.hashable, item: type,
131                value: map(key, item), at: position) -> (slot: usize) =
132    slot = at.next_slot
133    if slot == 0 -% 1 then
134        slot = value.first_used
135    end if
136end position_slot
137
138--- Whether the walk at `at` has handed out every live entry. While
139--- it is false, `next_entry` hands out the next one; keep the map unchanged
140--- during the walk.
141public at_end: (key: type is cmp.hashable, item: type,
142                value: map(key, item), at: position) -> (yes: bool) =
143    slot: usize = position_slot(value, at)
144    yes = true
145    return when slot >= slots(value)
146    record: bucket = mem.get(value.buckets, slot) else (problem)
147        _ = problem
148        return
149    end
150    yes = record.state <> slot_used
151end at_end
152
153--- Copy the next live key/value pair and advance the position. Call it
154--- only while `at_end` is false: at the end of the walk it stops the
155--- program, as a failed check does. Keep the map unchanged during the walk.
156---
157--- Each call follows one live link. Across an unmodified walk, every live
158--- entry is returned once in insertion order and the walk costs O(count).
159--- The result is what the map holds, a copy of its key and item, and no
160--- view of the map's storage.
161public next_entry: (key: type is cmp.hashable, item: type,
162                    value: map(key, item), inout at: position)
163                   -> (result: entry(key, item) from held value) =
164    at.next_slot = position_slot(value, at)
165    record: bucket = mem.get(value.buckets, at.next_slot)
166        else (problem)
167        _ = problem
168        compiler.unreachable()
169    end
170    if record.state <> slot_used then
171        compiler.unreachable()
172    end if
173    at.next_slot = record.next_used
174    found_key: key = mem.get(value.keys, record.dense_index)
175        else (problem)
176        _ = problem
177        compiler.unreachable()
178    end
179    found_item: item = mem.get(value.values, record.dense_index)
180        else (problem)
181        _ = problem
182        compiler.unreachable()
183    end
184    result = (key: found_key, item: found_item)
185end next_entry
186
187--  The map's conformance to core/iter's `iterable` (D1957): `for entry in
188--  m` walks the live entries in insertion order, as `next_entry` does,
189--  each a copy of its key and item.  The position is the slot of the entry
190--  next handed out.
191walk_first: (key: type is cmp.hashable, item: type,
192             s: ptr map_value(key, item)) -> (c: position) =
193    c = (next_slot: s.val.first_used)
194end walk_first
195
196walk_at_end: (key: type is cmp.hashable, item: type,
197              s: ptr map_value(key, item), c: position) -> (yes: bool) =
198    yes = true
199    return when c.next_slot >= slots(s.val)
200    record: bucket = mem.get(s.val.buckets, c.next_slot) else (problem)
201        _ = problem
202        return
203    end
204    yes = record.state <> slot_used
205end walk_at_end
206
207walk_item: (key: type is cmp.hashable, item: type,
208            s: ptr map_value(key, item), c: position)
209           -> (v: entry(key, item)) =
210    record: bucket = mem.get(s.val.buckets, c.next_slot) else (problem)
211        _ = problem
212        compiler.unreachable()
213    end
214    found_key: key = mem.get(s.val.keys, record.dense_index) else (problem)
215        _ = problem
216        compiler.unreachable()
217    end
218    found_item: item = mem.get(s.val.values, record.dense_index)
219        else (problem)
220        _ = problem
221        compiler.unreachable()
222    end
223    v = (key: found_key, item: found_item)
224end walk_item
225
226walk_next: (key: type is cmp.hashable, item: type,
227            s: ptr map_value(key, item), c: position) -> (c2: position) =
228    record: bucket = mem.get(s.val.buckets, c.next_slot) else (problem)
229        _ = problem
230        compiler.unreachable()
231    end
232    c2 = (next_slot: record.next_used)
233end walk_next
234
235(key: type is cmp.hashable, item: type) map_value(key, item) is iter.iterable
236    (cur: position, item_type: entry(key, item), first: walk_first,
237     at_end: walk_at_end, item: walk_item, next: walk_next)
238
239replace_value: (value: type, inout storage: mem.storage(value),
240                index: usize, escaping into storage replacement: value)
241               -> (ok: bool) =
242    mem.replace(storage, index, replacement) else (problem)
243        _ = problem
244        ok = false
245        return
246    end
247    ok = true
248end replace_value
249
250index_of: (key: type is cmp.hashable, value: key, slots: usize,
251           seed: cmp.hash_seed) -> (index: usize) =
252    --  A program's own hash may still be a key's value, so that keys
253    --  sharing a stride would share their low bits and one probe chain.
254    --  MurmurHash3's finalizer spreads every input bit over the word first. Every
255    --  library-created nonempty table is a power of two; mask in u64 before
256    --  narrowing, so the same full-width reduction applies on a 32-bit
257    --  target. Publicly composed maps may have other sizes.
258    mut hash: u64 = key.hash(value, seed)
259    hash ^= hash >> 33
260    hash *%= 18397679294719823053
261    hash ^= hash >> 33
262    hash *%= 14181476777654086739
263    hash ^= hash >> 33
264    if (slots & (slots - 1)) == 0 then
265        index = usize(hash & u64(slots - 1))
266    else
267        index = usize(hash % u64(slots))
268    end if
269end index_of
270
271next_index: (index: usize, slots: usize) -> (next: usize) =
272    if index == slots - 1 then
273        next = 0
274    else
275        next = index + 1
276    end if
277end next_index
278
279--  This is equivalent to `(count + tombstones + 1) * 4 > slots * 3`
280--  without overflowing either addition or multiplication. Corrupt counters
281--  conservatively report pressure rather than wrapping to "not crowded".
282--  Insert consults this whenever a new key would take a free bucket, so
283--  tombstones count towards the pressure as live entries do.
284crowded: (key: type is cmp.hashable, item: type,
285          value: map(key, item)) -> (yes: bool) =
286    slots: usize = slots(value)
287    if slots == 0 then
288        yes = true
289        return
290    end if
291    if value.count > slots or value.tombstones > slots - value.count then
292        yes = true
293        return
294    end if
295    occupied: usize = value.count + value.tombstones
296    yes = occupied >= crowding_threshold(slots)
297end crowded
298
299--  Three quarters of the slots, computed without overflow.
300crowding_threshold: (slots: usize) -> (threshold: usize) =
301    quarter: usize = slots / 4
302    remainder: usize = slots % 4
303    threshold = quarter * 3 + (remainder * 3) / 4
304end crowding_threshold
305
306install_at: (key: type is cmp.hashable, item: type,
307             inout value: map(key, item), at: usize, was_dead: bool,
308             escaping into value added_key: key,
309             escaping into value added_item: item)
310            -> (placed: bool) =
311    slots: usize = slots(value)
312    mut dense: usize = 0
313    if was_dead then
314        record: bucket = mem.get(value.buckets, at) else (problem)
315            _ = problem
316            placed = false
317            return
318        end
319        dense = record.dense_index
320        if not replace_value(value.keys, dense, added_key) then
321            placed = false
322            return
323        end if
324        if not replace_value(value.values, dense, added_item) then
325            placed = false
326            return
327        end if
328    else
329        dense = mem.admit(value.keys, added_key) else (problem)
330            _ = problem
331            placed = false
332            return
333        end
334        value_dense: usize = mem.admit(value.values, added_item)
335            else (problem)
336            _ = problem
337            discarded: key = mem.withdraw(value.keys) else (release_problem)
338                _ = release_problem
339                placed = false
340                return
341            end
342            placed = false
343            return
344        end
345        if value_dense <> dense then
346            placed = false
347            return
348        end if
349    end if
350
351    replacement_bucket: bucket =
352        (state: slot_used, dense_index: dense,
353         previous_used: value.last_used, next_used: slots)
354    if not replace_value(value.buckets, at, replacement_bucket) then
355        placed = false
356        return
357    end if
358    if value.last_used < slots then
359        mut tail: bucket = mem.get(value.buckets, value.last_used)
360            else (problem)
361            _ = problem
362            placed = false
363            return
364        end
365        tail.next_used = at
366        if not replace_value(value.buckets, value.last_used, tail) then
367            placed = false
368            return
369        end if
370    else
371        value.first_used = at
372    end if
373    value.last_used = at
374    inc value.count
375    if was_dead then
376        dec value.tombstones
377    end if
378    placed = true
379end install_at
380
381--  Keep the absent key's placement position so insertion without a rebuild
382--  does not probe the same chain again. A dead bucket is usable only after
383--  checking the rest of the chain for an equal used key.
384insert_search: type = struct
385    updated: bool
386    slot_index: usize
387    was_dead: bool
388end insert_search
389
390search_for_insert: (key: type is cmp.hashable, item: type,
391                    inout value: map(key, item), wanted: key,
392                    escaping into value replacement: item)
393                   -> (result: insert_search) ! mem.out_of_memory =
394    slots: usize = slots(value)
395    if slots == 0 then
396        result = (updated: false, slot_index: slots, was_dead: false)
397        return
398    end if
399
400    mut at: usize = index_of(wanted, slots, value.seed)
401    mut first_dead: usize = slots
402    mut probed: usize = 0
403    while probed < slots do
404        record: bucket = mem.get(value.buckets, at) else (problem)
405            _ = problem
406            fail mem.out_of_memory
407        end
408        if record.state == slot_free then
409            if first_dead < slots then
410                result = (updated: false, slot_index: first_dead,
411                          was_dead: true)
412            else
413                result = (updated: false, slot_index: at, was_dead: false)
414            end if
415            return
416        end if
417        if record.state == slot_dead then
418            if first_dead == slots then
419                first_dead = at
420            end if
421        elsif record.state == slot_used then
422            existing: key = mem.get(value.keys, record.dense_index)
423                else (problem)
424                _ = problem
425                fail mem.out_of_memory
426            end
427            if key.equal(existing, wanted) then
428                if not replace_value(value.values, record.dense_index,
429                                     replacement)
430                then
431                    fail mem.out_of_memory
432                end if
433                result = (updated: true, slot_index: at, was_dead: false)
434                return
435            end if
436        end if
437        at = next_index(at, slots)
438        inc probed
439    end while
440    result = (updated: false, slot_index: first_dead,
441              was_dead: first_dead < slots)
442end search_for_insert
443
444--  The caller has already proved this key absent. Probes are still bounded
445--  if no free bucket exists, and the first tombstone wins only after the
446--  search has reached a free bucket or exhausted the table.
447place_absent: (key: type is cmp.hashable, item: type,
448               inout value: map(key, item),
449               escaping into value added_key: key,
450               escaping into value added_item: item)
451              -> (placed: bool) =
452    slots: usize = slots(value)
453    if slots == 0 then
454        placed = false
455        return
456    end if
457
458    mut at: usize = index_of(added_key, slots, value.seed)
459    mut first_dead: usize = slots
460    mut probed: usize = 0
461    while probed < slots do
462        record: bucket = mem.get(value.buckets, at) else (problem)
463            _ = problem
464            placed = false
465            return
466        end
467        if record.state == slot_dead then
468            if first_dead == slots then
469                first_dead = at
470            end if
471        elsif record.state == slot_free then
472            if first_dead < slots then
473                placed = install_at(value, first_dead, true,
474                                    added_key, added_item)
475            else
476                placed = install_at(value, at, false,
477                                    added_key, added_item)
478            end if
479            return
480        end if
481        at = next_index(at, slots)
482        inc probed
483    end while
484
485    if first_dead < slots then
486        placed = install_at(value, first_dead, true, added_key, added_item)
487    else
488        placed = false
489    end if
490end place_absent
491
492rehash: (key: type is cmp.hashable, item: type,
493         provider: type is mem.allocator,
494         inout value: map(key, item), memory: provider, want: usize)
495        -> none ! mem.out_of_memory =
496    fail mem.out_of_memory when want == 0 or want < value.count
497
498    --  Preflight every byte product before the first provider effect.
499    bucket_extent: usize = try mem.storage_extent(item: bucket, slots: want)
500    key_extent: usize = try mem.storage_extent(item: key, slots: want)
501    value_extent: usize = try mem.storage_extent(item: item, slots: want)
502
503    bucket_block: ptr mut u8 = try provider.alloc
504        (memory, bucket_extent, alignof bucket)
505    mut new_buckets := mem.storage_over
506        (item: bucket, base: bucket_block, slots: want)
507    undo mem.release_storage(new_buckets, memory)
508
509    mut initialized: usize = 0
510    while initialized < want do
511        empty_bucket: bucket =
512            (state: slot_free, dense_index: 0,
513             previous_used: want, next_used: want)
514        admitted: usize = mem.admit
515            (new_buckets, empty_bucket)
516            else (problem)
517            _ = problem
518            fail mem.out_of_memory
519        end
520        _ = admitted
521        inc initialized
522    end while
523
524    key_block: ptr mut u8 = try provider.alloc
525        (memory, key_extent, alignof key)
526    mut new_keys := mem.storage_over(item: key, base: key_block, slots: want)
527    undo mem.release_storage(new_keys, memory)
528
529    value_block: ptr mut u8 = try provider.alloc
530        (memory, value_extent, alignof item)
531    mut new_values := mem.storage_over(item: item, base: value_block, slots: want)
532    undo mem.release_storage(new_values, memory)
533
534    old_slots: usize = slots(value)
535    mut old_at: usize = value.first_used
536    mut migrated: usize = 0
537    mut new_first: usize = want
538    mut new_last: usize = want
539    while migrated < value.count do
540        fail mem.out_of_memory when old_at >= old_slots
541        old_bucket: bucket = mem.get(value.buckets, old_at) else (problem)
542            _ = problem
543            fail mem.out_of_memory
544        end
545        fail mem.out_of_memory when old_bucket.state <> slot_used
546        old_key: key = mem.get(value.keys, old_bucket.dense_index)
547            else (problem)
548            _ = problem
549            fail mem.out_of_memory
550        end
551        mut target: usize = index_of(old_key, want, value.seed)
552        mut searched: usize = 0
553        while searched < want do
554            target_bucket: bucket = mem.get(new_buckets, target)
555                else (problem)
556                _ = problem
557                fail mem.out_of_memory
558            end
559            break when target_bucket.state == slot_free
560            target = next_index(target, want)
561            inc searched
562        end while
563        fail mem.out_of_memory when searched == want
564
565        key_dense: usize = mem.transfer
566            (new_keys, value.keys, old_bucket.dense_index)
567            else (problem)
568            _ = problem
569            fail mem.out_of_memory
570        end
571        value_dense: usize = mem.transfer
572            (new_values, value.values, old_bucket.dense_index)
573            else (problem)
574            _ = problem
575            fail mem.out_of_memory
576        end
577        fail mem.out_of_memory when key_dense <> value_dense
578        moved_bucket: bucket =
579            (state: slot_used, dense_index: key_dense,
580             previous_used: new_last, next_used: want)
581        if not replace_value(new_buckets, target, moved_bucket) then
582            fail mem.out_of_memory
583        end if
584        if new_last < want then
585            mut tail: bucket = mem.get(new_buckets, new_last)
586                else (problem)
587                _ = problem
588                fail mem.out_of_memory
589            end
590            tail.next_used = target
591            if not replace_value(new_buckets, new_last, tail) then
592                fail mem.out_of_memory
593            end if
594        else
595            new_first = target
596        end if
597        new_last = target
598        old_at = old_bucket.next_used
599        inc migrated
600    end while
601    fail mem.out_of_memory when old_at <> old_slots
602
603    --  Migration has succeeded. Everything below is infallible: retire all
604    --  three old extents exactly once and publish the replacement last.
605    mem.release_storage(value.values, memory)
606    mem.release_storage(value.keys, memory)
607    mem.release_storage(value.buckets, memory)
608    value.buckets = new_buckets
609    value.keys = new_keys
610    value.values = new_values
611    value.count = migrated
612    value.tombstones = 0
613    value.first_used = new_first
614    value.last_used = new_last
615end rehash
616
617--- Insert a new key/value pair or replace the value of an equal key. New keys
618--- append in insertion order; replacement keeps its position. Allocation
619--- failure preserves the previous map. Growth can invalidate views.
620public insert: (key: type is cmp.hashable, item: type,
621                provider: type is mem.allocator,
622                inout value: map(key, item), memory: provider,
623                escaping into value added_key: key,
624                escaping into value added_item: item)
625               -> none ! mem.out_of_memory =
626    position: insert_search = try search_for_insert
627        (value, added_key, added_item)
628    return when position.updated
629
630    --  A dead bucket on the key's own chain is reused without extending
631    --  either dense prefix or rebuilding. A new key taking a free bucket
632    --  counts against the threshold with the tombstones. The table is
633    --  rebuilt at its size, emptying them, only while the live entries with
634    --  the new key fit in half its capacity, and grows otherwise: tombstones
635    --  then make up at least half the pressure, so at least half a capacity
636    --  of removals and insertions separates two rebuilds, and a map churned
637    --  just below its capacity does not rebuild on every new key.
638    if not position.was_dead and crowded(value) then
639        old_slots: usize = slots(value)
640        mut want: usize = 8
641        if old_slots > 0 then
642            want = old_slots
643            if value.count >= crowding_threshold(old_slots) / 2 then
644                maximum: usize = 0 -% 1
645                fail mem.out_of_memory when old_slots > maximum / 2
646                want = old_slots * 2
647            end if
648        end if
649        try rehash(value, memory, want)
650        inserted: bool = place_absent(value, added_key, added_item)
651        fail mem.out_of_memory when not inserted
652        return
653    end if
654    fail mem.out_of_memory when position.slot_index == slots(value)
655    inserted: bool = install_at(value, position.slot_index, position.was_dead,
656                                added_key, added_item)
657    fail mem.out_of_memory when not inserted
658end insert
659
660--  Where a present key lives: its bucket and its dense position.
661location: type = struct
662    slot: usize
663    dense: usize
664end location
665
666locate: (key: type is cmp.hashable, item: type,
667         value: map(key, item), wanted: key)
668        -> (found: location) ! mem.not_found =
669    fail mem.not_found when value.count == 0
670    slots: usize = slots(value)
671    fail mem.not_found when slots == 0
672    mut slot: usize = index_of(wanted, slots, value.seed)
673    mut probed: usize = 0
674    while probed < slots do
675        record: bucket = mem.get(value.buckets, slot) else (problem)
676            _ = problem
677            fail mem.not_found
678        end
679        fail mem.not_found when record.state == slot_free
680        if record.state == slot_used then
681            existing: key = mem.get(value.keys, record.dense_index)
682                else (problem)
683                _ = problem
684                fail mem.not_found
685            end
686            if key.equal(existing, wanted) then
687                found = (slot: slot, dense: record.dense_index)
688                return
689            end if
690        end if
691        slot = next_index(slot, slots)
692        inc probed
693    end while
694    fail mem.not_found
695end locate
696
697--- Copy the value associated with a key. Reports `mem.not_found` if absent;
698--- references inside the copy retain their origin.
699public get: (key: type is cmp.hashable, item: type,
700             value: map(key, item), wanted: key)
701            -> (result: item from held value) ! mem.not_found =
702    found: location = try locate(value, wanted)
703    result = mem.get(value.values, found.dense) else (problem)
704        _ = problem
705        fail mem.not_found
706    end
707end get
708
709--- Lend a writable pointer to the present key's item for in-place update.
710--- Reports `mem.not_found` if absent. While the result lives the map binding
711--- may not be passed inout or sink [0800]; let it end before the next insert,
712--- remove or release.
713public at: (key: type is cmp.hashable, item: type,
714            inout value: map(key, item), wanted: key)
715           -> (slot: ptr mut item from value) ! mem.not_found =
716    found: location = try locate(value, wanted)
717    view: []mut item = mem.used(value.values)
718    fail mem.not_found when found.dense >= lenof view
719    slot = addr view[found.dense]
720end at
721
722--- Return whether a live entry has the requested key, without allocating.
723public contains: (key: type is cmp.hashable, item: type,
724                  value: map(key, item), wanted: key) -> (yes: bool) =
725    _ = locate(value, wanted) else (problem)
726        _ = problem
727        yes = false
728        return
729    end
730    yes = true
731end contains
732
733--- Remove a key/value entry without returning it. Reports `mem.not_found` if
734--- absent; preserves the relative order of remaining entries. End existing
735--- value pointers and positions before mutation.
736public remove: (key: type is cmp.hashable, item: type,
737                inout value: map(key, item), wanted: key)
738               -> none ! mem.not_found =
739    fail mem.not_found when value.count == 0
740    slots: usize = slots(value)
741    fail mem.not_found when slots == 0
742    mut at: usize = index_of(wanted, slots, value.seed)
743    mut probed: usize = 0
744    while probed < slots do
745        record: bucket = mem.get(value.buckets, at) else (problem)
746            _ = problem
747            fail mem.not_found
748        end
749        fail mem.not_found when record.state == slot_free
750        if record.state == slot_used then
751            existing: key = mem.get(value.keys, record.dense_index)
752                else (problem)
753                _ = problem
754                fail mem.not_found
755            end
756            if key.equal(existing, wanted) then
757                if record.previous_used < slots then
758                    mut previous: bucket =
759                        mem.get(value.buckets, record.previous_used)
760                        else (problem)
761                            _ = problem
762                            fail mem.not_found
763                        end
764                    previous.next_used = record.next_used
765                    if not replace_value(value.buckets,
766                                         record.previous_used, previous)
767                    then
768                        fail mem.not_found
769                    end if
770                else
771                    value.first_used = record.next_used
772                end if
773                if record.next_used < slots then
774                    mut next: bucket =
775                        mem.get(value.buckets, record.next_used)
776                        else (problem)
777                            _ = problem
778                            fail mem.not_found
779                        end
780                    next.previous_used = record.previous_used
781                    if not replace_value(value.buckets, record.next_used,
782                                         next)
783                    then
784                        fail mem.not_found
785                    end if
786                else
787                    value.last_used = record.previous_used
788                end if
789                dead_bucket: bucket =
790                    (state: slot_dead, dense_index: record.dense_index,
791                     previous_used: slots, next_used: slots)
792                if not replace_value(value.buckets, at, dead_bucket) then
793                    fail mem.not_found
794                end if
795                dec value.count
796                inc value.tombstones
797                return
798            end if
799        end if
800        at = next_index(at, slots)
801        inc probed
802    end while
803    fail mem.not_found
804end remove
805
806--- Discard all entries, free the map's backing through its original provider
807--- and reset it, keeping its seed. Nested resources referred to by keys or
808--- values are not freed automatically.
809public release: (key: type is cmp.hashable, item: type,
810                 provider: type is mem.allocator,
811                 inout value: map(key, item),
812                 memory: provider) -> none =
813    mem.release_storage(value.values, memory)
814    mem.release_storage(value.keys, memory)
815    mem.release_storage(value.buckets, memory)
816    value = new(key: key, item: item, seed: value.seed)
817end release
818
819--- Discard all entries and tombstones while keeping the allocations: every
820--- bucket is rewritten free and both dense prefixes are emptied. End
821--- existing pointers and walks first; resources the discarded values refer
822--- to remain the caller's.
823public clear: (key: type is cmp.hashable, item: type,
824               inout value: map(key, item)) -> none =
825    slots: usize = slots(value)
826    mut slot: usize = 0
827    while slot < slots do
828        free_bucket: bucket = (state: slot_free, dense_index: 0,
829                               previous_used: slots, next_used: slots)
830        return when not replace_value(value.buckets, slot, free_bucket)
831        inc slot
832    end while
833    mem.clear(value.keys)
834    mem.clear(value.values)
835    value.count = 0
836    value.tombstones = 0
837    value.first_used = slots
838    value.last_used = slots
839end clear
840
841--- Ensure room for at least `want` entries without a growth allocation:
842--- until `length` reaches `want`, inserting a new key neither grows nor
843--- rebuilds the table, as long as nothing is removed in between.  The
844--- table is doubled from eight slots until its `capacity` holds `want`,
845--- and the map is rebuilt once at that size.  A table already that large
846--- keeps its size: it is rebuilt at it when its removed entries, which
847--- hold their slots until a rebuild, leave less room than `want`, and is
848--- otherwise left alone.  A rebuild allocates the replacement storage
849--- before committing it.  Allocation failure frees the partial
850--- replacement and preserves every entry; success can invalidate pointers
851--- and positions.
852public reserve: (key: type is cmp.hashable, item: type,
853                 provider: type is mem.allocator,
854                 inout value: map(key, item), memory: provider,
855                 want: usize) -> none ! mem.out_of_memory =
856    return when want == 0
857    maximum: usize = 0 -% 1
858    mut want_slots: usize = 8
859    while want > crowding_threshold(want_slots) do
860        fail mem.out_of_memory when want_slots > maximum / 2
861        want_slots = want_slots * 2
862    end while
863    have_slots: usize = slots(value)
864    if want_slots <= have_slots then
865        --  A new key that takes a free bucket rebuilds once the live
866        --  entries and the tombstones fill the capacity, so `want` new
867        --  and live entries fit beside the tombstones only while the two
868        --  together do; `want` fits in the capacity here.
869        return when value.tombstones <= crowding_threshold(have_slots) - want
870        want_slots = have_slots
871    end if
872    try rehash(value, memory, want_slots)
873end reserve