StrDict

Source: lib/StrDict.cs

This page is generated from the source by scripts/gen-reference.py.

StrDict: hash map with string keys compared by their text, in an Arena. Values can be of any type: numbers, structs, strings or other references.

StrDict<int> counts = StrDict<int>.Create(keep);
int length = In.ReadLine(buffer);
ReadOnlySpan<char> word = buffer.Slice(0, length);
counts.TryGet(word, out int n);              // looks up a span: no allocation
counts.Set(word, n + 1);                     // a new key is copied into keep

Keys are taken as ReadOnlySpan (a string converts implicitly) and a new key is copied into the map's arena, so the map never depends on where its keys came from: a buffer that is overwritten, or a scratch arena that is reset. A removed key's copy stays allocated until the arena is reset.

Values are stored as they are. A reference value (a string, say) points wherever it was allocated and must outlive the map's use of it, as in RefList.

Like Dict, StrDict is a handle to a header in the arena, so copies share contents, and default(StrDict) is "not created" (lookups miss, Set fails). Open addressing with linear probing, kept at most 3/4 full; keys are hashed with FNV-1a over their chars.

Members

Create

public static StrDict<TValue> Create(Arena arena, int capacity = 32)

Returns a new map in arena, or a not-created map if it is out of memory.

IsCreated

public bool IsCreated

Count

public int Count

Set

public bool Set(ReadOnlySpan<char> key, TValue value)

Inserts or overwrites. A new key is copied into the map's arena. Returns false if the map isn't created or the arena is full.

TryGet

public bool TryGet(ReadOnlySpan<char> key, out TValue value)

ContainsKey

public bool ContainsKey(ReadOnlySpan<char> key)

Remove

public bool Remove(ReadOnlySpan<char> key)

Removes a key. Returns false if it wasn't there.

Clone

public StrDict<TValue> Clone(Arena target)

Returns an independent copy in target, keys included, so it outlives this map's arena. Returns a not-created map if this one isn't created or the target is out of memory.

Values are copied as they are: a reference value still points at the same object, wherever that lives.

GetEnumerator

public Enumerator GetEnumerator()

For foreach: every key and value, in no particular order.

Don't Set or Remove during the loop: entries move, so some may be skipped or seen twice.

StrDict.Pair

A key with its value, as foreach yields them.

Key

public string Key

Value

public TValue Value