#[repr(C)]pub struct Shape {Show 27 fields
pub id: ConstTypeId,
pub decl_id: DeclId,
pub layout: ShapeLayout,
pub vtable: VTableErased,
pub type_ops: Option<TypeOps>,
pub marker_traits: MarkerTraits,
pub ty: Type,
pub def: Def,
pub type_identifier: &'static str,
pub module_path: Option<&'static str>,
pub source_file: Option<&'static str>,
pub source_line: Option<u32>,
pub source_column: Option<u32>,
pub type_params: &'static [TypeParam],
pub doc: &'static [&'static str],
pub attributes: &'static [Attr],
pub type_tag: Option<&'static str>,
pub inner: Option<&'static Shape>,
pub builder_shape: Option<&'static Shape>,
pub type_name: Option<fn(&'static Shape, &mut Formatter<'_>, TypeNameOpts) -> Result<(), Error>>,
pub proxy: Option<&'static ProxyDef>,
pub format_proxies: &'static [FormatProxy],
pub variance: VarianceDesc,
pub flags: ShapeFlags,
pub tag: Option<&'static str>,
pub content: Option<&'static str>,
pub rename: Option<&'static str>,
}Expand description
Schema for reflection of a type — the core type in facet. Contains everything needed to inspect, allocate, and manipulate values at runtime.
Fields§
§id: ConstTypeIdUnique type identifier from the compiler. Use this for type equality checks and hash map keys.
decl_id: DeclIdDeclaration identifier — identifies the type declaration independent of type parameters.
Two shapes with the same decl_id come from the same source declaration
(the same generic type with potentially different type arguments).
For example, Vec<u32> and Vec<String> have different id values
(they are different types) but the same decl_id (they come from the
same Vec<T> declaration).
§Stability
DeclId is completely opaque and provides no stability guarantees.
It is NOT stable across compilations, refactors, or reformatting.
The only guarantee: within a single compilation, the same declaration
produces the same decl_id.
layout: ShapeLayoutSize and alignment — enough to allocate (but not initialize).
Check sized_layout() for sized types, or handle Unsized for slices/dyn.
vtable: VTableErasedErased vtable for display, debug, default, clone, hash, eq, ord, etc.
More specific vtables (e.g. for structs, enums) live in Def variants.
type_ops: Option<TypeOps>Per-type operations that must be monomorphized (drop, default, clone).
For generic containers like Vec<T>, the main vtable can be shared
across all instantiations (using type-erased operations), while type_ops
contains the operations that must be specialized per-T.
TypeOps::Directfor concrete types (uses thin pointers)TypeOps::Indirectfor generic containers (uses wide pointers with shape)
marker_traits: MarkerTraitsMarker traits like Copy, Send, Sync, etc.
ty: TypeUnderlying type category: primitive, array, slice, tuple, pointer, user-defined. Follows the Rust Reference.
def: DefType definition with variant-specific operations: scalar parsing, struct field access, enum variant iteration, map/list manipulation.
type_identifier: &'static strType name without generic parameters (e.g. Vec, not Vec<String>).
For the full name with generics, use vtable.type_name.
module_path: Option<&'static str>Module path where this type is defined (e.g. "std::collections").
Combined with type_identifier, this gives the fully qualified path
for code generation (e.g. std::collections::HashMap).
Nonefor primitives and foreign types (e.g. std library types)Some("crate_name")for types at the crate rootSome("crate_name::module::submodule")for nested types
source_file: Option<&'static str>Source file where this type is defined.
Populated when the doc feature is enabled in facet-macros.
None for primitives and foreign types (e.g. std library types).
source_line: Option<u32>Source line number where this type is defined (1-indexed).
Populated when the doc feature is enabled in facet-macros.
None for primitives and foreign types.
source_column: Option<u32>Source column number where this type is defined (1-indexed).
Populated when the doc feature is enabled in facet-macros.
None for primitives and foreign types.
type_params: &'static [TypeParam]Generic type parameters (e.g. T in Vec<T>).
Includes bounds and variance information.
doc: &'static [&'static str]Doc comments from the original type definition. Collected by facet-macros; lines usually start with a space.
attributes: &'static [Attr]Custom attributes applied to this type via #[facet(...)].
Use for validation, serialization hints, etc.
type_tag: Option<&'static str>Type tag for self-describing formats (e.g. JSON with type discriminators). Can be a qualified name, simple string, or integer depending on format.
inner: Option<&'static Shape>If set, this shape is a transparent wrapper around another shape.
Newtypes (NonZero), path wrappers (Utf8PathBuf), smart pointers (Arc<T>).
Serializes as the inner type: NonZero<u8> becomes 128, not {"value": 128}.
builder_shape: Option<&'static Shape>Optional builder type for immutable collections.
If set, deserializers should build this type first, then convert to the target type.
Examples: Bytes builds through BytesMut, Arc<[T]> builds through Vec<T>.
type_name: Option<fn(&'static Shape, &mut Formatter<'_>, TypeNameOpts) -> Result<(), Error>>Custom type name formatter for generic types.
If None, uses type_identifier. If Some, calls the function to format
the full type name including generic parameters (e.g., Vec<String>).
proxy: Option<&'static ProxyDef>alloc only.Container-level proxy for custom serialization/deserialization.
Set by #[facet(proxy = ProxyType)] on the container.
format_proxies: &'static [FormatProxy]alloc only.Format-specific container-level proxy definitions.
Set by #[facet(xml::proxy = ProxyType)], #[facet(json::proxy = ProxyType)], etc.
These take precedence over the format-agnostic proxy field when the format matches.
variance: VarianceDescDeclarative variance description for this type.
Describes how this type’s variance is computed from its dependencies.
The computed_variance method interprets this description, handling
cycle detection uniformly across all types.
See VarianceDesc for details on the structure.
flags: ShapeFlagsBit flags for common boolean attributes.
Provides O(1) access to frequently-checked attributes like untagged.
These are set by the derive macro based on #[facet(...)] attributes
with #[storage(flag)] in the grammar.
tag: Option<&'static str>Tag field name for internally/adjacently tagged enums.
Set by #[facet(tag = "...")].
content: Option<&'static str>Content field name for adjacently tagged enums.
Set by #[facet(content = "...")].
rename: Option<&'static str>Renamed type name for serialization/deserialization.
Set by #[facet(rename = "name")]. When present, serializers/deserializers
should use this name instead of the type’s actual name.
Implementations§
Source§impl Shape
impl Shape
Sourcepub const fn builder_for_sized<T>(type_identifier: &'static str) -> ShapeBuilder
pub const fn builder_for_sized<T>(type_identifier: &'static str) -> ShapeBuilder
Create a new builder for a sized type.
The id and layout are derived from the type parameter.
Sourcepub const fn builder_for_unsized<T>(
type_identifier: &'static str,
) -> ShapeBuilderwhere
T: ?Sized,
pub const fn builder_for_unsized<T>(
type_identifier: &'static str,
) -> ShapeBuilderwhere
T: ?Sized,
Create a new builder for an unsized type.
Source§impl Shape
impl Shape
Sourcepub const fn effective_name(&self) -> &'static str
pub const fn effective_name(&self) -> &'static str
Returns the effective name for serialization/deserialization.
Returns rename if set, otherwise returns the type’s identifier.
Sourcepub fn assert_shape(&self, other: &Shape)
pub fn assert_shape(&self, other: &Shape)
Assert that this shape is equal to the given shape, panicking if it’s not
Sourcepub const fn requires_eager_materialization(&self) -> bool
pub const fn requires_eager_materialization(&self) -> bool
Returns true if this shape requires eager materialization.
Shapes that require eager materialization cannot have their construction deferred because they need all their data available at once. Examples include:
Arc<[T]>,Box<[T]>,Rc<[T]>- slice-based smart pointers that need all elements to compute the final allocation
This is used by deferred validation mode in Partial to determine which
shapes must be fully materialized before proceeding.
Source§impl Shape
impl Shape
Sourcepub fn allocate(&self) -> Result<PtrUninit, UnsizedError>
Available on crate feature alloc only.
pub fn allocate(&self) -> Result<PtrUninit, UnsizedError>
alloc only.Heap-allocate a value of this shape
Sourcepub unsafe fn deallocate_mut(&self, ptr: PtrMut) -> Result<(), UnsizedError>
Available on crate feature alloc only.
pub unsafe fn deallocate_mut(&self, ptr: PtrMut) -> Result<(), UnsizedError>
alloc only.Deallocate a heap-allocated value of this shape
§Safety
ptrmust have been allocated usingSelf::allocateand be aligned for this shape.ptrmust point to a region that is not already deallocated.
Sourcepub unsafe fn deallocate_uninit(
&self,
ptr: PtrUninit,
) -> Result<(), UnsizedError>
Available on crate feature alloc only.
pub unsafe fn deallocate_uninit( &self, ptr: PtrUninit, ) -> Result<(), UnsizedError>
alloc only.Deallocate a heap-allocated, uninitialized value of this shape.
§Safety
ptrmust have been allocated usingSelf::allocate(or equivalent) for this shape.ptrmust not have been already deallocated.ptrmust be properly aligned for this shape.
Source§impl Shape
impl Shape
Sourcepub const UNSIZED_LAYOUT: ShapeLayout = ShapeLayout::Unsized
pub const UNSIZED_LAYOUT: ShapeLayout = ShapeLayout::Unsized
Returns the unsized layout marker.
Sourcepub const fn id_of<T>() -> ConstTypeIdwhere
T: ?Sized,
pub const fn id_of<T>() -> ConstTypeIdwhere
T: ?Sized,
Returns a const type ID for type T.
Sourcepub const fn layout_of<T>() -> ShapeLayout
pub const fn layout_of<T>() -> ShapeLayout
Returns the sized layout for type T.
Sourcepub fn has_deny_unknown_fields_attr(&self) -> bool
pub fn has_deny_unknown_fields_attr(&self) -> bool
Returns true if this shape has the deny_unknown_fields builtin attribute.
Sourcepub fn has_default_attr(&self) -> bool
pub fn has_default_attr(&self) -> bool
Returns true if this shape has the default builtin attribute.
Sourcepub fn has_builtin_attr(&self, key: &str) -> bool
pub fn has_builtin_attr(&self, key: &str) -> bool
Returns true if this shape has a builtin attribute with the given key.
Sourcepub fn is_transparent(&self) -> bool
pub fn is_transparent(&self) -> bool
Returns true if this shape is transparent.
A type is transparent if it has #[repr(transparent)] or is marked
with #[facet(transparent)].
Sourcepub const fn is_untagged(&self) -> bool
pub const fn is_untagged(&self) -> bool
Returns true if this enum is untagged.
Untagged enums serialize their content directly without any discriminant.
This checks the UNTAGGED flag (O(1)).
Sourcepub const fn is_numeric(&self) -> bool
pub const fn is_numeric(&self) -> bool
Returns true if this enum is numeric.
This checks the NUMERIC flag (O(1)).
Sourcepub const fn is_pod(&self) -> bool
pub const fn is_pod(&self) -> bool
Returns true if this type is Plain Old Data.
POD types have no invariants - any combination of valid field values produces a valid instance. This enables safe mutation through reflection (poke operations).
This returns true if:
- The type is a primitive (implicitly POD), OR
- The type has the
PODflag set via#[facet(pod)]
Note: POD is NOT an auto-trait. A struct with all POD fields is NOT automatically POD - it must be explicitly marked. This is because the struct might have semantic invariants that aren’t expressed in the type system (e.g., “these two fields must be in sync”).
Containers like Vec<T> and Option<T> don’t need POD marking - they
are manipulated through their vtables which maintain their invariants.
The POD-ness of the element type T matters when mutating elements.
Sourcepub const fn is_metadata_container(&self) -> bool
pub const fn is_metadata_container(&self) -> bool
Returns true if this struct is a metadata container.
Metadata containers serialize transparently through their non-metadata field
while preserving metadata fields for formats that support them.
This checks the METADATA_CONTAINER flag (O(1)).
Sourcepub const fn get_tag_attr(&self) -> Option<&'static str>
pub const fn get_tag_attr(&self) -> Option<&'static str>
Returns the tag field name for internally/adjacently tagged enums.
This is the direct field access (O(1)), not an attribute lookup.
Sourcepub const fn get_content_attr(&self) -> Option<&'static str>
pub const fn get_content_attr(&self) -> Option<&'static str>
Returns the content field name for adjacently tagged enums.
This is the direct field access (O(1)), not an attribute lookup.
Sourcepub fn get_builtin_attr_value<'a, T>(&self, key: &str) -> Option<T>
pub fn get_builtin_attr_value<'a, T>(&self, key: &str) -> Option<T>
Gets a builtin attribute value by key.
This is a helper for attributes with simple payload types like &'static str.
Sourcepub fn format_proxy(&self, format: &str) -> Option<&'static ProxyDef>
Available on crate feature alloc only.
pub fn format_proxy(&self, format: &str) -> Option<&'static ProxyDef>
alloc only.Sourcepub fn effective_proxy(&self, format: Option<&str>) -> Option<&'static ProxyDef>
Available on crate feature alloc only.
pub fn effective_proxy(&self, format: Option<&str>) -> Option<&'static ProxyDef>
alloc only.Gets the effective proxy definition for the given format.
Resolution order:
- Format-specific proxy (e.g.,
xml::proxywhen format is “xml”) - Format-agnostic proxy (
proxy)
§Arguments
format- The format namespace (e.g., “xml”, “json”), orNonefor format-agnostic
§Returns
The appropriate proxy definition, or None if no proxy is defined.
Sourcepub fn has_any_proxy(&self) -> bool
Available on crate feature alloc only.
pub fn has_any_proxy(&self) -> bool
alloc only.Returns true if this shape has any proxy (format-specific or format-agnostic).
Sourcepub fn computed_variance(&'static self) -> Variance
pub fn computed_variance(&'static self) -> Variance
Compute the combined variance of this type over all its lifetime parameters.
Variance describes how a type relates to subtyping of its parameters. From the Rustonomicon:
- Covariant: lifetimes can be shortened (
'static→'a) - Contravariant: lifetimes can be lengthened (
'a→'static) - Invariant: lifetimes cannot be changed
- Bivariant: no lifetime parameters (can be treated as any of the above)
This method computes the combined variance across all lifetime parameters in the type. For example:
i32→ Bivariant (no lifetimes)&'a T→ Covariant (single lifetime in covariant position)&'a mut &'b T→ Invariant ('acovariant +'binvariant = invariant)
The primary use case is determining if Peek::shrink_lifetime or
Peek::grow_lifetime operations are safe:
can_shrink()is true for Covariant and Bivariantcan_grow()is true for Contravariant and Bivariant
See GitHub issue #1713 for discussion of potential API improvements.
Source§impl Shape
impl Shape
Sourcepub unsafe fn call_debug(
&'static self,
ptr: PtrConst,
f: &mut Formatter<'_>,
) -> Option<Result<(), Error>>
pub unsafe fn call_debug( &'static self, ptr: PtrConst, f: &mut Formatter<'_>, ) -> Option<Result<(), Error>>
Call the debug function, regardless of vtable style.
§Safety
ptr must point to a valid value of this shape’s type.
Sourcepub unsafe fn call_display(
&'static self,
ptr: PtrConst,
f: &mut Formatter<'_>,
) -> Option<Result<(), Error>>
pub unsafe fn call_display( &'static self, ptr: PtrConst, f: &mut Formatter<'_>, ) -> Option<Result<(), Error>>
Call the display function, regardless of vtable style.
§Safety
ptr must point to a valid value of this shape’s type.
Sourcepub unsafe fn call_hash(
&'static self,
ptr: PtrConst,
hasher: &mut HashProxy<'_>,
) -> Option<()>
pub unsafe fn call_hash( &'static self, ptr: PtrConst, hasher: &mut HashProxy<'_>, ) -> Option<()>
Call the hash function, regardless of vtable style.
§Safety
ptr must point to a valid value of this shape’s type.
Sourcepub unsafe fn call_partial_eq(
&'static self,
a: PtrConst,
b: PtrConst,
) -> Option<bool>
pub unsafe fn call_partial_eq( &'static self, a: PtrConst, b: PtrConst, ) -> Option<bool>
Call the partial_eq function, regardless of vtable style.
§Safety
a and b must point to valid values of this shape’s type.
Sourcepub unsafe fn call_partial_cmp(
&'static self,
a: PtrConst,
b: PtrConst,
) -> Option<Option<Ordering>>
pub unsafe fn call_partial_cmp( &'static self, a: PtrConst, b: PtrConst, ) -> Option<Option<Ordering>>
Call the partial_cmp function, regardless of vtable style.
§Safety
a and b must point to valid values of this shape’s type.
Sourcepub unsafe fn call_cmp(
&'static self,
a: PtrConst,
b: PtrConst,
) -> Option<Ordering>
pub unsafe fn call_cmp( &'static self, a: PtrConst, b: PtrConst, ) -> Option<Ordering>
Call the cmp function, regardless of vtable style.
§Safety
a and b must point to valid values of this shape’s type.
Sourcepub unsafe fn call_drop_in_place(&'static self, ptr: PtrMut) -> Option<()>
pub unsafe fn call_drop_in_place(&'static self, ptr: PtrMut) -> Option<()>
Call the drop_in_place function from type_ops.
§Safety
ptr must point to a valid value of this shape’s type that can be dropped.
Sourcepub unsafe fn call_default_in_place(&'static self, ptr: PtrMut) -> Option<()>
pub unsafe fn call_default_in_place(&'static self, ptr: PtrMut) -> Option<()>
Call the default_in_place function from type_ops.
§Safety
ptr must point to uninitialized memory suitable for this shape’s type.
Sourcepub unsafe fn call_invariants(
&'static self,
ptr: PtrConst,
) -> Option<Result<(), String>>
pub unsafe fn call_invariants( &'static self, ptr: PtrConst, ) -> Option<Result<(), String>>
Call the invariants function, regardless of vtable style.
§Safety
ptr must point to a valid value of this shape’s type.
Sourcepub unsafe fn call_parse(
&'static self,
s: &str,
dst: PtrUninit,
) -> Option<Result<(), ParseError>>
pub unsafe fn call_parse( &'static self, s: &str, dst: PtrUninit, ) -> Option<Result<(), ParseError>>
Call the parse function, regardless of vtable style.
§Safety
dst must point to uninitialized memory suitable for this shape’s type.
Sourcepub unsafe fn call_parse_bytes(
&'static self,
bytes: &[u8],
dst: PtrUninit,
) -> Option<Result<(), ParseError>>
pub unsafe fn call_parse_bytes( &'static self, bytes: &[u8], dst: PtrUninit, ) -> Option<Result<(), ParseError>>
Call the parse_bytes function, regardless of vtable style.
For types with efficient binary representations (e.g., UUID as 16 bytes).
§Safety
dst must point to uninitialized memory suitable for this shape’s type.
Sourcepub unsafe fn call_try_from(
&'static self,
src_shape: &'static Shape,
src: PtrConst,
dst: PtrUninit,
) -> Option<TryFromOutcome>
pub unsafe fn call_try_from( &'static self, src_shape: &'static Shape, src: PtrConst, dst: PtrUninit, ) -> Option<TryFromOutcome>
Call the try_from function, regardless of vtable style.
§Safety
src must point to a valid value of the source type (described by src_shape).
dst must point to uninitialized memory suitable for this shape’s type.
Sourcepub unsafe fn call_try_borrow_inner(
&'static self,
ptr: PtrConst,
) -> Option<Result<PtrMut, String>>
pub unsafe fn call_try_borrow_inner( &'static self, ptr: PtrConst, ) -> Option<Result<PtrMut, String>>
Call the try_borrow_inner function, regardless of vtable style.
§Safety
ptr must point to a valid value of this shape’s type.
Sourcepub unsafe fn call_clone_into(
&'static self,
src: PtrConst,
dst: PtrMut,
) -> Option<()>
pub unsafe fn call_clone_into( &'static self, src: PtrConst, dst: PtrMut, ) -> Option<()>
Call the clone_into function from type_ops.
§Safety
src must point to a valid value of this shape’s type.
dst must point to uninitialized memory suitable for this shape’s type.
Source§impl Shape
impl Shape
Sourcepub fn scalar_type(&self) -> Option<ScalarType>
pub fn scalar_type(&self) -> Option<ScalarType>
Get the scalar type if this shape represents a scalar.
Returns Some(ScalarType) if this shape corresponds to a known scalar type
(primitives, String, Cow<str>, network address types, etc.),
or None if it’s a non-scalar type like a struct, enum, list, or map.
§Example
use facet_core::{Facet, ScalarType};
assert_eq!(bool::SHAPE.scalar_type(), Some(ScalarType::Bool));
assert_eq!(u32::SHAPE.scalar_type(), Some(ScalarType::U32));
assert_eq!(f64::SHAPE.scalar_type(), Some(ScalarType::F64));Source§impl Shape
impl Shape
Sourcepub const fn is(&self, characteristic: Characteristic) -> bool
pub const fn is(&self, characteristic: Characteristic) -> bool
Checks if a shape has the given characteristic.
Sourcepub const fn is_display(&self) -> bool
pub const fn is_display(&self) -> bool
Check if this shape implements the Display trait
Sourcepub const fn is_partial_eq(&self) -> bool
pub const fn is_partial_eq(&self) -> bool
Check if this shape implements the PartialEq trait
Sourcepub const fn is_partial_ord(&self) -> bool
pub const fn is_partial_ord(&self) -> bool
Check if this shape implements the PartialOrd trait
Sourcepub const fn is_default(&self) -> bool
pub const fn is_default(&self) -> bool
Check if this shape implements the Default trait
Sourcepub const fn is_from_str(&self) -> bool
pub const fn is_from_str(&self) -> bool
Check if this shape implements the FromStr trait
Sourcepub fn write_type_name(
&'static self,
f: &mut Formatter<'_>,
opts: TypeNameOpts,
) -> Result<(), Error>
pub fn write_type_name( &'static self, f: &mut Formatter<'_>, opts: TypeNameOpts, ) -> Result<(), Error>
Writes the name of this type to the given formatter.
If the type has a custom type_name function, it will be used. Otherwise, falls back to the type_identifier.
Sourcepub const fn type_name(&'static self) -> TypeNameDisplay
pub const fn type_name(&'static self) -> TypeNameDisplay
Returns a wrapper that implements Display for the full type name
including generic parameters.
§Example
extern crate alloc;
use facet_core::Facet;
use alloc::vec::Vec;
let shape = <Vec<u32>>::SHAPE;
assert_eq!(format!("{}", shape.type_name()), "Vec<u32>");