Expand description
§facet
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:
- facet-macros, which implements the
Facetderive 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:
- facet-json: JSON format support
- facet-toml: TOML format support
- facet-yaml: YAML format support
- facet-msgpack: MessagePack deserialization
- facet-asn1: ASN.1 format support
- facet-xdr: XDR format support
- facet-csv: CSV format support
Still adjacent to serialization/deserialization, we have:
- facet-urlencoded: URL-encoded form data deserialization
- facet-args: CLI arguments (a-la clap)
As far as utilities go:
- facet-value: Memory-efficient dynamic value type, supporting JSON-like data plus bytes
- facet-pretty: Pretty-print Facet types
- facet-diff: Diffing capabilities for Facet types
- facet-assert: Pretty assertions for Facet types (no PartialEq required)
- facet-serialize: Generic iterative serialization facilities
- facet-deserialize: Generic iterative deserialization facilities
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
MultiArrayListtype
§Sponsors
Thanks to all individual sponsors:
…along with corporate sponsors:
…without whom this work could not exist.
§Special thanks
The facet logo was drawn by Misiasart.
§License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
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.
- debug
reflectand non-tracing - Forwards to tracing::debug when the tracing feature is enabled
- define_
attr_ grammar - Define an attribute grammar with type-safe parsing.
- trace
reflectand non-tracing - Forwards to tracing::trace when the tracing 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§
- Array
Def - Fields for array types
- Array
Type - Describes a fixed-size array (
[T; N]) - ArrayV
Table - Virtual table for an array
- ArrayV
Table Builder - Builder for the vtable
- Attr
- An attribute attaches metadata to a container or a field
- Const
Type Id - TypeId equivalent usable in const contexts.
- Covariant
Peek reflect - A covariant wrapper around
Peekfor types that can safely shrink lifetimes. - DeclId
- Identifies a type declaration, independent of type parameters.
- DefArray
Builder - Builder that produces
Def::Array(...). - DefList
Builder - Builder that produces
Def::List(...). - DefMap
Builder - Builder that produces
Def::Map(...). - DefOption
Builder - Builder that produces
Def::Option(...). - DefResult
Builder - Builder that produces
Def::Result(...). - DefSet
Builder - Builder that produces
Def::Set(...). - Duplicate
Field Error reflect - Error when building a resolution.
- Dynamic
Value Def - Definition for dynamic value types.
- Dynamic
ValueV Table - Virtual table for dynamic value types.
- Enum
Type - Fields for enum types
- Enum
Type Builder - Builder for constructing
EnumTypeinstances in const contexts. - Field
- Describes a field in a struct or tuple
- Field
Builder - Builder for constructing
Fieldinstances in const contexts. - Field
Flags - Bit flags for common field attributes.
- Field
Info reflect - Information about a single field in a resolution.
- Field
Item reflect - A field item with runtime state for serialization.
- Field
Iter reflect - An iterator over all the fields of a struct or enum. See
HasFields::fields - Field
Path reflect - A path through the type tree to a field.
- Fields
ForSerialize Iter reflect - An iterator over the fields of a struct or enum that should be serialized. See
HasFields::fields_for_serialize - Format
Proxy alloc - A format-specific proxy definition.
- Function
Pointer Def - Common fields for function pointer types
- Guard
reflect - A guard structure to manage memory allocation and deallocation.
- Hash
Proxy - A proxy type that wraps
&mut dyn Hasherand implementsHasher. - Heap
Value reflect - A type-erased value stored on the heap
- IterV
Table - VTable for an iterator
- ListDef
- Fields for list types
- List
Type Ops - Per-type list operations that must be monomorphized.
- List
Type OpsBuilder - Builder for
ListTypeOps. - ListV
Table - Virtual table for shareable list operations.
- ListV
Table Builder - Builder for the vtable
- Lock
GuardV Table - Functions for manipulating a guard
- Lock
Result - Type-erased result of locking a mutex-like or reader-writer lock pointer.
- MapDef
- Fields for map types
- MapV
Table - Virtual table for a Map<K, V>
- MapV
Table Builder - Builder for the vtable
- Marker
Traits - Bitflags tracking implementation of Rust’s marker/auto traits.
- Native
Wide Ptr - A wide pointer in native platform layout.
- NdArray
Def - Fields for n-dimensional array types
- NdArrayV
Table - 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.
- Option
Def - Describes an Option — including a vtable to query and alter its state,
and the inner shape (the
TinOption<T>). - OptionV
Table - Virtual table for
Option<T> - OptionV
Table Builder - Builder for the vtable
- Owned
Peek reflect - An Owned version of a Peek used for custom serialization
- OxMut
- Safe mutable reference with shape.
- OxPtr
Const - Read-only shaped pointer for vtable use.
- OxPtr
Mut - Mutable shaped pointer for vtable use.
- OxPtr
Uninit - Uninitialized shaped pointer for vtable use.
- OxRef
- Safe read-only reference with shape.
- Partial
reflect - A type-erased, heap-allocated, partially-initialized value.
- Peek
reflect - A read-only view into a value with runtime type information.
- Peek
Dynamic Value reflect - Lets you read from a dynamic value (implements read-only operations for DynamicValue types)
- Peek
Dynamic Value Array Iter reflect - Iterator over array elements in a dynamic value
- Peek
Dynamic Value Object Iter reflect - Iterator over object entries in a dynamic value
- Peek
Enum reflect - Lets you read from an enum (implements read-only enum operations)
- Peek
List reflect - Lets you read from a list (implements read-only
facet_core::ListVTableproxies) - Peek
List Iter reflect - Iterator over a
PeekList - Peek
List Like reflect - Lets you read from a list, array or slice
- Peek
List Like Iter reflect - Iterator over a
PeekListLike - PeekMap
reflect - Lets you read from a map (implements read-only
facet_core::MapVTableproxies) - Peek
MapIter reflect - Iterator over key-value pairs in a
PeekMap - Peek
NdArray reflect - Lets you read from an n-dimensional array (implements read-only
facet_core::NdArrayVTableproxies) - Peek
Option reflect - Lets you read from an option (implements read-only option operations)
- Peek
Pointer reflect - Represents a pointer that can be peeked at during memory inspection.
- Peek
Result reflect - Lets you read from a result (implements read-only result operations)
- PeekSet
reflect - Lets you read from a set
- Peek
SetIter reflect - Iterator over values in a
PeekSet - Peek
Struct reflect - Lets you read from a struct (implements read-only struct operations)
- Peek
Tuple reflect - Lets you read from a tuple
- Pointer
Def - Describes a pointer — including a vtable to query and alter its state, and the inner shape (the pointee type in the pointer).
- Pointer
Flags - Flags to represent various characteristics of pointers
- PointerV
Table - Functions for interacting with a pointer
- Poke
reflect - A mutable view into a value with runtime type information.
- Poke
Enum reflect - Lets you mutate an enum’s fields.
- Poke
List reflect - Lets you mutate a list (implements mutable
facet_core::ListVTableproxies) - Poke
List Iter reflect - Iterator over a
PokeList - Poke
Struct reflect - Lets you mutate a struct’s fields.
- Proxy
Def alloc - 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
- Resolution
reflect - One possible “shape” the flattened type could take.
- Result
Def - Describes a Result — including a vtable to query and alter its state,
and the inner shapes (the
TandEinResult<T, E>). - ResultV
Table - Virtual table for
Result<T, E> - ResultV
Table Builder - Builder for the vtable
- SetDef
- Fields for set types
- SetV
Table - Virtual table for a
Set<T> - SetV
Table Builder - 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.
- Shape
Builder - Builder for creating
Shapeinstances. - Shape
Flags - Bit flags for common shape-level attributes.
- Shape
Ref - A lazy reference to a
Shapevia a function pointer. - Slice
BuilderV Table - Functions for creating and manipulating slice builders.
- Slice
Def - Fields for slice types
- Slice
Type - Describes a slice (
[T]) - SliceV
Table - Virtual table for a slice-like type (like
Vec<T>, but alsoHashSet<T>, etc.) - Span
reflect - Source span with offset and length.
- Spanned
reflect - A value with source span information.
- Struct
Type - Common fields for struct-like types
- Struct
Type Builder - Builder for
StructTypeto enable shorter derive macro output - Tagged
Ptr - A pointer that uses the high bit (bit 63) as a tag to indicate wide vs thin.
- Tuple
Type reflect - Local representation of a tuple type for peek operations
- Type
Enum Builder - Builder that produces
Type::User(UserType::Enum(...)). - Type
Name Display - A wrapper around
&'static Shapethat implementsDisplayusing the full type name (including generic parameters). - Type
Name Opts - Options for formatting the name of a type.
- Type
OpsDirect - Type-specific operations for concrete types (uses thin pointers).
- Type
OpsIndirect - Type-specific operations for generic containers (uses wide pointers with shape).
- Type
Param - Represents a lifetime parameter, e.g.,
'aor'a: 'b + 'c. - Type
Struct Builder - Builder that produces
Type::User(UserType::Struct(...)). - Type
Union Builder - Builder that produces
Type::User(UserType::Union(...)). - TypedV
Table Direct Builder - Type-safe builder for VTableDirect.
- Union
Type - Common fields for union types
- Union
Type Builder - Builder for constructing
UnionTypeinstances in const contexts. - Unsized
Error - Tried to get the
Layoutof an unsized type - VTable
Direct - VTable for concrete types with compile-time known traits.
- VTable
Indirect - VTable for generic containers with runtime trait resolution.
- ValueId
reflect - A unique identifier for a peek value
- Value
Pointer Type - Describes the raw/reference pointer
- Variance
Dep - A dependency for variance computation.
- Variance
Desc - Declarative description of a type’s variance.
- Variant
- Describes a variant of an enum
- Variant
Builder - Builder for constructing
Variantinstances in const contexts. - Variant
Selection reflect - Records that a specific enum field has a specific variant selected.
Enums§
- Base
Repr - 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?
- Default
Source - Source of a field’s default value.
- DynDate
Time Kind - The kind of datetime value (for dynamic value datetime support).
- DynValue
Kind - The kind of value stored in a dynamic value.
- Enum
Repr - All possible representations for Rust enums — ie. the type/size of the discriminant
- Field
Category reflect - Category of a field for format-aware field lookup.
- Field
Error - Errors encountered when calling
field_by_indexorfield_by_name - Field
Key reflect - A key for field lookup in schemas and solvers.
- Function
Abi - The calling ABI of a function pointer
- Known
Pointer - Represents common standard library pointer kinds
- List
Like Def reflect - Fields for types which act like lists
- Match
Result reflect - Result of matching input fields against a resolution.
- Numeric
Type - Describes numeric types (integer/float)
- Ox
- Type-erased value with ownership tracking — like
Cowbut for any shape. - Parse
Error - Error returned by parse operations.
- Path
Segment reflect - A segment in a field path.
- Pointer
Type - Describes all pointer types
- Primitive
Type - Describes built-in primitives (u32, bool, str, etc.)
- PtrKind
- The kind of a pointer based on its size.
- Reflect
Error reflect - Errors that can occur when reflecting on types.
- Scalar
Type - All scalar types supported out of the box by facet.
- Sequence
Type - Describes built-in sequence type (array, slice)
- Shape
Layout - Layout of the shape
- Stride
Error reflect - Error that can occur when trying to access an n-dimensional array as strided
- Struct
Kind - Describes the kind of struct (useful for deserializing)
- Textual
Type - Describes textual types (char/string)
- Tracker
Kind reflect - A kind-only version of Tracker
- TryBorrow
Inner Error - Error returned when
try_borrow_innerfails. - TryFrom
Error - Error returned when
try_fromfails to convert a value. - TryFrom
Outcome - Outcome of a
try_fromvtable operation. - TryInto
Inner Error - Error returned when
try_into_innerfails. - Type
- The definition of a shape in accordance to rust reference:
- TypeOps
- Type-erased TypeOps that can hold either Direct or Indirect style.
- User
Type - User-defined types (structs, enums, unions)
- VTable
Erased - Type-erased VTable that can hold either Direct or Indirect style.
- Variance
- Variance of a type with respect to its type/lifetime parameters.
- Variance
Position - Position of a type dependency in variance computation.
- Variant
Error reflect - 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
Shapeof a type, which in turn lets us inspect any fields, build a value of this type progressively, etc. - HasFields
reflect - Trait for types that have field methods
- Iter
Item - A kind of item that an
IterVTablereturns - Write
- A
no_stdcompatible write trait used by facet serializers.
Functions§
- decl_
id_ hash - Computes a
DeclIdhash from a string at compile time. - decl_
id_ hash_ extern - Computes a
DeclIdhash from module path, kind, and type identifier. - find_
span_ metadata_ field reflect - Find the span metadata field in a struct shape.
- get_
spanned_ inner_ shape reflect - Extract the inner value shape from a Spanned-like struct.
- is_
spanned_ shape reflect - Check if a shape represents a type with span metadata (like
Spanned<T>). - of
- Create a
TypeIdfor a type. - peek_
enum reflect - Returns the enum definition if the shape represents an enum, None otherwise
- peek_
enum_ repr reflect - Returns the enum representation if the shape represents an enum, None otherwise
- peek_
enum_ variants reflect - 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§
- Array
AsMut PtrFn - Get mutable pointer to the data buffer of the array.
- Array
AsPtr Fn - Get pointer to the data buffer of the array.
- Borrow
Fn - Tries to obtain a reference to the inner value of the pointer.
- Default
InPlace Fn - Function type for default initialization in-place.
Used by the
#[facet(default)]attribute. - DomKey
Path reflect - A path of serialized keys for probing (DOM-aware). Each key includes the category (attribute vs element) for DOM formats.
- Downgrade
Into Fn - Downgrades a strong pointer to a weak one.
- DynArray
GetFn - Get an element from an array by index. Returns None if not an array or index out of bounds.
- DynArray
LenFn - Get the length of an array. Returns None if not an array.
- DynBegin
Array Fn - Initialize the value as an empty array.
- DynBegin
Object Fn - Initialize the value as an empty object.
- DynEnd
Array Fn - Finalize the array (optional, for shrinking capacity etc.).
- DynEnd
Object Fn - Finalize the object (optional, for shrinking capacity etc.).
- DynGet
Bool Fn - Get a boolean value. Returns None if not a bool.
- DynGet
Bytes Fn - Get a bytes reference. Returns None if not bytes.
- DynGet
Date Time Fn - Get datetime components from a datetime value.
- DynGet
F64Fn - Get a 64-bit float value. Returns None if not a number.
- DynGet
I64Fn - Get a signed 64-bit integer value. Returns None if not representable as i64.
- DynGet
Kind Fn - Get the kind of value stored.
- DynGet
StrFn - Get a string reference. Returns None if not a string.
- DynGet
U64Fn - Get an unsigned 64-bit integer value. Returns None if not representable as u64.
- DynInsert
Object Entry Fn - Insert a key-value pair into the object.
- DynObject
GetEntry Fn - Get a key-value pair from an object by index. Returns None if not an object or index out of bounds.
- DynObject
GetFn - Get a value from an object by key. Returns None if not an object or key not found.
- DynObject
GetMut Fn - Get a mutable reference to a value from an object by key. Returns None if not an object or key not found.
- DynObject
LenFn - Get the length of an object. Returns None if not an object.
- DynPush
Array Element Fn - Push an element to the array.
- DynSet
Bool Fn - Set the value to a boolean.
- DynSet
Bytes Fn - Set the value to bytes.
- DynSet
Date Time Fn - Set the value to a datetime.
- DynSet
F64Fn - Set the value to a 64-bit float.
- DynSet
I64Fn - Set the value to a signed 64-bit integer.
- DynSet
Null Fn - Set the value to null.
- DynSet
StrFn - Set the value to a string.
- DynSet
U64Fn - Set the value to an unsigned 64-bit integer.
- Field
Attribute - An attribute that can be set on a field.
This is now just an alias for
ExtensionAttr- all attributes use the same representation. - Invariants
Fn - Function type for type invariant validation.
Used by the
#[facet(invariants = fn)]attribute. - Iter
Dealloc Fn - Deallocate the iterator
- Iter
Init With Value Fn - Create a new iterator that iterates over the provided value
- Iter
Next Back Fn - Advance the iterator in reverse, returning the next value from the end of the iterator.
- Iter
Next Fn - Advance the iterator, returning the next value from the iterator
- Iter
Size Hint Fn - Return the lower and upper bounds of the iterator, if known.
- KeyPath
reflect - A path of serialized key names for probing (flat formats). Unlike FieldPath which tracks the internal type structure (including variant selections), KeyPath only tracks the keys as they appear in the serialized format.
- List
AsMut PtrFn - Get mutable pointer to the data buffer of the list.
- List
AsMut PtrTyped Fn - Get raw mutable pointer to the data buffer as
*mut u8. - List
AsPtr Fn - Get pointer to the data buffer of the list.
- List
Capacity Fn - Get the current capacity of the list.
- List
GetFn - Get pointer to the element at
indexin the list, orNoneif the index is out of bounds. - List
GetMut Fn - Get mutable pointer to the element at
indexin the list, orNoneif the index is out of bounds. - List
Init InPlace With Capacity Fn - Initialize a list in place with a given capacity
- List
LenFn - Get the number of items in the list
- List
Push Fn - Push an item to the list
- List
Reserve Fn - Reserve capacity for at least
additionalmore elements. - List
SetLen Fn - Set the length of a list (for direct-fill operations).
- LockFn
- Acquires a lock on a mutex-like pointer (exclusive access)
- MapContains
KeyFn - Check if the map contains a key
- MapFrom
Pair Slice Fn - Build a map from a contiguous slice of (K, V) pairs.
- MapGet
Value PtrFn - Get pointer to a value for a given key, returns None if not found
- MapInit
InPlace With Capacity Fn - Initialize a map in place with a given capacity
- MapInsert
Fn - Insert a key-value pair into the map
- MapLen
Fn - Get the number of entries in the map
- NdArray
AsMut PtrFn - Get mutable pointer to the data buffer of the array.
- NdArray
AsPtr Fn - Get pointer to the data buffer of the array.
- NdArray
Byte Stride Fn - Get the i-th stride in the array in bytes, or
Noneif the dimension index is out of bounds. - NdArray
Count Fn - Get the total count of elements in the array.
- NdArray
DimFn - Get the i-th dimension in the array, or
Noneif the dimension index is out of bounds. - NdArray
GetFn - Get pointer to the element at
indexin the array, orNoneif the index is out of bounds. - NdArray
GetMut Fn - Get mutable pointer to the element at
indexin the array, orNoneif the index is out of bounds. - NdArrayN
DimFn - Get the number of dimensions in the array.
- NewInto
Fn - Creates a new pointer wrapping the given value.
- Option
GetValue Fn - Get the value contained in an option, if present
- Option
Init None Fn - Initialize an option with None
- Option
Init Some Fn - Initialize an option with Some(value)
- Option
IsSome Fn - Check if an option contains a value
- Option
Replace With Fn - Replace an existing option with a new value
- Proxy
Convert InFn alloc - Function type for proxy deserialization: converts FROM proxy type INTO target type.
- Proxy
Convert OutFn alloc - Function type for proxy serialization: converts FROM target type INTO proxy type.
- ReadFn
- Acquires a read lock on a reader-writer lock-like pointer (shared access)
- Read
Lock Result - Result of acquiring a read lock (shared access) - data is immutable
- Result
GetErr Fn - Get the Err value contained in a result, if present
- Result
GetOk Fn - Get the Ok value contained in a result, if present
- Result
Init ErrFn - Initialize a result with Err(value)
- Result
Init OkFn - Initialize a result with Ok(value)
- Result
IsOk Fn - Check if a result is Ok
- SetContains
Fn - Check if the set contains a value
- SetInit
InPlace With Capacity Fn - Initialize a set in place with a given capacity
- SetInsert
Fn - Insert a value in the set if not already contained, returning true if the value wasn’t present before
- SetLen
Fn - Get the number of values in the set
- Shape
Attribute - An attribute that can be applied to a shape.
This is now just an alias for
ExtensionAttr- all attributes use the same representation. - Skip
Serializing IfFn - 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.
- Slice
AsMut PtrFn - Get mutable pointer to the data buffer of the slice
- Slice
AsPtr Fn - Get pointer to the data buffer of the slice
- Slice
Builder Convert Fn - Converts a slice builder into a pointer. This takes ownership of the builder and frees the backing storage.
- Slice
Builder Free Fn - Frees a slice builder without converting it into a pointer
- Slice
Builder NewFn - Creates a new slice builder for a pointer: ie. for
Arc<[u8]>, it builds aVec<u8>internally, to which you can push, and then turn into anArc<[u8]>at the last stage. - Slice
Builder Push Fn - Pushes a value into a slice builder.
- Slice
LenFn - Get the number of items in the slice
- Truthy
Fn - Function type for truthiness checks used by skip_unless_truthy-style helpers.
- Tuple
Field reflect - Field index and associated peek value
- Type
Name Fn - Function pointer type for formatting type names.
- Upgrade
Into Fn - Tries to upgrade the weak pointer to a strong one.
- Validator
Fn - A function that validates a field value. Takes a type-erased pointer and returns
Ok(())if valid, orErr(message)with a description of the validation failure. - Variant
Attribute - 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 (exclusive access)
- Write
Lock Result - Result of acquiring a write/mutex lock (exclusive access) - data is mutable
Attribute Macros§
- on_
error - Attribute macro that runs cleanup code when a method returns an error.