Skip to content

Any

Spice
import "std/type/any";

Any struct

Any is a type-erased container that can hold a value of an arbitrary type.

It is the Spice equivalent of C++'s std::any and is primarily used as the return type of the AST visitor, where different passes (and different visit methods) yield different result types. The stored type is identified via the typeid builtin, so retrieval is checked: requesting the wrong type panics.

Trivially-copyable and -destructible payloads up to ANY_INLINE_BYTES (a single pointer-sized slot) are stored inline to avoid a heap allocation. All other payloads - larger ones, and non-trivial ones - are boxed on the heap. For non-trivial payloads, Any captures the type's copy constructor and destructor as thunks at construction time and runs them on copy/destroy, just like a std::any manager. Non-trivial types are therefore always heap-boxed, which makes heapStore != nil a reliable "owns a live payload" signal and keeps the destructor correct under move/return (a moved-from Any has heapStore nil'd).

Note: non-trivial payloads must follow the std convention of public copy constructor and destructor.

Constructors

ctor

Spice
public p Any.ctor()

Initialize an empty Any.

ctor

Spice
public p Any.ctor(const Any& original)

Copy-construct an Any, deep-copying the payload so that both instances own independent storage. Non-trivial payloads are copied via their copy ctor.

Parameters

Name Type Description
original const Any&

dtor

Spice
public p Any.dtor()

Destroy the held payload (if any) and release its storage.

Methods

isStoredInline

Spice
public inline f<bool> Any.isStoredInline()

Returns if the data is stored in the inline buffer.

Returns: bool

set

Spice
public p Any.set<T>(const T& value)

Stores a value of arbitrary type T, type-erasing it into the Any. Replaces and destroys any previously held value.

Parameters

Name Type Description
value const T& Value to store

get

Spice
public inline f<T&> Any.get<T>()

Retrieves the stored value as type T. Panics if the Any does not currently hold a value of type T.

Returns: T& — Reference to the stored value

has

Spice
public inline f<bool> Any.has<T>()

Checks whether the Any currently holds a value of type T.

Returns: bool — Holds T or not

isEmpty

Spice
public inline f<bool> Any.isEmpty()

Checks whether the Any is empty (holds no value).

Returns: bool — Empty or not

getTypeId

Spice
public inline f<long> Any.getTypeId()

Returns the typeid of the stored value, or 0 if the Any is empty.

Returns: long — typeid of stored value

Functions

any

Spice
public f<Any> any<T>(const T& value)

Constructs an Any holding the given value.

Parameters

Name Type Description
value const T& Value to store

Returns: Any — Any wrapping the value

Operators

operator=

Spice
public p operator=<T>(Any& this, const Any& newValue)

Deep-copy assignment. Destroys and releases the currently held payload first.

Parameters

Name Type Description
newValue const Any&