Crate facet

Crate facet 

Source
Expand description

§facet

Coverage Status crates.io documentation MIT/Apache-2.0 licensed Discord

facet provides reflection for Rust: it gives types a SHAPE associated const with details on the layout, fields, doc comments, attributes, etc.

It can be used for many things, from (de)serialization to pretty-printing, rich debuggers, CLI parsing, reflection in templating engines, code generation, etc.

See https://facet.rs for details.

§Workspace contents

The main facet crate re-exports symbols from:

  • facet-core, which defines the main components:
    • The Facet trait and implementations for foreign types (mostly libstd)
    • The Shape struct along with various vtables and the whole Def tree
    • Type-erased pointer helpers like PtrUninit, PtrConst, and Opaque
    • Autoderef specialization trick needed for facet-macros
  • facet-macros, which implements the Facet derive attribute as a fast/light proc macro powered by unsynn

For struct manipulation and reflection, we have:

  • facet-reflect, allows building values of arbitrary shapes in safe code, respecting invariants. It also allows peeking at existing values.

Internal crates include:

  • facet-testhelpers a simple log logger and color-backtrace configured with the lightweight btparse backend

§Ecosystem

Various crates live under the https://github.com/facet-rs umbrella, and their repositories are kept somewhat-consistent through facet-dev.

Crates are in various states of progress, buyer beware!

In terms of data formats, we have:

Still adjacent to serialization/deserialization, we have:

As far as utilities go:

And the less developed:

  • facet-inspect: Utilities to inspect the content of a Facet object

§Extended cinematic universe

Some crates are developed completely independently from the facet org:

  • facet-v8 provides an experimental Facet/v8 integration
  • facet-openapi (experimental) Generates OpenAPI definitions from types that implement Facet
  • facet_generate reflects Facet types into Java, Swift and TypeScript
  • multi-array-list provides an experimental MultiArrayList type

§Sponsors

Thanks to all individual sponsors:

GitHub Sponsors Patreon

…along with corporate sponsors:

AWS Zed Depot

…without whom this work could not exist.

§Special thanks

The facet logo was drawn by Misiasart.

§License

Licensed under either of:

at your option.

Modules§

builtin
Built-in facet attributes.
specialization
Auto-deref specialization helpers for the Facet reflection system

Macros§

bitflags
Defines a bitflags struct with the given flags.
builder_def
Generates a builder struct and basic setter methods.
debugreflect and non-log
Forwards to log::debug when the log feature is enabled
define_attr_grammar
Define an attribute grammar with type-safe parsing.
tracereflect and non-log
Forwards to log::trace when the log feature is enabled
type_ops_direct
Creates a TypeOpsDirect for a type by specifying which traits it implements.
vtable_direct
Creates a VTableDirect for a type by specifying which traits it implements.
vtable_indirect
Creates a VTableIndirect for generic container types by specifying which traits it implements.

Structs§

