facet_reflect/partial/partial_api/
alloc.rs

1use super::*;
2use crate::AllocatedShape;
3
4////////////////////////////////////////////////////////////////////////////////////////////////////
5// Allocation, constructors etc.
6////////////////////////////////////////////////////////////////////////////////////////////////////
7
8/// Allocate a Partial that can borrow from input with lifetime 'facet.
9/// This is the default mode - use this when deserializing from a buffer that outlives the result.
10impl<'facet> Partial<'facet, true> {
11    /// Allocates a new [Partial] instance on the heap, with the given shape and type.
12    ///
13    /// This creates a borrowing Partial that can hold references with lifetime 'facet.
14    pub fn alloc<T>() -> Result<Self, ReflectError>
15    where
16        T: Facet<'facet> + ?Sized,
17    {
18        // SAFETY: T::SHAPE comes from the Facet implementation for T,
19        // which is an unsafe trait requiring accurate shape descriptions.
20        unsafe { Self::alloc_shape(T::SHAPE) }
21    }
22
23    /// Allocates a new [Partial] instance on the heap, with the given shape.
24    ///
25    /// This creates a borrowing Partial that can hold references with lifetime 'facet.
26    ///
27    /// # Safety
28    ///
29    /// The caller must ensure that `shape` accurately describes the memory layout
30    /// and invariants of any type `T` that will be materialized from this `Partial`.
31    ///
32    /// In particular:
33    /// - `shape.id` must match `TypeId::of::<T>()`
34    /// - `shape.layout` must match `Layout::of::<T>()`
35    /// - `shape.ty` and `shape.def` must accurately describe T's structure
36    /// - All vtable operations must be valid for type T
37    ///
38    /// Violating these requirements may cause undefined behavior when accessing
39    /// fields, materializing values, or calling vtable methods.
40    ///
41    /// **Safe alternative**: Use [`Partial::alloc::<T>()`](Self::alloc) which gets the shape
42    /// from `T::SHAPE` (guaranteed safe by `unsafe impl Facet for T`).
43    pub unsafe fn alloc_shape(shape: &'static Shape) -> Result<Self, ReflectError> {
44        alloc_shape_inner(shape)
45    }
46}
47
48/// Allocate a Partial that cannot borrow - all data must be owned.
49/// Use this when deserializing from a temporary buffer (e.g., HTTP request body).
50impl Partial<'static, false> {
51    /// Allocates a new [Partial] instance on the heap, with the given shape and type.
52    ///
53    /// This creates an owned Partial that cannot hold borrowed references.
54    /// Use this when the input buffer is temporary and won't outlive the result.
55    pub fn alloc_owned<T>() -> Result<Self, ReflectError>
56    where
57        T: Facet<'static> + ?Sized,
58    {
59        // SAFETY: T::SHAPE comes from the Facet implementation for T,
60        // which is an unsafe trait requiring accurate shape descriptions.
61        unsafe { Self::alloc_shape_owned(T::SHAPE) }
62    }
63
64    /// Allocates a new [Partial] instance on the heap, with the given shape.
65    ///
66    /// This creates an owned Partial that cannot hold borrowed references.
67    ///
68    /// # Safety
69    ///
70    /// The caller must ensure that `shape` accurately describes the memory layout
71    /// and invariants of any type `T` that will be materialized from this `Partial`.
72    ///
73    /// In particular:
74    /// - `shape.id` must match `TypeId::of::<T>()`
75    /// - `shape.layout` must match `Layout::of::<T>()`
76    /// - `shape.ty` and `shape.def` must accurately describe T's structure
77    /// - All vtable operations must be valid for type T
78    ///
79    /// Violating these requirements may cause undefined behavior when accessing
80    /// fields, materializing values, or calling vtable methods.
81    ///
82    /// **Safe alternative**: Use [`Partial::alloc_owned::<T>()`](Self::alloc_owned) which gets the shape
83    /// from `T::SHAPE` (guaranteed safe by `unsafe impl Facet for T`).
84    pub unsafe fn alloc_shape_owned(shape: &'static Shape) -> Result<Self, ReflectError> {
85        alloc_shape_inner(shape)
86    }
87}
88
89fn alloc_shape_inner<'facet, const BORROW: bool>(
90    shape: &'static Shape,
91) -> Result<Partial<'facet, BORROW>, ReflectError> {
92    crate::trace!(
93        "alloc_shape({:?}), with layout {:?}",
94        shape,
95        shape.layout.sized_layout()
96    );
97
98    let data = shape.allocate().map_err(|_| ReflectError::Unsized {
99        shape,
100        operation: "alloc_shape",
101    })?;
102
103    // Get the actual allocated size
104    let allocated_size = shape.layout.sized_layout().expect("must be sized").size();
105
106    // Preallocate a couple of frames. The cost of allocating 4 frames is
107    // basically identical to allocating 1 frame, so for every type that
108    // has at least 1 level of nesting, this saves at least one guaranteed reallocation.
109    let mut stack = Vec::with_capacity(4);
110    stack.push(Frame::new(
111        data,
112        AllocatedShape::new(shape, allocated_size),
113        FrameOwnership::Owned,
114    ));
115
116    Ok(Partial {
117        mode: FrameMode::Strict { stack },
118        state: PartialState::Active,
119        invariant: PhantomData,
120    })
121}