Arena

Source: lib/Scratch.cs

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

Arena.Scratch: temporary memory whose lifetime the compiler checks.

int sum = Arena.Scratch(static (scoped ScratchScope s) =>
{
    Span<int> buffer = s.AllocSpan<int>(1000);
    ...
    return total;
});                    // buffer's memory is reused from here on

Everything allocated through the scope is freed when the callback returns, and the compiler makes sure nothing from it is still reachable then: the scope is a ref struct passed as a scoped parameter, so a span or ref it gives out can't be returned, stored in a field or a static, put in the state, or kept in a variable that outlives the callback. Each of those is a compile error, not a dangling pointer. No unsafe block is needed anywhere. The one case the compiler can't see, an outer scope allocating inside a nested Arena.Scratch, stops the program instead (see below).

The memory comes from a scratch arena of the thread's own, not from one of yours, so a List or StrBuilder of yours that grows during the callback grows in its own arena and is unaffected (with Arena.OpenScope it would grow into memory the scope then frees). Scratch calls nest. Each thread keeps its scratch arena for its whole life, sized to the most it ever needed at once.

To pass data in and out without a closure (which would allocate), use the overloads with a state passed by ref; it may be a ref struct holding spans of the caller's. For data that only goes in, or spans the callback fills, there are overloads with an input passed by value.

Besides spans, the scope makes growable lists and text, dictionaries and sets, and pools (items found by a Handle, removed one by one), that live as long:

ScratchList<int> evens = s.List<int>();
ScratchText line = s.Text();
line.Append($"{evens.Count} evens");

They are ref structs too, so the same compile-time rules keep them inside the callback. One rule the compiler can't check: a scope, and the lists and text it made, allocate only while their callback is the innermost one running. Inside a nested Arena.Scratch (reached through a state passed by ref, or an input) the outer ones can still be read and written, but allocating from the scope, adding to a list or appending to text stops the program: that memory would be freed when the inner callback returns.

Members

Scratch

public static void Scratch(ScratchAction action)

Runs action with a scope to allocate temporary memory from, and frees it all when the action returns. The compiler stops anything allocated from the scope from escaping the action.

public static void Scratch<TState>(
    ref TState state,
    ScratchAction<TState> action)

The same, with a state the action can read and change, passed by ref.

public static TResult Scratch<TResult>(ScratchFunc<TResult> func)

The same, returning the action's result, which can't come from the scope's memory.

public static TResult Scratch<TState, TResult>(
    ref TState state,
    ScratchFunc<TState, TResult> func)

The same, with a state and a result.

public static void Scratch<TInput>(TInput input, ScratchActionIn<TInput> action)

The same, with an input the action gets a copy of: for a span of yours, or a ref struct of several, that the action reads or fills. What it writes into a span's items the caller sees; a change to the copy itself it doesn't.

public static TResult Scratch<TInput, TResult>(
    TInput input,
    ScratchFuncIn<TInput, TResult> func)

The same, returning the action's result.

ScratchScope

Allocates memory that lives until the Arena.Scratch callback it was given to returns.

AllocSpan

public Span<T> AllocSpan<T>(int count) where T : unmanaged

A zeroed span of count items, valid until the callback returns.

Alloc

public ref T Alloc<T>() where T : unmanaged

A zeroed T, valid until the callback returns.

List

public ScratchList<T> List<T>(int initialCapacity = 16) where T : unmanaged

An empty list whose items live until the callback returns.

Dict

public ScratchDict<TKey, TValue> Dict<TKey, TValue>(int capacity = 32)

An empty dictionary whose entries live until the callback returns.

HashSet

public ScratchHashSet<T> HashSet<T>(int capacity = 32) where T : unmanaged

An empty set whose items live until the callback returns.

Pool

public ScratchPool<T> Pool<T>(int chunkSize = 64) where T : unmanaged

An empty pool whose items live until the callback returns.

Text

public ScratchText Text(int initialCapacity = 64)

Empty text, for building a string that lives until the callback returns.

ScratchList

A growable list from ScratchScope.List{T}, freed when the Arena.Scratch callback returns. Copies share the same items.

Count

public int Count

How many items the list holds.

this[]

public ref T this[int index]

The item at index; out of range stops the program.

Add

public void Add(T item)

Appends an item, growing the list if it is full.

AddRange

public void AddRange(ReadOnlySpan<T> items)

Appends each of items.

RemoveAt

public bool RemoveAt(int index)

Removes the item at index, moving the later ones down. False if out of range.

Clear

public void Clear()

Removes every item; the memory stays the list's.

AsSpan

public Span<T> AsSpan()

The items, valid until the callback returns. After Add, RemoveAt or Clear it may show the items as they were, but its memory stays valid.

GetEnumerator

public Span<T>.Enumerator GetEnumerator()

For foreach: the items, as AsSpan shows them.

ScratchDict