ArrayDef
Fields for array types
ArrayType
Describes a fixed-size array ([T; N])
ArrayVTable
Virtual table for an array
ArrayVTableBuilder
Builder for the vtable
Attr
An attribute attaches metadata to a container or a field
ConstTypeId
TypeId equivalent usable in const contexts.
CovariantPeekreflect
A covariant wrapper around Peek for types that are covariant over their lifetime parameter.
DefArrayBuilder
Builder that produces Def::Array(...).
DefListBuilder
Builder that produces Def::List(...).
DefMapBuilder
Builder that produces Def::Map(...).
DefOptionBuilder
Builder that produces Def::Option(...).
DefResultBuilder
Builder that produces Def::Result(...).
DefSetBuilder
Builder that produces Def::Set(...).
DuplicateFieldErrorreflect
Error when building a resolution.
DynamicValueDef
Definition for dynamic value types.
DynamicValueVTable
Virtual table for dynamic value types.
EnumType
Fields for enum types
EnumTypeBuilder
Builder for constructing EnumType instances in const contexts.
Field
Describes a field in a struct or tuple
FieldBuilder
Builder for constructing Field instances in const contexts.
FieldFlags
Bit flags for common field attributes.
FieldInforeflect
Information about a single field in a resolution.
FieldItemreflect
A field item with runtime state for serialization.
FieldIterreflect
An iterator over all the fields of a struct or enum. See HasFields::fields
FieldPathreflect
A path through the type tree to a field.
FieldsForSerializeIterreflect
An iterator over the fields of a struct or enum that should be serialized. See HasFields::fields_for_serialize
FunctionPointerDef
Common fields for function pointer types
Guardreflect
A guard structure to manage memory allocation and deallocation.
HashProxy
A proxy type that wraps &mut dyn Hasher and implements Hasher.
HeapValuereflect
A type-erased value stored on the heap
IterVTable
VTable for an iterator
ListDef
Fields for list types
ListTypeOps
Per-type list operations that must be monomorphized.
ListTypeOpsBuilder
Builder for ListTypeOps.
ListVTable
Virtual table for shareable list operations.
ListVTableBuilder
Builder for the vtable
LockGuardVTable
Functions for manipulating a guard
LockResult
Type-erased result of locking a mutex-like pointer
MapDef
Fields for map types
MapVTable
Virtual table for a Map<K, V>
MapVTableBuilder
Builder for the vtable
MarkerTraits
Bitflags tracking implementation of Rust’s marker/auto traits.
NativeWidePtr
A wide pointer in native platform layout.
NdArrayDef
Fields for n-dimensional array types
NdArrayVTable
Virtual table for a n-dimensional array type (like Matrix<T>, Tensor<T>, etc.)
Opaque
Wrapper for struct fields whose types we don’t want to expose. Prevents direct access while preserving layout.
OptionDef
Describes an Option — including a vtable to query and alter its state, and the inner shape (the T in Option<T>).
OptionVTable
Virtual table for Option<T>
OptionVTableBuilder
Builder for the vtable
OwnedPeekreflect
An Owned version of a Peek used for custom serialization
OxMut
Safe mutable reference with shape.
OxPtrConst
Read-only shaped pointer for vtable use.
OxPtrMut
Mutable shaped pointer for vtable use.
OxPtrUninit
Uninitialized shaped pointer for vtable use.
OxRef
Safe read-only reference with shape.
Partialreflect
A type-erased, heap-allocated, partially-initialized value.
Peekreflect
A read-only view into a value with runtime type information.
PeekDynamicValuereflect
Lets you read from a dynamic value (implements read-only operations for DynamicValue types)
PeekDynamicValueArrayIterreflect
Iterator over array elements in a dynamic value
PeekDynamicValueObjectIterreflect
Iterator over object entries in a dynamic value
PeekEnumreflect
Lets you read from an enum (implements read-only enum operations)
PeekListreflect
Lets you read from a list (implements read-only facet_core::ListVTable proxies)
PeekListIterreflect
Iterator over a PeekList
PeekListLikereflect
Lets you read from a list, array or slice
PeekListLikeIterreflect
Iterator over a PeekListLike
PeekMapreflect
Lets you read from a map (implements read-only facet_core::MapVTable proxies)
PeekMapIterreflect
Iterator over key-value pairs in a PeekMap
PeekNdArrayreflect
Lets you read from an n-dimensional array (implements read-only facet_core::NdArrayVTable proxies)
PeekOptionreflect
Lets you read from an option (implements read-only option operations)
PeekPointerreflect
Represents a pointer that can be peeked at during memory inspection.
PeekResultreflect
Lets you read from a result (implements read-only result operations)
PeekSetreflect
Lets you read from a set
PeekSetIterreflect
Iterator over values in a PeekSet
PeekStructreflect
Lets you read from a struct (implements read-only struct operations)
PeekTuplereflect
Lets you read from a tuple
PointerDef
Describes a pointer — including a vtable to query and alter its state, and the inner shape (the pointee type in the pointer).
PointerFlags
Flags to represent various characteristics of pointers
PointerVTable
Functions for interacting with a pointer
Pokereflect
A mutable view into a value with runtime type information.
PokeEnumreflect
Lets you mutate an enum’s fields.
PokeStructreflect
Lets you mutate a struct’s fields.
ProxyDefalloc
Definition of a proxy type for custom serialization/deserialization.
PtrConst
A type-erased read-only pointer.
PtrMut
A type-erased mutable pointer (wide pointer) holding a data pointer and metadata.
PtrUninit
A type-erased pointer to uninitialized memory.
Repr
Describes base representation of the type
Resolutionreflect
One possible “shape” the flattened type could take.
ResultDef
Describes a Result — including a vtable to query and alter its state, and the inner shapes (the T and E in Result<T, E>).
ResultVTable
Virtual table for Result<T, E>
ResultVTableBuilder
Builder for the vtable
SetDef
Fields for set types
SetVTable
Virtual table for a Set<T>
SetVTableBuilder
Builder for the vtable
Shape
Schema for reflection of a type — the core type in facet. Contains everything needed to inspect, allocate, and manipulate values at runtime.
ShapeBuilder
Builder for creating Shape instances.
ShapeFlags
Bit flags for common shape-level attributes.
ShapeRef
A lazy reference to a Shape via a function pointer.
SliceBuilderVTable
Functions for creating and manipulating slice builders.
SliceDef
Fields for slice types
SliceType
Describes a slice ([T])
SliceVTable
Virtual table for a slice-like type (like Vec<T>, but also HashSet<T>, etc.)
Spanreflect
Source span with offset and length.
Spannedreflect
A value with source span information.
StructType
Common fields for struct-like types
StructTypeBuilder
Builder for StructType to enable shorter derive macro output
TaggedPtr
A pointer that uses the high bit (bit 63) as a tag to indicate wide vs thin.
TupleTypereflect
Local representation of a tuple type for peek operations
TypeEnumBuilder
Builder that produces Type::User(UserType::Enum(...)).
TypeNameDisplay
A wrapper around &'static Shape that implements Display using the full type name (including generic parameters).
TypeNameOpts
Options for formatting the name of a type.
TypeOpsDirect
Type-specific operations for concrete types (uses thin pointers).
TypeOpsIndirect
Type-specific operations for generic containers (uses wide pointers with shape).
TypeParam
Represents a lifetime parameter, e.g., 'a or 'a: 'b + 'c.
TypeStructBuilder
Builder that produces Type::User(UserType::Struct(...)).
TypeUnionBuilder
Builder that produces Type::User(UserType::Union(...)).
TypedVTableDirectBuilder
Type-safe builder for VTableDirect.
UnionType
Common fields for union types
UnionTypeBuilder
Builder for constructing UnionType instances in const contexts.
UnsizedError
Tried to get the Layout of an unsized type
VTableDirect
VTable for concrete types with compile-time known traits.
VTableIndirect
VTable for generic containers with runtime trait resolution.
ValueIdreflect
A unique identifier for a peek value
ValuePointerType
Describes the raw/reference pointer
Variant
Describes a variant of an enum
VariantBuilder
Builder for constructing Variant instances in const contexts.
VariantSelectionreflect
Records that a specific enum field has a specific variant selected.

