Landin library reference discuss source

Shared: available on every enabled target.

An insertion-ordered hash map with explicit entry walks.

Call What it does
map.new Start an empty map that hashes its keys under a seed.
map.insert Add a key and its item, through the provider's handle.
map.get, map.at, map.contains Copy an item, lend a pointer to it, or ask whether a key is there.
map.remove Remove a key.
map.entries, map.next_entry Walk the entries in insertion order.
for each in m The same walk through core/iter's iterable, each entry a copy of its key and item.

Keys are constrained on the hashable concept of core/cmp, whose table lists the types hashable ships for. An alternative policy uses a distinct wrapper. Floating-point keys need an explicit equality and hashing policy.

Keep keys and their backing stable while the map stores them, and restart positions after any mutation.

A map hashes every key under the seed map.new is given, and keeps it through release and clear. A seed the key's chooser does not know keeps keys from being chosen to share one probe chain, where each insertion and lookup would take time in proportion to the map's size:

  • a hosted program keyed by outside data draws its seed with random.hash_seed from its entropy provider;
  • firmware without entropy builds one with cmp.seed_from from two words of its own: a hardware random number or a unique device ID where it has one, and otherwise a constant chosen for the build, which protects the map only while the image stays secret;
  • a test uses a constant, so that every run probes alike.

The seed changes nothing a lookup finds and not the order of a walk. It changes which slots the keys take, and so the number of probes. After removals it also decides whether a new key reuses a removed entry's slot or rebuilds the table, which slots, removed and capacity report. A constant seed makes all of this the same on every run.

Keys chosen against a known seed share one probe chain and spread under another seed; a hosted map draws its seed from the system's entropy, and a firmware map is given two words.

There are two ways to walk a map. One starts at map.entries() and asks map.at_end before each map.next_entry, which never fails; the executable example below walks this way. The other is a for loop over the map, as this program does. The derived container program also walks after removing keys.

Three counts describe the table:

Call What it counts
capacity How many entries fit before the next new key rebuilds the table. Removed entries count against the capacity until a rebuild.
slots The table's size.
removed The dead entries, which hold their slots until a rebuild.

The representation is the module's own. Hashes are spread before they choose a slot, so keys that share a stride do not share a probe chain.

A complete map workload can exceed the Cortex-M0 test profile of 32 KiB flash. The Cortex-M0 example therefore checks only the empty-map surface. It does not show that a populated map fits that profile.

Items

public entry: type (key: type, item: type) = struct
    key: key
    item: item
end entry

A copied key/value pair returned by next_entry. References inside either value still depend on their original backing.

public map: type (key: type is cmp.hashable, item: type) =
    map_value(key, item)

Insertion-ordered hash map over slot metadata and dense key/value prefixes. Providers are supplied per operation. Its representation is the module's own, so nothing outside core/map can break the invariants its operations keep.

A map hashes its keys under the seed it was made with, and the hashes core/cmp ships are SipHash-1-3 keyed by it, so whoever does not know the seed cannot choose keys that share one probe chain. Seed a map keyed by outside data from entropy, as random.hash_seed draws one; a program without entropy gives a value its adversary cannot read. The seed changes nothing a lookup finds and not the order of a walk, only which slots the keys take, and so how many probes an operation makes and, after removals, whether a new key reuses a removed entry's slot or rebuilds the table, which slots, removed and capacity then report. A constant seed makes all of that the same on every run.

public position: type = position_value

Position in an insertion-order entry walk. Start with entries; do not mutate the map during a walk.

A position is a manual live-bucket place, not an ownership or snapshot token: it has no map identity or generation check and is not transferable between maps. Any mutation, including insert, remove, rehash, clear and release, invalidates an active walk; callers must discard its position and restart. Its slot is the module's own.

public at: (key: type is cmp.hashable, item: type,
            inout value: map(key, item), wanted: key)
           -> (slot: ptr mut item from value) ! mem.not_found

Lend a writable pointer to the present key's item for in-place update. Reports mem.not_found if absent. While the result lives the map binding may not be passed inout or sink [0800]; let it end before the next insert, remove or release.

public at_end: (key: type is cmp.hashable, item: type,
                value: map(key, item), at: position) -> (yes: bool)

Whether the walk at at has handed out every live entry. While it is false, next_entry hands out the next one; keep the map unchanged during the walk.

capacity

function core/map/map.ldn:99 ↑ index
public capacity: (key: type is cmp.hashable, item: type,
                  value: map(key, item)) -> (count: usize)

Return how many entries the map holds before inserting a new key rebuilds it: three quarters of its hash slots. Removed entries occupy their slots until a rebuild, so after a removal the rebuild can come sooner.

public clear: (key: type is cmp.hashable, item: type,
               inout value: map(key, item)) -> none

Discard all entries and tombstones while keeping the allocations: every bucket is rewritten free and both dense prefixes are emptied. End existing pointers and walks first; resources the discarded values refer to remain the caller's.

