Ptr

Source: lib/Ptr.cs

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

Ptr: a typed pointer to one item in an Arena, for linking items together.

public struct Node
{
    public int Number;
    public Ptr<Node> Prev;
    public Ptr<Node> Next;
}
Ptr<Node> a = arena.New(new Node { Number = 1 });
Ptr<Node> b = arena.New(new Node { Number = 2 });
a.Value.Next = b;
b.Value.Prev = a;              // a cycle, no unsafe needed

A struct can't contain itself, so linked lists, trees and graphs need a pointer between items. Ptr is one that needs no unsafe in your code: Value gives a ref to the item, and a null Ptr (the default) stops the program when used instead of crashing it.

Like a List, a Ptr is valid until its arena is reset, destroyed or restored to before the item was made: the unsafe calls whose caller promises that nothing still uses that memory. Under Arena.DebugChecks, a Ptr used after that stops the program. An item lives as long as its arena; there is no freeing one item on its own.

A Ptr is a pointer and its arena (16 bytes on 64-bit machines), so it can make that check, and copies of it point at the same item.

Value hands out a ref into the arena without unsafe, unlike AllocSpan and List.AsSpan. An item never moves (List.AsSpan is unsafe because Add can move the items) and only those unsafe calls free it, so a ref from Value is good for as long as the Ptr is. DebugChecks only sees uses of Value, though: a ref kept in a local and used after a Reset goes unnoticed.

A pointer to an item in an arena, from Arena.New{T}(T).

Members

IsNull

public bool IsNull

True for the default Ptr, which points at nothing.

Value

public ref T Value

The item, to read or change in place. A null Ptr stops the program.

Equals

public bool Equals(Ptr<T> other)

Whether both point at the same item (not whether the items are equal).

public override bool Equals(object obj)

Whether obj is a Ptr to the same item.

GetHashCode

public override int GetHashCode()

A hash of the address, matching Equals.

operator ==

public static bool operator ==(Ptr<T> left, Ptr<T> right)

Whether both point at the same item.

operator !=

public static bool operator !=(Ptr<T> left, Ptr<T> right)

Whether they point at different items.

Arena

New

public Ptr<T> New<T>(T value) where T : unmanaged

Copies value into the arena and returns a pointer to it, or a null Ptr if the arena is out of memory.

public Ptr<T> New<T>() where T : unmanaged

A zeroed item in the arena, or a null Ptr if it is out of memory.