Crate facet

Source
Expand description

Facet logo - a reflection library for Rust

Coverage Status free of syn crates.io documentation MIT/Apache-2.0 licensed

Logo by Misiasart

Thanks to all individual and corporate sponsors, without whom this work could not exist:

Ko-fi GitHub Sponsors Patreon Zed Depot

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.

§Known issues and limitations

We have the occasional soundness issue, see the soundness tag. Those are prioritized and fixed as soon as possible.

Format crates like facet-json are still very much incomplete, and will probably always be slower than the serde-* equivalent. Reflection has advantages in terms of flexibility, ergonomics and compile time but has a runtime cost compared to “monomorphize all the things”.

(Note: with codegen, one could get the best of both worlds. To be researched more)

Some format crates (like facet-toml) first deserialize to a DOM, and then to partial structs — this is not as efficient as it could be, but it’s a good first step.

Rust 1.86.0 has a compile error if you just import Facet but don’t use it, see https://github.com/facet-rs/facet/issues/75. This is fixed in nightly and will no longer be a problem with the next major Rust version.

type_eq is not const, thus preventing many useful things in const fn, see https://github.com/facet-rs/facet/issues/98. Language changes are needed to address that.

The design of arbitrary attributes is still in flux, see:

There isn’t a comparison between facet-reflect and bevy-reflect available right now— this is by design. We’re letting facet develop on its own for a while; we’ll make a detailed comparison once things have settled.

There are more issues and limitations of course, but this should get you started.

§Ecosystem

The core crates, facet-trait, facet-types etc. are no_std-friendly.

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-derive
  • facet-derive, which implements the Facet derive attribute as a fast/light proc macro powered by unsynn

For struct manipulation and reflection, the following is available:

  • facet-reflect, allows building values of arbitrary shapes in safe code, respecting invariants. It also allows peeking at existing values.
  • facet-pretty is able to pretty-print Facet types.

facet supports deserialization from multiple data formats through dedicated crates:

Internal crates include:

  • facet-codegen is internal and generates some of the code of facet-core
  • facet-testhelpers a simpler log logger and color-backtrace configured with the lightweight btparse backend

§License

Licensed under either of:

at your option.

Re-exports§

pub use static_assertions;

Modules§

hacking
Hacking Guide to Facet
sample_generated_code
This defines a few types showcasing various features of the Facet derive macro.
spez
Auto-deref specialization helpers for the Facet reflection system

Macros§

debug
Forwards to log::debug when the log feature is enabled
trace
Forwards to log::trace when the log feature is enabled
value_vtable
Creates a ValueVTable for a given type.

Structs§

