Hash-based key-value storage parameterized by key and value schemas.
HashTable
Construct with key and value schemas before the type name: Key Value HashTable, for example Int32 Int32 HashTable.
HashTable
(keySchema valueSchema -- table) Constructs an empty owning table from key and value schemas.- Use schema objects such as
Int32or mutable prototype views such as@keyPrototype @valuePrototype; immutable prototype views can makefind,at, orgetOrDefaultfail to compile when lookup instantiates the matching-node branch («set», Second argument (target) is of different schema) and makegetOrCreatereturn an immutable view. - Stored key and value variables must support construction. Text is not a constructible stored item here; use
Stringfor owned text.
Fields
SCHEMA_NAME: static Text schema-name field built from the key and value schema names.HASH_TABLE: static empty-Tuple marker.Key: static NIL reference descriptor for the key schema.Value: static NIL reference descriptor for the value schema.Node: static Block with effect(-- node)that constructs an object containing onekeyfield of the key schema and onevaluefield of the value schema.data: array of bucket arrays containing Node values.dataSize:Int32count of stored nodes.
A new HashTable is empty. An immutable table source is copied using contained assignment operations; a mutable table can be moved, leaving the source empty. Destroying the table destroys its owned arrays, nodes, keys, and values, not objects merely referenced by contained reference fields.
Buckets have independent array storage. An insertion can move a bucket and invalidate its references even without changing the bucket count. Erasing can replace another slot in the same bucket. Reacquire references and iterators after any insertion or erasure, and after clear, release, assignment, move, or destruction.
Methods
nexthas effect(-- item valid). It yields an immutable key view and a value view whose mutability follows the table view.
keys
(-- iter) Returns an iterator of stored keys.nexthas effect(-- item valid); it always yields immutable key views.
values
(-- iter) Returns an iterator of stored values.nexthas effect(-- item valid); it yields value views whose mutability follows the table view.
empty
(-- cond) Reports whether the table has no stored pairs.size
(-- count) Returns the number of stored key-value pairs.at
(key -- ref) Returns a view of the stored value, mutable through a mutable table and immutable through an immutable table.- A missing key reports
Key is not in the collectionwith DEBUG enabled and exits with status 2; with DEBUG disabled it yields a NIL value reference that must not be dereferenced.
find
(key -- result) Returns a result record describing the key lookup.result.successis TRUE when the key exists.result.valueis a value reference whose mutability follows the table view; ordinary reads of a result field are immutable, while@r.@valueretains the stored reference's view. The value reference is NIL when success is FALSE.
getOrDefault
(key default -- value) Returns a copy of the stored value for key, or a copy of default when key is not stored.defaultmust have the table's value schema.
getOrInsert
(key value -- ref) Returns a mutable view of the stored value for key, inserting the pair first when key is not stored.- When
keyis stored, no pair is constructed; otherwise construction, growth, and invalidation followinsert.
getOrCreate
(key -- ref) Returns a mutable view of the stored value for key, inserting a pair with a new value first when key is not stored.- The new value is created with
newVarOfTheSameType; any storage left uninitialized, such as anInt32, must be written before it is read. - When
keyis stored, no pair is constructed; otherwise construction, growth, and invalidation followinsert, but the pair is constructed after the growth.
erase
(key --) Removes the stored pair with key.- On a nonempty table, a missing key reports
Erasing unexisting element!and exits with status 2; on an empty table it does not.
predicatehas effect(pair -- cond);pairis a view of a stored{key value}pair.
insert
(key value --) Constructs a stored pair from key and value.- With DEBUG enabled, inserting an existing key reports
The key is already in the HashTableand exits with status 2; with DEBUG disabled, duplicate pairs are accepted. - Each input is copied or moved according to its view and construction support; mutable managed inputs can be moved from, immutable inputs are copied, and contained references retain aliasing.
insertUnsafe
(key value --) Inserts a pair without checking for an existing key.- Construction, growth, and invalidation follow insert; check for an existing key when unique keys are required.
tryInsert
(key value -- cond) Inserts the pair and returns TRUE when key is not stored; otherwise returns FALSE.- When
keyis stored, no pair is constructed; otherwise construction, growth, and invalidation followinsert.
insertOrAssign
(key value --) Inserts the pair when key is not stored; otherwise assigns value to the stored value.- When
keyis stored, no pair is constructed, and the assignment follows the input view's rules: a mutable managed value can be moved from, while an immutable one is copied. Otherwise construction, growth, and invalidation followinsert.
rebuild
(bucketCount --) Redistributes the stored nodes over bucketCount buckets; the size counter is not changed.bucketCountmust be a positiveInt32.- Normal growth uses powers of two (16, 32, ...). The bucket index is
hash and (bucketCount - 1), so a count that is not a power of two leaves some buckets unused. rebuildinvalidates stored references and iterators.
Known issue: shrinking the bucket count destroys truncated buckets before rehashing, loses their pairs without correcting size, and leaves the table inconsistent; do not shrink the bucket count.
clear
(--) Removes stored pairs and sets the item count to zero.Remarks
- The outer bucket array retains its reserved allocation; stored pairs and their owned values are destroyed.
release
(--) Releases bucket storage and sets the item count to zero.Implementation helper
makeIter
(buckets projection -- iter) Used by iter, keys, and values; builds an iterator over bucket-node storage, applying projection to each node.- The iterator retains the supplied storage view and has method, data, bucket, item, and next fields.
projectionmust consume a node and return one item; it is stored as a static field.nexthas effect(-- item valid). On exhaustion it callsprojectionwith a node containing key/value references with unknown addresses and returns its result followed byFALSE. Do not dereference those references.
Key requirements and iteration order
- Keys are hashed with
hash, which accepts numbers, Conds, and Lists of keys. - A Dict key with a named field must provide a
getHashfield or method that returns oneNat32result; a table does not convert a custom hash. WithoutgetHashit fails withAll 4 predicates named «hash» did not match. - Equal keys must have equal hashes. Do not change a stored key's hash or equality while it remains in the table.
- Keys are compared with
=: a number or Cond key uses the builtin; a Dict key with anequalfield uses control's=; any other iterable key uses algorithm's=. - A non-iterable Dict without
equalfails withBuilt-in text, tuple, Iter, or Iterable expected. - Initially no buckets are allocated. The first insertion creates 16 buckets; before an insertion whose item count equals the bucket count, the bucket count doubles.
- Iteration visits buckets in ascending bucket index and items in their current bucket-storage order. It is neither sorted-key nor insertion order.
toHashTable
(source -- hashTable) Builds an owning HashTable from an iteration source of key-value pairs.- Each item is a Struct of two fields (or a view of one): field 0 is the key and field 1 is the value. Field names are ignored; a Dict must declare those fields in that order. A Tuple such as
(1 10)and the pairs yielded by another table'siterare accepted. - The first item returned by next supplies both schemas, even if its validity flag is FALSE; valid items are inserted in source order.
- An empty source works when its end item supplies both field schemas. Duplicate handling is the same as
insert.
Examples
Example: lookup and erasure
After three inserts, at and find read stored values, and erase removes key 2.
"HashTable" use
"String" use
"control" use
{} Int32 {} [
h: Int32 Int32 HashTable;
1 10 @h.insert
2 20 @h.insert
3 30 @h.insert
r: 3 @h.find;
("size=" h.size LF
"at2=" 2 @h.at new LF
"found3=" r.success LF
"value3=" @r.value new LF) printList
2 @h.erase
("size2=" h.size LF) printList
0
] "main" exportFunction
Expected Output
size=3
at2=20
found3=TRUE
value3=30
size2=2
Example: lookup of a missing key
find reports success for key 1 and failure for the missing key 5, without inserting it.
"HashTable" use
"String" use
"control" use
{} Int32 {} [
h: Int32 Int32 HashTable;
1 10 @h.insert
r0: 1 @h.find;
r1: 5 @h.find;
("found0=" r0.success LF
"value0=" @r0.value new LF
"found1=" r1.success LF
"size=" h.size LF) printList
0
] "main" exportFunction
Expected Output
found0=TRUE
value0=10
found1=FALSE
size=1
Example: building from pairs
toHashTable builds a table from a tuple of key-value pairs.
"HashTable" use
"String" use
"control" use
{} Int32 {} [
t: ((1 10) (2 20)) toHashTable;
("size=" t.size LF
"at2=" 2 @t.at new LF) printList
0
] "main" exportFunction
Expected Output
size=2
at2=20
Example: iter, keys, and values
iter yields key-value pairs, and keys and values yield the keys and the values alone.
"HashTable" use
"String" use
"control" use
{} Int32 {} [
h: Int32 Int32 HashTable;
1 10 @h.insert
2 20 @h.insert
pairs: @h.iter;
pair0: ok0: @pairs.next;;
pair1: ok1: @pairs.next;;
pair2: ok2: @pairs.next;;
keys: @h.keys;
key0: hasKey0: @keys.next;;
key1: hasKey1: @keys.next;;
values: @h.values;
value0: hasValue0: @values.next;;
value1: hasValue1: @values.next;;
("pair0Key=" pair0.key LF
"pair0Value=" @pair0.value new LF
"pair1Key=" pair1.key LF
"pair1Value=" @pair1.value new LF
"iterDone=" ok2 LF
"key0=" key0 LF
"key1=" key1 LF
"value0=" value0 new LF
"value1=" value1 new LF) printList
0
] "main" exportFunction
Expected Output
pair0Key=2
pair0Value=20
pair1Key=1
pair1Value=10
iterDone=FALSE
key0=2
key1=1
value0=20
value1=10