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 Discord

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.

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-macros
  • facet-macros, 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.
value_vtable_unsized
Similar to value_vtable! macro but for !Sized types.

Structs§

ArrayDef
Fields for array types
ArrayDefBuilder
Builder for ArrayDef
ArrayType
Describes a fixed-size array ([T; N])
ArrayVTable
Virtual table for an array
ArrayVTableBuilder
Builds a ArrayVTable
ConstTypeId
TypeId equivalent usable in const contexts.
EnumDefBuilder
Builder for EnumDef
EnumType
Fields for enum types
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
FieldIter
An iterator over all the fields of a struct or enum. See HasFields::fields
FieldVTable
Vtable for field-specific operations
FieldVTableBuilder
Builder for FieldVTable
FieldsForSerializeIter
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
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
IterVTable
VTable for an iterator
IterVTableBuilder
Builds an IterVTable
ListDef
Fields for list types
ListDefBuilder
Builder for ListDef
ListVTable
Virtual table for a list-like type (like Vec<T>)
ListVTableBuilder
Builds a ListVTable
LockGuardVTable
Functions for manipulating a guard
LockResult
Type-erased result of locking a mutex-like pointer
MapDef
Fields for map types
MapDefBuilder
Builder for MapDef
MapVTable
Virtual table for a Map<K, V>
MapVTableBuilder
Builds a MapVTable
MarkerTraits
Bitflags for common marker traits that a type may implement
Opaque
Helper type for opaque members
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
Partial
A work-in-progress heap-allocated value
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
PeekListLike
Lets you read from a list, array or slice
PeekListLikeIter
Iterator over a PeekListLike
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)
PeekPointer
Represents a pointer that can be peeked at during memory inspection.
PeekSet
Lets you read from a set
PeekSetIter
Iterator over values in a PeekSet
PeekStruct
Lets you read from a struct (implements read-only struct operations)
PeekTuple
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).
PointerDefBuilder
Builder for creating a PointerDef.
PointerFlags
Flags to represent various characteristics of pointers
PointerVTable
Functions for interacting with a pointer
PointerVTableBuilder
Builder for creating a PointerVTable.
PtrConst
A type-erased read-only pointer to an initialized value.
PtrConstWide
A type-erased, read-only wide pointer to an initialized value.
PtrMut
A type-erased pointer to an initialized value
PtrMutWide
A type-erased, mutable wide pointer to an initialized value.
PtrUninit
A type-erased pointer to an uninitialized value
PtrUninitWide
A type-erased, wide pointer to an uninitialized value.
Repr
Describes base representation of the type
SetDef
Fields for set types
SetDefBuilder
Builder for SetDef
SetVTable
Virtual table for a Set<T>
SetVTableBuilder
Builds a SetVTable
Shape
Schema for reflection of a type
ShapeBuilder
Builder for Shape
SliceBuilderVTable
Functions for creating and manipulating slice builders.
SliceBuilderVTableBuilder
Builder for creating a SliceBuilderVTable.
SliceDef
Fields for slice types
SliceDefBuilder
Builder for SliceDef
SliceType
Describes a slice ([T])
SliceVTable
Virtual table for a slice-like type (like Vec<T>, but also HashSet<T>, etc.)
SliceVTableBuilder
Builds a SliceVTable
StructBuilder
Builder for StructType
StructType
Common fields for struct-like types
TupleType
Local representation of a tuple type for peek operations
TypeNameOpts
Options for formatting the name of a type
TypeParam
Represents a lifetime parameter, e.g., 'a or 'a: 'b + 'c.
TypedPartial
A typed wrapper around Partial, for when you want to statically ensure that build gives you the proper type.
TypedPtrUninit
A pointer to an uninitialized value with a lifetime.
UnionType
Common fields for union types
UnsizedError
Tried to get the Layout of an unsized type
VTableView
A typed view of a ValueVTable.
ValueId
A unique identifier for a peek value
ValuePointerType
Describes the raw/reference pointer
ValueVTableBuilder
Builds a ValueVTable
ValueVTableBuilderUnsized
Builds a ValueVTable for a !Sized type
ValueVTableSized
VTable for common operations that can be performed on any Sized shape
ValueVTableUnsized
VTable for common operations that can be performed on any !Sized shape
Variant
Describes a variant of an enum
VariantBuilder
Builder for Variant

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?
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
FunctionAbi
The calling ABI of a function pointer
GenericPtr
A generic wrapper for either a thin or wide constant pointer. This enables working with both sized and unsized types using a single enum.
KnownPointer
Represents common standard library pointer kinds
ListLikeDef
Fields for types which act like lists
NumericType
Describes numeric types (integer/float)
ParseError
Error returned by ParseFn
PointerType
Describes all pointer types
PrimitiveType
Describes built-in primitives (u32, bool, str, etc.)
ReflectError
Errors that can occur when reflecting on types.
ScalarType
All scalar types supported out of the box by peek and poke.
SequenceType
Describes built-in sequence type (array, slice)
ShapeAttribute
An attribute that can be applied to a shape
ShapeLayout
Layout of the shape
StructKind
Describes the kind of struct (useful for deserializing)
TextualType
Describes textual types (char/string)
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.
Type
The definition of a shape in accordance to rust reference:
UserType
User-defined types (structs, enums, unions)
ValueVTable
A vtable representing the operations that can be performed on a type, either for sized or unsized types.
VariantAttribute
An attribute that can be set on an enum variant
VariantError
Error that can occur when trying to determine variant information

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
IterItem
A kind of item that an IterVTable returns

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§

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.
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
CmpFnWide
Function to compare two values and return their ordering (wide pointer version)
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.
DebugFnWide
Function to format a value for debug (wide pointer version). If this returns None, the shape did not implement Debug (wide).
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
DisplayFnWide
Function to format a value for display (wide pointer version)
DowngradeIntoFn
Downgrades a strong pointer to a weak one.
DropInPlaceFn
Function to drop a value
DropInPlaceFnWide
Function to drop a value (wide pointer version)
HashFn
Function to hash a value
HashFnTyped
Function to hash a value
HashFnWide
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.
InvariantsFnWide
Function to validate the invariants of a value. If it returns false, the value is considered invalid (wide pointer version).
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.
ListAsMutPtrFn
Get mutable pointer to the data buffer of the list.
ListAsPtrFn
Get pointer to the data buffer 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
LockFn
Acquires a lock on a mutex-like 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
MapLenFn
Get the number of entries in the map
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
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
PartialEqFnWide
Function to check if two values are partially equal (wide pointer version)
PartialOrdFn
Function to compare two values and return their ordering if comparable
PartialOrdFnTyped
Function to compare two values and return their ordering if comparable
PartialOrdFnWide
Function to compare two values and return their ordering if comparable (wide pointer version)
ReadFn
Acquires a read lock on a reader-writer lock-like pointer
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
SkipSerializingIfFn
A function that, if present, determines whether field should be included in the serialization step.
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
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.
TryBorrowInnerFnWide
Function to borrow the inner value from a transparent/newtype wrapper without copying (wide pointer version).
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.
TupleField
Field index and associated peek value
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 pointer

Derive Macros§

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