contains

function core/map/map.ldn:723 ↑ index
public contains: (key: type is cmp.hashable, item: type,
                  value: map(key, item), wanted: key) -> (yes: bool)

Return whether a live entry has the requested key, without allocating.

entries

function core/map/map.ldn:120 ↑ index
public entries: () -> (at: position)

Create a position before the first entry. The walk follows current insertion order.

public get: (key: type is cmp.hashable, item: type,
             value: map(key, item), wanted: key)
            -> (result: item from held value) ! mem.not_found

Copy the value associated with a key. Reports mem.not_found if absent; references inside the copy retain their origin.

public insert: (key: type is cmp.hashable, item: type,
                provider: type is mem.allocator,
                inout value: map(key, item), memory: provider,
                escaping into value added_key: key,
                escaping into value added_item: item)
               -> none ! mem.out_of_memory

Insert a new key/value pair or replace the value of an equal key. New keys append in insertion order; replacement keeps its position. Allocation failure preserves the previous map. Growth can invalidate views.

length

function core/map/map.ldn:90 ↑ index
public length: (key: type is cmp.hashable, item: type,
                value: map(key, item)) -> (count: usize)

Return the number of live key/value entries.

public new: (key: type is cmp.hashable, item: type, seed: cmp.hash_seed)
            -> (result: map(key, item))

Create an empty map without allocating backing, hashing its keys under seed.

next_entry

function core/map/map.ldn:161 ↑ index
public next_entry: (key: type is cmp.hashable, item: type,
                    value: map(key, item), inout at: position)
                   -> (result: entry(key, item) from held value)

Copy the next live key/value pair and advance the position. Call it only while at_end is false: at the end of the walk it stops the program, as a failed check does. Keep the map unchanged during the walk.

Each call follows one live link. Across an unmodified walk, every live entry is returned once in insertion order and the walk costs O(count). The result is what the map holds, a copy of its key and item, and no view of the map's storage.

release

function core/map/map.ldn:809 ↑ index
public release: (key: type is cmp.hashable, item: type,
                 provider: type is mem.allocator,
                 inout value: map(key, item),
                 memory: provider) -> none

Discard all entries, free the map's backing through its original provider and reset it, keeping its seed. Nested resources referred to by keys or values are not freed automatically.

public remove: (key: type is cmp.hashable, item: type,
                inout value: map(key, item), wanted: key)
               -> none ! mem.not_found

Remove a key/value entry without returning it. Reports mem.not_found if absent; preserves the relative order of remaining entries. End existing value pointers and positions before mutation.

removed

function core/map/map.ldn:106 ↑ index
public removed: (key: type is cmp.hashable, item: type,
                 value: map(key, item)) -> (count: usize)

Return how many removed entries still hold their slots until the next rebuild, and so bring it sooner.

reserve

function core/map/map.ldn:852 ↑ index
public reserve: (key: type is cmp.hashable, item: type,
                 provider: type is mem.allocator,
                 inout value: map(key, item), memory: provider,
                 want: usize) -> none ! mem.out_of_memory

Ensure room for at least want entries without a growth allocation: until length reaches want, inserting a new key neither grows nor rebuilds the table, as long as nothing is removed in between. The table is doubled from eight slots until its capacity holds want, and the map is rebuilt once at that size. A table already that large keeps its size: it is rebuilt at it when its removed entries, which hold their slots until a rebuild, leave less room than want, and is otherwise left alone. A rebuild allocates the replacement storage before committing it. Allocation failure frees the partial replacement and preserves every entry; success can invalidate pointers and positions.

public slots: (key: type is cmp.hashable, item: type,
               value: map(key, item)) -> (count: usize)

Return the number of hash slots, the table size capacity is three quarters of.

Example program

The program keeps three maps over one arena, keyed by i32, []u8 and utf8. It inserts keys, replaces one key's item and reads each item back. It finds a []u8 key through equal bytes at another address. It walks the utf8 map's entries in insertion order until map.at_end, and it releases every map.

This complete program is one of the compiler's runtime tests. View source.

compiler/tests/fixtures/runtime/library-builtin-keys/main.ldn134 lines
import core/arena
import core/cmp
import core/map
import core/mem
import core/net
import core/sort
import core/text
import core/time

--  No conformance is declared here: every key and ordering is the library's.