ArrayDef
Fields for array types
ArrayDefBuilder
Builder for ArrayDef
ArrayVTable
Virtual table for a list-like type (like Vec<T>, but also HashSet<T>, etc.)
ArrayVTableBuilder
Builds a ArrayVTable
BoolAffinity
Definition for boolean scalar affinities
BoolAffinityBuilder
Builder for BoolAffinity
CharAffinity
Definition for character scalar affinities
CharAffinityBuilder
Builder for CharAffinity
ComplexNumberAffinity
Definition for string-like scalar affinities
ComplexNumberAffinityBuilder
Builder for ComplexNumberAffinity
ConstTypeId
TypeId equivalent usable in const contexts.
EmptyAffinity
Definition for empty scalar affinities
EmptyAffinityBuilder
Builder for EmptyAffinity
EnumDef
Fields for enum types
EnumDefBuilder
Builder for EnumDef
Field
Describes a field in a struct or tuple
FieldBuilder
Builder for Field
FieldFlags
Flags that can be applied to fields to modify their behavior
FieldVTable
Vtable for field-specific operations
FieldVTableBuilder
Builder for FieldVTable
Frame
Represents a frame in the initialization stack
FrameFlags
Flags that can be applied to frames
FunctionPointerDef
Common fields for function pointer types
FunctionPointerDefBuilder
Builder for FunctionPointerDef
Guard
A guard structure to manage memory allocation and deallocation.
HasherProxy
Provides an implementation of core::hash::Hasher for a given hasher pointer and write function
HeapValue
A type-erased value stored on the heap
ISet
Keeps track of which fields were initialized, up to 64 fields
IpAddrAffinity
Definition for IP address scalar affinities
IpAddrAffinityBuilder
Builder for IpAddrAffinity
ListDef
Fields for list types
ListDefBuilder
Builder for ListDef
ListVTable
Virtual table for a list-like type (like Vec<T>, but also HashSet<T>, etc.)
ListVTableBuilder
Builds a ListVTable
LockGuardVTable
Functions for manipulating a guard
LockResult
Type-erased result of locking a mutex-like smart pointer
MapDef
Fields for map types
MapDefBuilder
Builder for MapDef
MapIterVTable
VTable for an iterator over a map
MapIterVTableBuilder
Builds a MapIterVTable
MapVTable
Virtual table for a Map<K, V>
MapVTableBuilder
Builds a MapVTable
MarkerTraits
Bitflags for common marker traits that a type may implement
NumberAffinity
Definition for number-like scalar affinities
NumberAffinityBuilder
Builder for NumberAffinity
Opaque
Helper type for opaque members
OpaqueAffinity
Definition for opaque scalar affinities
OpaqueAffinityBuilder
Builder for OpaqueAffinity
OptionDef
Describes an Option — including a vtable to query and alter its state, and the inner shape (the T in Option<T>).
OptionDefBuilder
Builder for OptionDef
OptionVTable
Virtual table for Option<T>
OptionVTableBuilder
Builds an OptionVTable
OtherAffinity
Definition for other scalar affinities
OtherAffinityBuilder
Builder for OtherAffinity
PathAffinity
Definition for path scalar affinities
PathAffinityBuilder
Builder for PathAffinity
Peek
Lets you read from a value (implements read-only ValueVTable proxies)
PeekEnum
Lets you read from an enum (implements read-only enum operations)
PeekList
Lets you read from a list (implements read-only facet_core::ListVTable proxies)
PeekListIter
Iterator over a PeekList
PeekMap
Lets you read from a map (implements read-only facet_core::MapVTable proxies)
PeekMapIter
Iterator over key-value pairs in a PeekMap
PeekOption
Lets you read from an option (implements read-only option operations)
PeekSmartPointer
Represents a smart pointer that can be peeked at during memory inspection.
PeekStruct
Lets you read from a struct (implements read-only struct operations)
PtrConst
A type-erased read-only pointer to an initialized value.
PtrMut
A type-erased pointer to an initialized value
PtrUninit
A type-erased pointer to an uninitialized value
ScalarDef
Definition for scalar types
ScalarDefBuilder
Builder for ScalarDef
Shape
Schema for reflection of a type
ShapeBuilder
Builder for Shape
SliceDef
Fields for slice types
SliceDefBuilder
Builder for SliceDef
SliceVTable
Virtual table for a slice-like type (like Vec<T>, but also HashSet<T>, etc.)
SliceVTableBuilder
Builds a SliceVTable
SmartPointerDef
Describes a smart pointer — including a vtable to query and alter its state, and the inner shape (the pointee type in the smart pointer).
SmartPointerDefBuilder
Builder for creating a SmartPointerDef.
SmartPointerFlags
Flags to represent various characteristics of smart pointers
SmartPointerVTable
Functions for interacting with a smart pointer
SmartPointerVTableBuilder
Builder for creating a SmartPointerVTable.
SocketAddrAffinity
Definition for socket address scalar affinities
SocketAddrAffinityBuilder
Builder for SocketAddrAffinity
StringAffinity
Definition for string-like scalar affinities
StringAffinityBuilder
Builder for StringAffinity
StructBuilder
Builder for StructDef
StructDef
Common fields for struct-like types
TimeAffinity
Definition for Datetime/Timestamp scalar affinities
TimeAffinityBuilder
Builder for UuidAffinity
TypeNameOpts
Options for formatting the name of a type
TypeParam
Represents a lifetime parameter, e.g., 'a or 'a: 'b + 'c.
TypedPtrUninit
A pointer to an uninitialized value with a lifetime.
UlidAffinity
Definition for ULID and ULID-like scalar affinities
UlidAffinityBuilder
Builder for UlidAffinity
UnsizedError
Tried to get the Layout of an unsized type
UuidAffinity
Definition for UUID and UUID-like scalar affinities
UuidAffinityBuilder
Builder for UuidAffinity
VTableView
A typed view of a ValueVTable.
ValueId
A unique identifier for a peek value
ValueVTable
VTable for common operations that can be performed on any shape
ValueVTableBuilder
Builds a ValueVTable
Variant
Describes a variant of an enum
VariantBuilder
Builder for Variant
Wip
A work-in-progress heap-allocated value

Enums§