Enums§

BaseRepr
Underlying byte layout representation
Characteristic
A characteristic a shape can have
Def
The semantic definition of a shape: is it more like a scalar, a map, a list?
DefaultSource
Source of a field’s default value.
DynDateTimeKind
The kind of datetime value (for dynamic value datetime support).
DynValueKind
The kind of value stored in a dynamic value.
EnumRepr
All possible representations for Rust enums — ie. the type/size of the discriminant
FieldError
Errors encountered when calling field_by_index or field_by_name
FunctionAbi
The calling ABI of a function pointer
KnownPointer
Represents common standard library pointer kinds
ListLikeDefreflect
Fields for types which act like lists
MatchResultreflect
Result of matching input fields against a resolution.
NumericType
Describes numeric types (integer/float)
Ox
Type-erased value with ownership tracking — like Cow but for any shape.
ParseError
Error returned by parse operations.
PathSegmentreflect
A segment in a field path.
PointerType
Describes all pointer types
PrimitiveType
Describes built-in primitives (u32, bool, str, etc.)
PtrKind
The kind of a pointer based on its size.
ReflectErrorreflect
Errors that can occur when reflecting on types.
ScalarType
All scalar types supported out of the box by facet.
SequenceType
Describes built-in sequence type (array, slice)
ShapeLayout
Layout of the shape
StrideErrorreflect
Error that can occur when trying to access an n-dimensional array as strided
StructKind
Describes the kind of struct (useful for deserializing)
TextualType
Describes textual types (char/string)
TrackerKindreflect
A kind-only version of Tracker
TryBorrowInnerError
Error returned when try_borrow_inner fails.
TryFromError
Error returned when try_from fails to convert a value.
TryIntoInnerError
Error returned when try_into_inner fails.
Type
The definition of a shape in accordance to rust reference:
TypeOps
Type-erased TypeOps that can hold either Direct or Indirect style.
UserType
User-defined types (structs, enums, unions)
VTableErased
Type-erased VTable that can hold either Direct or Indirect style.
Variance
Variance of a type with respect to its type/lifetime parameters.
VariantErrorreflect
Error that can occur when trying to determine variant information

Constants§