A dictionary from ScratchScope.Dict{TKey, TValue}, freed when the Arena.Scratch callback returns; keys are compared as Dict's are. Clone copies it into an arena you keep. Copies share the same entries.

Count

public int Count

How many keys it holds.

Set

public void Set(TKey key, TValue value)

Adds the key or changes its value.

TryAdd

public bool TryAdd(TKey key, TValue value)

Adds the key if it isn't there. False if it was.

TryGet

public bool TryGet(TKey key, out TValue value)

The key's value, if it is there.

ContainsKey

public bool ContainsKey(TKey key)

Whether the key is there.

Remove

public bool Remove(TKey key)

Removes the key. False if it wasn't there.

Clear

public void Clear()

Removes every key.

GetEnumerator

public Dict<TKey, TValue>.Enumerator GetEnumerator()

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

Clone

public Dict<TKey, TValue> Clone(Arena target)

A copy in target, an arena you keep: how the result leaves the callback.

ScratchHashSet

A set from ScratchScope.HashSet{T}, freed when the Arena.Scratch callback returns; items are compared as HashSet's are. Clone copies it into an arena you keep. Copies share the same items.

Count

public int Count

How many items it holds.

Add

public bool Add(T item)

Adds the item. False if it was already there.

Contains

public bool Contains(T item)

Whether the item is there.

Remove

public bool Remove(T item)

Removes the item. False if it wasn't there.

Clear

public void Clear()

Removes every item.

GetEnumerator

public HashSet<T, DefaultEqualityComparer<T>>.Enumerator GetEnumerator()

For foreach: every item, in no particular order.

Clone

public HashSet<T> Clone(Arena target)

A copy in target, an arena you keep: how the result leaves the callback.

ScratchPool

A pool from ScratchScope.Pool{T}, freed when the Arena.Scratch callback returns: items found by a Handle, removed one by one, and moved out with MoveTo into a pool you keep. Copies share the same items.

A handle is a plain struct and can outlive the callback, but it finds nothing without its pool, which can't.

Count

public int Count

How many items the pool holds.

Add

public Handle<T> Add(T item)

Adds an item and returns its handle.

this[]

public ref T this[Handle<T> handle]

The item the handle finds; one removed or moved stops the program.

Contains

public bool Contains(Handle<T> handle)

Whether the handle finds an item.

TryGet

public bool TryGet(Handle<T> handle, out T item)

The item the handle finds, if it finds one.

Remove

public bool Remove(Handle<T> handle)

Removes the item the handle finds. False if it finds none.

Move

public Handle<T> Move(ref Handle<T> handle)

Gives the item a new handle; the old one and its copies are refused from then on.

MoveTo

public Handle<T> MoveTo(Pool<T> target, ref Handle<T> handle)

Moves the item into target, a pool you keep, and returns its handle there: how a result leaves the callback.

Clear

public void Clear()

Removes every item.

GetEnumerator

public Pool<T>.Enumerator GetEnumerator()

For foreach: the handle of each item.

ScratchText

Growable text from ScratchScope.Text, with $"..." support, freed when the Arena.Scratch callback returns. Copies share the same text.

Length

public int Length

How many chars the text holds.

AsSpan

public ReadOnlySpan<char> AsSpan()

The text so far, valid until the callback returns.

Append

public void Append(ReadOnlySpan<char> text)

Appends text.

public void Append(char value)

Appends one char.

public void Append(long value)

Appends a number in decimal.

public void Append(int value)

Appends a number in decimal.

public void Append(double value)

Appends a number as $"" writes it.

public void Append(bool value)

Appends True or False.

public void Append(ref StrBuilder.InterpolatedHandler handler)

Appends $"..." directly, without an intermediate string.

this[]

public char this[int index]

The char at index; stops the program if it is out of range.

Insert

public void Insert(int index, ReadOnlySpan<char> text)

Puts text before the char at index (at the end when it is Length).

public void Insert(int index, char value)

Puts one char before the char at index.

public void Insert(int index, long value)

Puts a number, in decimal, before the char at index.

public void Insert(int index, int value)

Puts a number, in decimal, before the char at index.

Remove

public void Remove(int startIndex, int length)

Removes length chars from startIndex.

Replace

public void Replace(char oldChar, char newChar)

Replaces every oldChar with newChar.

public void Replace(char oldChar, char newChar, int startIndex, int count)

Replaces oldChar with newChar in the count chars from startIndex.

public void Replace(ReadOnlySpan<char> oldValue, ReadOnlySpan<char> newValue)

Replaces every oldValue with newValue, left to right.

public void Replace(
    ReadOnlySpan<char> oldValue,
    ReadOnlySpan<char> newValue,
    int startIndex,
    int count)

Replaces the oldValues that lie wholly within the count chars from startIndex.

Clear

public void Clear()

Empties the text; the memory stays the text's.

ToArenaString

public string ToArenaString(Arena target)

Copies the text into a new string in target, to keep after the callback returns. Returns null if the target is out of memory.