Lists & dicts
Growable sequences and hash tables come from the standard library: List in libstd/list, five dictionary flavours in libstd/dict, plus literal syntax for the common cases.
List
A List is a growable array of ref with amortised O(1) append. Any pointer goes in without a cast (a str, an object, an array) and comes back with as str/as ClassName, a checked downcast for a class. For a growable sequence of numbers there is LongList (llist_new, llist_push, llist_get, llist_set, llist_pop_back, llist_length, llist_clear), the same structure over long.
#include <libstd/stdio>
#include <libstd/list>
class Point:
x int
y int
lst = list_new()
list_push(lst, "ten")
list_push(lst, "twenty")
list_push(lst, "thirty")
print(list_length(lst), " ", list_get(lst, 1 as long) as str, "\n")
last = list_pop_back(lst) as str // thirty
list_set(lst, 0 as long, "ninety-nine")
p = new Point()
p.x = 3
list_push(lst, p) // an object: ref, counted
q = list_peek_back(lst) as Point // checked
print(q.x, "\n")
i = 0 as long
while i < list_length(lst) - 1 as long:
print(list_get(lst, i) as str, " ")
i = i + 1 as long
print("\n")
3 twenty
3
ninety-nine twenty
| Function | Cost | Does |
|---|---|---|
list_new(), list_new_cap(n) | empty list; the second pre-allocates n slots | |
list_push(l, v) | O(1) amortised | append |
list_push_first(l, v), list_pop_front(l) | O(n) | insert/remove at the front (shifts the elements) |
list_pop_back(l), list_peek_back(l), list_peek_front(l) | O(1) | undefined on an empty list: check list_is_empty first |
list_get(l, i), list_set(l, i, v) | O(1) | index must be < list_length(l) |
list_length(l), list_is_empty(l), list_clear(l) | O(1) | list_clear keeps the capacity |
list_get_range(l, a, b), list_merge(l1, l2), list_cpy(dst, src) | O(n) | new lists / copy; the results never share buffers with the sources |
Indices and lengths are long, so literals need as long; an int variable widens automatically when passed as an argument.
List literals
[10, 20, 30] is a fixed array (int[3]), not a List: it cannot grow, but it is indexed directly and bounds-checked. See Arrays.
Dictionaries
All dictionaries are open-addressing hash tables (linear probing, tombstones on delete); four are keyed by str (a word-at-a-time hash, cached per slot) and differ in the value type, idict_* is keyed by int. The handle is a str pointer.
| Flavour | Values | Create | Missing key |
|---|---|---|---|
dict_* | int | dict_new(cap) | dict_get returns -1 |
sdict_* | str; an object with sdict_set_ref/sdict_set_grow_ref, read back as sdict_get(d, k) as Class | sdict_new(cap) | sdict_get returns "" |
vdict_* | int, long or str, tagged | vdict_new(cap) | vdict_type_of returns 0 |
adict_* | boxed values of any type, including other dicts | adict_new(cap) | adict_get returns "" |
idict_* | str, with int keys | idict_new(cap) | idict_get returns "" |
#include <libstd/stdio>
#include <libstd/dict>
d = dict_new(8) // capacity is rounded up to a power of two
dict_set(d, "ciao", 10)
dict_set(d, "mondo", 20)
dict_set(d, "ciao", 99) // update
print(dict_get(d, "ciao"), " ", dict_has(d, "assente"), " ", dict_count(d), "\n")
dict_del(d, "ciao")
names = sdict_new(4)
sdict_set(names, "nome", "federico")
print(sdict_get(names, "nome"), "\n")
99 0 2
federico
A fixed-capacity table returns 0 from *_set when it is full. idict_set_grow (for a dict_*, despite the name) and sdict_set_grow double the table instead and return the (possibly new) handle, which must be reassigned: d = sdict_set_grow(d, key, value). They double before the entries pass half the slots: with linear probing, a lookup for a missing key walks every occupied slot in a row, so a table kept below half full answers a miss in about two probes.
Dict literals
counts = {"a": 1, "b": 2, "c": 3} // str -> int, a dict_*
words = {"x": "hello", "y": "world"} // str -> str, an sdict_*
codes = {200: "OK", 404: "Not Found"} // int -> str, an idict_*
print(dict_get(counts, "b"), " ", sdict_get(words, "y"), " ", idict_get(codes, 404), "\n")
The literal picks the flavour from the value types (all int → dict, all str → sdict, mixed scalars → adict with boxes) and sizes the table for the entries given. The keys are all str or all int; with int keys the values are str (an idict). A repeated key keeps the last value.
Iterating an sdict
it = dict_iter_new(words)
while dict_iter_has_next(it):
k, v = dict_iter_next(it)
print(k, "=", v, "\n")
dict_iter_del_current(it) removes the last returned pair safely during the iteration; sdict_iter(d) returns the keys and values as two parallel arrays instead.
The Sdict class
Sdict (in libstd/dict) keeps an sdict table in an object with methods. When the table grows only the object's table field changes, so there is no handle to reassign, and every sdict_* function still works on d.table. Create it with Sdict_new(capacity), which allocates the table: new Sdict() alone already has the methods but no table yet.
ages = Sdict_new(4)
ages.set("anna", "31")
ages.set("bruno", "27")
ages.set("carla", "45") // grows by itself
print(ages.get("bruno"), " ", ages.has("dario"), " ", ages.count(), "\n")
ages.reset()
while ages.next():
print(ages.key(), "=", ages.value(), " ")
print("\n")
27 0 3
carla=45 anna=31 bruno=27
The loop needs no iterator object: next() moves a cursor kept in the Sdict itself (the slot index iter_idx, the current pair in iter_key and iter_value) and returns 0 at the end. The order is the table's, not the insertion order. Removing the current entry inside the loop is safe; an insertion that makes the table grow replaces it under the cursor. There is one cursor per object, so two nested loops over the same Sdict, or a function called inside the loop that iterates it again, move each other's cursor. There, walk the slots directly:
i = sdict_next_slot(ages.table, 0)
while i >= 0:
print(sdict_key_at(ages.table, i), " ")
i = sdict_next_slot(ages.table, i + 1)
Nested and mixed values: adict
inner = adict_new(4)
adict_set(inner, "x", box_int(10))
outer = adict_new(4)
adict_set(outer, "config", box_dict(inner))
adict_set(outer, "nome", box_str("federico"))
adict_set(outer, "big", box_long(9999999999))
v = adict_get(outer, "config")
if adict_type_id(v) == 4: // 4 = dict
print(unbox_int(adict_get(unbox_dict(v), "x")), "\n")
Check adict_has before adict_get: the "" sentinel of a missing key is not a box, and adict_type_id("") reads garbage.
JSON
libstd/json gives every JSON value an object of class Json: json_parse(text) or json_load(path) returns the root, get(key), at(i) and get_str, get_int... read it, set and push change it, dumps() writes it back. Its objects keep their keys in insertion order, with a dict_* index once they grow past a few keys.
Containers and the arena
A list or a dict holds a counted reference to each value it stores, like a field: the value lives as long as the container (or anyone else) holds it, and is freed when it is removed, overwritten or when the container itself goes, if nothing else holds it. A value read with list_get or sdict_get and kept in a local stays valid even if the container drops it afterwards. Only dict_poke64, which writes a pointer into raw memory, pins the value for the rest of the program. See The arena.