MAX_VARIANCE_DEPTH
Maximum recursion depth for variance computation to prevent stack overflow on recursive types.

Traits§

Facet
Allows querying the Shape of a type, which in turn lets us inspect any fields, build a value of this type progressively, etc.
HasFieldsreflect
Trait for types that have field methods
IterItem
A kind of item that an IterVTable returns
Write
A no_std compatible write trait used by facet serializers.

Functions§

find_span_metadata_fieldreflect
Find the span metadata field in a struct shape.
get_spanned_inner_shapereflect
Extract the inner value shape from a Spanned-like struct.
is_spanned_shapereflect
Check if a shape represents a type with span metadata (like Spanned<T>).
of
Create a TypeId for a type.
peek_enumreflect
Returns the enum definition if the shape represents an enum, None otherwise
peek_enum_reprreflect
Returns the enum representation if the shape represents an enum, None otherwise
peek_enum_variantsreflect
Returns the enum variants if the shape represents an enum, None otherwise
ptr_kind
Determines the pointer kind for a given type.
shape_of
Returns the shape of a type as a function pointer.

Type Aliases§

ArrayAsMutPtrFn
Get mutable pointer to the data buffer of the array.
ArrayAsPtrFn
Get pointer to the data buffer of the array.
BorrowFn
Tries to obtain a reference to the inner value of the pointer.
DefaultInPlaceFn
Function type for default initialization in-place. Used by the #[facet(default)] attribute.
DowngradeIntoFn
Downgrades a strong pointer to a weak one.
DynArrayGetFn
Get an element from an array by index. Returns None if not an array or index out of bounds.
DynArrayLenFn
Get the length of an array. Returns None if not an array.
DynBeginArrayFn
Initialize the value as an empty array.
DynBeginObjectFn
Initialize the value as an empty object.
DynEndArrayFn
Finalize the array (optional, for shrinking capacity etc.).
DynEndObjectFn
Finalize the object (optional, for shrinking capacity etc.).
DynGetBoolFn
Get a boolean value. Returns None if not a bool.
DynGetBytesFn
Get a bytes reference. Returns None if not bytes.
DynGetDateTimeFn
Get datetime components from a datetime value.
DynGetF64Fn
Get a 64-bit float value. Returns None if not a number.
DynGetI64Fn
Get a signed 64-bit integer value. Returns None if not representable as i64.
DynGetKindFn
Get the kind of value stored.
DynGetStrFn
Get a string reference. Returns None if not a string.
DynGetU64Fn
Get an unsigned 64-bit integer value. Returns None if not representable as u64.
DynInsertObjectEntryFn
Insert a key-value pair into the object.
DynObjectGetEntryFn
Get a key-value pair from an object by index. Returns None if not an object or index out of bounds.
DynObjectGetFn
Get a value from an object by key. Returns None if not an object or key not found.
DynObjectGetMutFn
Get a mutable reference to a value from an object by key. Returns None if not an object or key not found.
DynObjectLenFn
Get the length of an object. Returns None if not an object.
DynPushArrayElementFn
Push an element to the array.
DynSetBoolFn
Set the value to a boolean.
DynSetBytesFn
Set the value to bytes.
DynSetDateTimeFn
Set the value to a datetime.
DynSetF64Fn
Set the value to a 64-bit float.
DynSetI64Fn
Set the value to a signed 64-bit integer.
DynSetNullFn
Set the value to null.
DynSetStrFn
Set the value to a string.
DynSetU64Fn
Set the value to an unsigned 64-bit integer.
FieldAttribute
An attribute that can be set on a field. This is now just an alias for ExtensionAttr - all attributes use the same representation.
InvariantsFn
Function type for type invariant validation. Used by the #[facet(invariants = fn)] attribute.
IterDeallocFn
Deallocate the iterator
IterInitWithValueFn
Create a new iterator that iterates over the provided value
IterNextBackFn
Advance the iterator in reverse, returning the next value from the end of the iterator.
IterNextFn
Advance the iterator, returning the next value from the iterator
IterSizeHintFn
Return the lower and upper bounds of the iterator, if known.
KeyPathreflect
A path of serialized key names for probing. Unlike FieldPath which tracks the internal type structure (including variant selections), KeyPath only tracks the keys as they appear in the serialized format.
ListAsMutPtrFn
Get mutable pointer to the data buffer of the list.
ListAsMutPtrTypedFn
Get raw mutable pointer to the data buffer as *mut u8.
ListAsPtrFn
Get pointer to the data buffer of the list.
ListCapacityFn
Get the current capacity of the list.
ListGetFn
Get pointer to the element at index in the list, or None if the index is out of bounds.
ListGetMutFn
Get mutable pointer to the element at index in the list, or None if the index is out of bounds.
ListInitInPlaceWithCapacityFn
Initialize a list in place with a given capacity
ListLenFn
Get the number of items in the list
ListPushFn
Push an item to the list
ListReserveFn
Reserve capacity for at least additional more elements.
ListSetLenFn
Set the length of a list (for direct-fill operations).
LockFn
Acquires a lock on a mutex-like pointer
MapContainsKeyFn
Check if the map contains a key
MapFromPairSliceFn
Build a map from a contiguous slice of (K, V) pairs.
MapGetValuePtrFn
Get pointer to a value for a given key, returns None if not found
MapInitInPlaceWithCapacityFn
Initialize a map in place with a given capacity
MapInsertFn
Insert a key-value pair into the map
MapLenFn
Get the number of entries in the map
NdArrayAsMutPtrFn
Get mutable pointer to the data buffer of the array.
NdArrayAsPtrFn
Get pointer to the data buffer of the array.
NdArrayByteStrideFn
Get the i-th stride in the array in bytes, or None if the dimension index is out of bounds.
NdArrayCountFn
Get the total count of elements in the array.
NdArrayDimFn
Get the i-th dimension in the array, or None if the dimension index is out of bounds.
NdArrayGetFn
Get pointer to the element at index in the array, or None if the index is out of bounds.
NdArrayGetMutFn
Get mutable pointer to the element at index in the array, or None if the index is out of bounds.
NdArrayNDimFn
Get the number of dimensions in the array.
NewIntoFn
Creates a new pointer wrapping the given value.
OptionGetValueFn
Get the value contained in an option, if present
OptionInitNoneFn
Initialize an option with None
OptionInitSomeFn
Initialize an option with Some(value)
OptionIsSomeFn
Check if an option contains a value
OptionReplaceWithFn
Replace an existing option with a new value
ProxyConvertInFnalloc
Function type for proxy deserialization: converts FROM proxy type INTO target type.
ProxyConvertOutFnalloc
Function type for proxy serialization: converts FROM target type INTO proxy type.
ReadFn
Acquires a read lock on a reader-writer lock-like pointer
ResultGetErrFn
Get the Err value contained in a result, if present
ResultGetOkFn
Get the Ok value contained in a result, if present
ResultInitErrFn
Initialize a result with Err(value)
ResultInitOkFn
Initialize a result with Ok(value)
ResultIsOkFn
Check if a result is Ok
SetContainsFn
Check if the set contains a value
SetInitInPlaceWithCapacityFn
Initialize a set in place with a given capacity
SetInsertFn
Insert a value in the set if not already contained, returning true if the value wasn’t present before
SetLenFn
Get the number of values in the set
ShapeAttribute
An attribute that can be applied to a shape. This is now just an alias for ExtensionAttr - all attributes use the same representation.
SkipSerializingIfFn
A function that, if present, determines whether field should be included in the serialization step. Takes a type-erased pointer and returns true if the field should be skipped.
SliceAsMutPtrFn
Get mutable pointer to the data buffer of the slice
SliceAsPtrFn
Get pointer to the data buffer of the slice
SliceBuilderConvertFn
Converts a slice builder into a pointer. This takes ownership of the builder and frees the backing storage.
SliceBuilderFreeFn
Frees a slice builder without converting it into a pointer
SliceBuilderNewFn
Creates a new slice builder for a pointer: ie. for Arc<[u8]>, it builds a Vec<u8> internally, to which you can push, and then turn into an Arc<[u8]> at the last stage.
SliceBuilderPushFn
Pushes a value into a slice builder.
SliceLenFn
Get the number of items in the slice
TruthyFn
Function type for truthiness checks used by skip_unless_truthy-style helpers.
TupleFieldreflect
Field index and associated peek value
TypeNameFn
Function pointer type for formatting type names.
UpgradeIntoFn
Tries to upgrade the weak pointer to a strong one.
VariantAttribute
An attribute that can be set on an enum variant. This is now just an alias for ExtensionAttr - all attributes use the same representation.
WriteFn
Acquires a write lock on a reader-writer lock-like pointer

Attribute Macros§

on_error
Attribute macro that runs cleanup code when a method returns an error.

Derive Macros§

Facet