--  Spans sort, and maps key by instants and by addresses, a zone telling
--  two addresses apart as `net.same_address` does.
timed: (memory: arena.arena) -> (ok: bool)
       ! mem.out_of_memory | mem.not_found | net.invalid_address =
    ok = false
    mut spans: [4]time.duration = [time.seconds(1), time.nanoseconds(7),
                                   time.milliseconds(2), time.nanoseconds(0)]
    sort.sort(spans[0..<4])
    return when spans[0] <> time.nanoseconds(0) or spans[1] <> time.nanoseconds(7)
      or spans[2] <> time.milliseconds(2) or spans[3] <> time.seconds(1)

    start: time.instant = time.instant(1000)
    mut deadlines := map.new(key: time.instant, item: u8, seed: test_seed())
    try map.insert(deadlines, memory, start, u8(1))
    try map.insert(deadlines, memory, time.later(start, time.seconds(1)), u8(2))
    try map.insert(deadlines, memory, time.instant(1000), u8(3))
    again: u8 = try map.get(deadlines, start)
    later: u8 = try map.get(deadlines, time.instant(1000001000))
    return when again <> 3 or later <> 2 or map.length(deadlines) <> 2
      or map.contains(deadlines, time.instant(0))

    bare: net.address = net.ipv6_address([0xfe80, 0, 0, 0, 0, 0, 0, 1], 80)
    zoned: net.address = try net.with_zone(bare, "eth0")
    mut peers := map.new(key: net.address, item: u8, seed: test_seed())
    try map.insert(peers, memory, net.loopback(net.ipv4, 80), u8(4))
    try map.insert(peers, memory, bare, u8(6))
    try map.insert(peers, memory, zoned, u8(7))
    read: net.address = try net.parse_address("127.0.0.1:80")
    four: u8 = try map.get(peers, read)
    near: u8 = try map.get(peers, try net.parse_address("[fe80::1%eth0]:80"))
    return when four <> 4 or near <> 7 or map.length(peers) <> 3
      or map.contains(peers, net.loopback(net.ipv4, 81))

    map.release(peers, memory)
    map.release(deadlines, memory)
    ok = true
end timed

exercise: () -> (ok: bool) ! mem.out_of_memory | mem.not_found | text.invalid_text =
    ok = false
    mut backing: [3072]u8 = zeroed
    mut space: arena.space = zeroed
    memory := arena.over_unchecked(space, addr backing[0], lenof backing)

    least: i32 = (0 - 2147483647) - 1
    mut signed := map.new(key: i32, item: u8, seed: test_seed())
    try map.insert(signed, memory, -1, u8(1))
    try map.insert(signed, memory, 0, u8(2))
    try map.insert(signed, memory, least, u8(3))
    first: u8 = try map.get(signed, -1)
    second: u8 = try map.get(signed, 0)
    third: u8 = try map.get(signed, least)
    return when first <> 1 or second <> 2 or third <> 3
    return when map.contains(signed, 1)

    alpha: []u8 = "alpha"
    beta: []u8 = "beta"
    mut names := map.new(key: []u8, item: u32, seed: test_seed())
    try map.insert(names, memory, alpha, u32(1))
    try map.insert(names, memory, beta, u32(2))
    mut spelled: [5]u8 = zeroed
    mut at: usize = 0
    while at < lenof alpha do
        spelled[at] = alpha[at]
        inc at
    end while
    --  Equal bytes at a different address are the same key.
    copied: []u8 = spelled[0..<5]
    found: u32 = try map.get(names, copied)
    return when found <> 1 or map.length(names) <> 2

    mut words := map.new(key: utf8, item: u32, seed: test_seed())
    try map.insert(words, memory, "one", u32(1))
    try map.insert(words, memory, "two", u32(2))
    try map.insert(words, memory, "one", u32(10))
    one: u32 = try map.get(words, "one")
    return when one <> 10 or map.length(words) <> 2
    typed: utf8 = try text.from_bytes("two")
    two: u32 = try map.get(words, typed)
    return when two <> 2

    --  A walk visits each live entry once, in insertion order, and ends
    --  at `map.at_end`; replacing an item kept "one" first.
    mut position := map.entries()
    mut walked: u32 = 0
    mut order: u32 = 0
    while not map.at_end(words, position) do
        entry: map.entry(utf8, u32) = map.next_entry(words, position)
        order = order * 100 + entry.item
        inc walked
    end while
    return when walked <> 2 or order <> 1002

    mut texts: [3]utf8 = ["pear", "apple", "fig"]
    sort.sort(texts[0..<3])
    return when not text.equal(texts[0], "apple") or not text.equal(texts[1], "fig")
      or not text.equal(texts[2], "pear")
    mut numbers: [4]i64 = [3, -5, 0, -1]
    sort.sort(numbers[0..<4])
    return when numbers[0] <> -5 or numbers[1] <> -1 or numbers[2] <> 0
      or numbers[3] <> 3
    mut bytes: [3]u8 = [9, 2, 5]
    sort.sort_selection(bytes[0..<3])
    return when bytes[0] <> 2 or bytes[2] <> 9

    map.release(words, memory)
    map.release(names, memory)
    map.release(signed, memory)
    ok = timed(memory) else false
end exercise

public main: () -> (code: i32) =
    code = 1
    ok := exercise() else false
    if ok then
        code = 42
    end if
end main

--  A constant seed: the same probes and rebuilds on every run.
test_seed: () -> (seed: cmp.hash_seed) =
    seed = cmp.seed_from(1, 2)
end test_seed