Characteristic
A characteristic a shape can have
Def
The definition of a shape: is it more like a struct, a map, a list?
EnumRepr
All possible representations for Rust enums — ie. the type/size of the discriminant
FieldAttribute
An attribute that can be set on a field
FieldError
Errors encountered when calling field_by_index or field_by_name
FrameMode
Represents the special mode a frame can be in
FunctionAbi
The calling ABI of a function pointer
KnownSmartPointer
Represents common standard library smart pointer kinds
NumberBits
Bit representation of numbers
ParseError
Error returned by ParseFn
ReflectError
Errors that can occur when reflecting on types.
ScalarAffinity
Scalar affinity: what a scalar spiritually is: a number, a string, a bool, something else entirely?
ScalarType
All scalar types supported out of the box by peek and poke.
ShapeAttribute
An attribute that can be applied to a shape
ShapeLayout
Layout of the shape
Signedness
Represents whether a numeric type is signed or unsigned
StructKind
Describes the kind of struct (useful for deserializing)
TryBorrowInnerError
Error type returned by TryBorrowInnerFn when attempting to borrow the inner value from a wrapper type.
TryFromError
Error type for TryFrom conversion failures
TryIntoInnerError
Error type returned by TryIntoInnerFn when attempting to extract the inner value from a wrapper type.
VariantAttribute
An attribute that can be set on an enum variant

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.
HasFields
Trait for types that have field methods

Functions§

of
Create a TypeId for a type.
peek_enum
Returns the enum definition if the shape represents an enum, None otherwise
peek_enum_repr
Returns the enum representation if the shape represents an enum, None otherwise
peek_enum_variants
Returns the enum variants if the shape represents an enum, None otherwise

Type Aliases§

ArrayGetItemPtrFn
Get pointer to the item at the given index. Panics if out of bounds.
BorrowFn
Tries to obtain a reference to the inner value of the smart pointer.
CloneIntoFn
Function to clone a value into another already-allocated value
CloneIntoFnTyped
Function to clone a value into another already-allocated value
CmpFn
Function to compare two values and return their ordering
CmpFnTyped
Function to compare two values and return their ordering
DebugFn
Function to format a value for debug. If this returns None, the shape did not implement Debug.
DebugFnTyped
Function to format a value for debug. If this returns None, the shape did not implement Debug.
DefaultInPlaceFn
Function to set a value to its default in-place
DefaultInPlaceFnTyped
Function to set a value to its default in-place
DisplayFn
Function to format a value for display
DisplayFnTyped
Function to format a value for display
DowngradeIntoFn
Downgrades a strong pointer to a weak one.
DropInPlaceFn
Function to drop a value
HashFn
Function to hash a value
HashFnTyped
Function to hash a value
HasherWriteFn
Function to write bytes to a hasher
HasherWriteFnTyped
Function to write bytes to a hasher
InvariantsFn
Function to validate the invariants of a value. If it returns false, the value is considered invalid.
InvariantsFnTyped
Function to validate the invariants of a value. If it returns false, the value is considered invalid.
ListGetItemPtrFn
Get pointer to the item at the given index. Panics if 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
LockFn
Acquires a lock on a mutex-like smart pointer
MapContainsKeyFn
Check if the map contains a key
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
MapIterDeallocFn
Deallocate the iterator
MapIterFn
Get an iterator over the map
MapIterNextFn
Get the next key-value pair from the iterator
MapLenFn
Get the number of entries in the map
NewIntoFn
Creates a new smart 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
ParseFn
Function to parse a value from a string.
ParseFnTyped
Function to parse a value from a string.
PartialEqFn
Function to check if two values are partially equal
PartialEqFnTyped
Function to check if two values are partially equal
PartialOrdFn
Function to compare two values and return their ordering if comparable
PartialOrdFnTyped
Function to compare two values and return their ordering if comparable
ReadFn
Acquires a read lock on a reader-writer lock-like smart pointer
SkipSerializingIfFn
A function that, if present, determines whether field should be included in the serialization step.
SliceGetItemPtrFn
Get pointer to the item at the given index. Panics if out of bounds.
SliceLenFn
Get the number of items in the slice
TryBorrowInnerFn
Function to borrow the inner value from a transparent/newtype wrapper without copying.
TryBorrowInnerFnTyped
Function to borrow the inner value from a transparent/newtype wrapper without copying.
TryFromFn
Function to try converting from another type
TryFromFnTyped
Function to try converting from another type
TryIntoInnerFn
Function to convert a transparent/newtype wrapper into its inner type.
TryIntoInnerFnTyped
Function to convert a transparent/newtype wrapper into its inner type.
TypeNameFn
A function that formats the name of a type.
UpgradeIntoFn
Tries to upgrade the weak pointer to a strong one.
WriteFn
Acquires a write lock on a reader-writer lock-like smart pointer

Derive Macros§

Facet
Derive the Facet trait for structs, tuple structs, and enums.