facet_reflect/partial/partial_api/build.rs
1use super::*;
2
3////////////////////////////////////////////////////////////////////////////////////////////////////
4// Build
5////////////////////////////////////////////////////////////////////////////////////////////////////
6impl<'facet, const BORROW: bool> Partial<'facet, BORROW> {
7 /// Builds the value, consuming the Partial.
8 pub fn build(mut self) -> Result<HeapValue<'facet, BORROW>, ReflectError> {
9 if self.frames().len() != 1 {
10 return Err(ReflectError::InvariantViolation {
11 invariant: "Partial::build() expects a single frame — call end() until that's the case",
12 });
13 }
14
15 let frame = self.frames_mut().pop().unwrap();
16
17 // Check initialization before proceeding
18 if let Err(e) = frame.require_full_initialization() {
19 // Put the frame back so Drop can handle cleanup properly
20 self.frames_mut().push(frame);
21 return Err(e);
22 }
23
24 // Check invariants if present
25 // Safety: The value is fully initialized at this point (we just checked with require_full_initialization)
26 let value_ptr = unsafe { frame.data.assume_init().as_const() };
27 if let Some(result) = unsafe { frame.shape.call_invariants(value_ptr) } {
28 match result {
29 Ok(()) => {
30 // Invariants passed
31 }
32 Err(message) => {
33 // Put the frame back so Drop can handle cleanup properly
34 let shape = frame.shape;
35 self.frames_mut().push(frame);
36 return Err(ReflectError::UserInvariantFailed { message, shape });
37 }
38 }
39 }
40
41 // Mark as built to prevent Drop from cleaning up the value
42 self.state = PartialState::Built;
43
44 match frame
45 .shape
46 .layout
47 .sized_layout()
48 .map_err(|_layout_err| ReflectError::Unsized {
49 shape: frame.shape,
50 operation: "build (final check for sized layout)",
51 }) {
52 Ok(layout) => {
53 // Determine if we should deallocate based on ownership
54 let should_dealloc = !matches!(frame.ownership, FrameOwnership::ManagedElsewhere);
55
56 Ok(HeapValue {
57 guard: Some(Guard {
58 ptr: unsafe { NonNull::new_unchecked(frame.data.as_mut_byte_ptr()) },
59 layout,
60 should_dealloc,
61 }),
62 shape: frame.shape,
63 phantom: PhantomData,
64 })
65 }
66 Err(e) => {
67 // Put the frame back for proper cleanup
68 self.frames_mut().push(frame);
69 Err(e)
70 }
71 }
72 }
73}