1#[cfg(test)]
125mod tests;
126
127use alloc::boxed::Box;
128use alloc::format;
129use alloc::string::{String, ToString};
130use alloc::vec;
131
132mod iset;
133
134use crate::{Peek, ReflectError, trace};
135use facet_core::DefaultInPlaceFn;
136
137use core::marker::PhantomData;
138
139mod heap_value;
140use alloc::vec::Vec;
141pub use heap_value::*;
142
143use facet_core::{
144 Def, EnumRepr, Facet, KnownSmartPointer, PtrConst, PtrMut, PtrUninit, Shape, Type, UserType,
145 Variant,
146};
147use iset::ISet;
148
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151enum PartialState {
152 Active,
154 Built,
156 BuildFailed,
158}
159
160pub struct Partial<'facet, 'shape> {
167 frames: Vec<Frame<'shape>>,
169
170 state: PartialState,
172
173 invariant: PhantomData<fn(&'facet ()) -> &'facet ()>,
174}
175
176#[derive(Clone, Copy, Debug)]
177enum MapInsertState {
178 Idle,
180 PushingKey {
182 key_ptr: Option<PtrUninit<'static>>,
184 },
185 PushingValue {
187 key_ptr: PtrUninit<'static>,
189 value_ptr: Option<PtrUninit<'static>>,
191 },
192}
193
194#[derive(Debug)]
195enum FrameOwnership {
196 Owned,
198 Field,
200 ManagedElsewhere,
202}
203
204struct Frame<'shape> {
205 data: PtrUninit<'static>,
207
208 shape: &'shape Shape<'shape>,
210
211 tracker: Tracker<'shape>,
213
214 ownership: FrameOwnership,
216}
217
218enum Tracker<'shape> {
219 Uninit,
221
222 Init,
224
225 Array {
227 iset: ISet,
229 current_child: Option<usize>,
231 },
232
233 Struct {
235 iset: ISet,
238
239 current_child: Option<usize>,
242 },
243
244 SmartPointer {
246 is_initialized: bool,
248 },
249
250 Enum {
252 variant: Variant<'shape>,
253 data: ISet,
254 current_child: Option<usize>,
256 },
257
258 List {
260 is_initialized: bool,
262 current_child: bool,
264 },
265
266 Map {
268 is_initialized: bool,
270 insert_state: MapInsertState,
272 },
273
274 Option {
276 building_inner: bool,
278 },
279}
280
281impl<'shape> Frame<'shape> {
282 fn new(
283 data: PtrUninit<'static>,
284 shape: &'shape Shape<'shape>,
285 ownership: FrameOwnership,
286 ) -> Self {
287 let tracker = match shape.ty {
290 Type::User(UserType::Struct(struct_type)) if struct_type.fields.is_empty() => {
291 Tracker::Init
292 }
293 _ => Tracker::Uninit,
294 };
295
296 Self {
297 data,
298 shape,
299 tracker,
300 ownership,
301 }
302 }
303
304 fn require_full_initialization(&self) -> Result<(), ReflectError<'shape>> {
306 match self.tracker {
307 Tracker::Uninit => Err(ReflectError::UninitializedValue { shape: self.shape }),
308 Tracker::Init => Ok(()),
309 Tracker::Array { iset, .. } => {
310 match self.shape.ty {
311 Type::Sequence(facet_core::SequenceType::Array(array_def)) => {
312 if (0..array_def.n).all(|idx| iset.get(idx)) {
314 Ok(())
315 } else {
316 Err(ReflectError::UninitializedValue { shape: self.shape })
317 }
318 }
319 _ => Err(ReflectError::UninitializedValue { shape: self.shape }),
320 }
321 }
322 Tracker::Struct { iset, .. } => {
323 if iset.all_set() {
324 Ok(())
325 } else {
326 match self.shape.ty {
328 Type::User(UserType::Struct(struct_type)) => {
329 let first_missing_idx =
331 (0..struct_type.fields.len()).find(|&idx| !iset.get(idx));
332 if let Some(missing_idx) = first_missing_idx {
333 let field_name = struct_type.fields[missing_idx].name;
334 Err(ReflectError::UninitializedField {
335 shape: self.shape,
336 field_name,
337 })
338 } else {
339 Err(ReflectError::UninitializedValue { shape: self.shape })
341 }
342 }
343 _ => Err(ReflectError::UninitializedValue { shape: self.shape }),
344 }
345 }
346 }
347 Tracker::Enum { variant, data, .. } => {
348 let num_fields = variant.data.fields.len();
350 if num_fields == 0 {
351 Ok(())
353 } else if (0..num_fields).all(|idx| data.get(idx)) {
354 Ok(())
355 } else {
356 let first_missing_idx = (0..num_fields).find(|&idx| !data.get(idx));
358 if let Some(missing_idx) = first_missing_idx {
359 let field_name = variant.data.fields[missing_idx].name;
360 Err(ReflectError::UninitializedEnumField {
361 shape: self.shape,
362 field_name,
363 variant_name: variant.name,
364 })
365 } else {
366 Err(ReflectError::UninitializedValue { shape: self.shape })
367 }
368 }
369 }
370 Tracker::SmartPointer { is_initialized } => {
371 if is_initialized {
372 Ok(())
373 } else {
374 Err(ReflectError::UninitializedValue { shape: self.shape })
375 }
376 }
377 Tracker::List { is_initialized, .. } => {
378 if is_initialized {
379 Ok(())
380 } else {
381 Err(ReflectError::UninitializedValue { shape: self.shape })
382 }
383 }
384 Tracker::Map {
385 is_initialized,
386 insert_state,
387 } => {
388 if is_initialized && matches!(insert_state, MapInsertState::Idle) {
389 Ok(())
390 } else {
391 Err(ReflectError::UninitializedValue { shape: self.shape })
392 }
393 }
394 Tracker::Option { building_inner } => {
395 if building_inner {
396 Err(ReflectError::UninitializedValue { shape: self.shape })
397 } else {
398 Ok(())
399 }
400 }
401 }
402 }
403}
404
405impl<'facet, 'shape> Partial<'facet, 'shape> {
406 pub fn alloc_shape(shape: &'shape Shape<'shape>) -> Result<Self, ReflectError<'shape>> {
408 let data = shape
409 .allocate()
410 .map_err(|_| ReflectError::Unsized { shape })?;
411
412 Ok(Self {
413 frames: vec![Frame::new(data, shape, FrameOwnership::Owned)],
414 state: PartialState::Active,
415 invariant: PhantomData,
416 })
417 }
418
419 pub fn alloc<T>() -> Result<TypedPartial<'facet, 'shape, T>, ReflectError<'shape>>
421 where
422 T: Facet<'facet>,
423 {
424 Ok(TypedPartial {
425 inner: Self::alloc_shape(T::SHAPE)?,
426 phantom: PhantomData,
427 })
428 }
429
430 pub fn from_ptr(data: PtrUninit<'_>, shape: &'shape Shape<'shape>) -> Self {
432 let data_static = PtrUninit::new(data.as_mut_byte_ptr());
435 Self {
436 frames: vec![Frame::new(data_static, shape, FrameOwnership::Field)],
437 state: PartialState::Active,
438 invariant: PhantomData,
439 }
440 }
441
442 fn require_active(&self) -> Result<(), ReflectError<'shape>> {
444 if self.state == PartialState::Active {
445 Ok(())
446 } else {
447 Err(ReflectError::InvariantViolation {
448 invariant: "Cannot use Partial after it has been built or poisoned",
449 })
450 }
451 }
452
453 pub fn frame_count(&self) -> usize {
455 self.frames.len()
456 }
457
458 pub fn set<U>(&mut self, value: U) -> Result<&mut Self, ReflectError<'shape>>
460 where
461 U: Facet<'facet>,
462 {
463 self.require_active()?;
464
465 let ptr_const = PtrConst::new(&raw const value);
468 unsafe {
469 self.set_shape(ptr_const, U::SHAPE)?
471 };
472
473 core::mem::forget(value);
475 Ok(self)
476 }
477
478 pub unsafe fn set_shape(
494 &mut self,
495 src_value: PtrConst<'_>,
496 src_shape: &'shape Shape<'shape>,
497 ) -> Result<&mut Self, ReflectError<'shape>> {
498 self.require_active()?;
499
500 let fr = self.frames.last_mut().unwrap();
501 if !fr.shape.is_shape(src_shape) {
502 let err = ReflectError::WrongShape {
503 expected: fr.shape,
504 actual: src_shape,
505 };
506 return Err(err);
507 }
508
509 if fr.shape.layout.sized_layout().is_err() {
510 return Err(ReflectError::Unsized { shape: fr.shape });
511 }
512
513 unsafe {
514 fr.data.copy_from(src_value, fr.shape).unwrap();
515 }
516 fr.tracker = Tracker::Init;
517 Ok(self)
518 }
519
520 pub fn set_default(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
522 let frame = self.frames.last().unwrap(); if let Some(default_fn) = (frame.shape.vtable.default_in_place)() {
525 self.set_from_function(move |ptr: PtrUninit<'_>| {
532 unsafe { default_fn(PtrUninit::new(ptr.as_mut_byte_ptr())) };
533 Ok(())
534 })
535 } else {
536 Err(ReflectError::OperationFailed {
538 shape: frame.shape,
539 operation: "type does not implement Default",
540 })
541 }
542 }
543
544 pub fn set_field_default(
546 &mut self,
547 field_default_fn: DefaultInPlaceFn,
548 ) -> Result<&mut Self, ReflectError<'shape>> {
549 self.set_from_function(move |ptr: PtrUninit<'_>| {
556 unsafe { field_default_fn(PtrUninit::new(ptr.as_mut_byte_ptr())) };
557 Ok(())
558 })
559 }
560
561 pub fn set_from_function<F>(&mut self, f: F) -> Result<&mut Self, ReflectError<'shape>>
563 where
564 F: FnOnce(PtrUninit<'_>) -> Result<(), ReflectError<'shape>>,
565 {
566 self.require_active()?;
567
568 let frame = self.frames.last_mut().unwrap();
569
570 if matches!(frame.tracker, Tracker::Init) {
572 if let Some(drop_fn) = (frame.shape.vtable.drop_in_place)() {
573 unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };
574 }
575 }
576
577 if matches!(
579 frame.tracker,
580 Tracker::Option {
581 building_inner: true
582 }
583 ) {
584 return Err(ReflectError::OperationFailed {
585 shape: frame.shape,
586 operation: "Cannot overwrite while building Option inner value",
587 });
588 }
589
590 match f(frame.data) {
592 Ok(()) => {
593 frame.tracker = Tracker::Init;
595 Ok(self)
596 }
597 Err(e) => Err(e),
598 }
599 }
600
601 pub fn parse_from_str(&mut self, s: &str) -> Result<&mut Self, ReflectError<'shape>> {
603 self.require_active()?;
604
605 let frame = self.frames.last_mut().unwrap();
606
607 let parse_fn = match (frame.shape.vtable.parse)() {
609 Some(parse_fn) => parse_fn,
610 None => {
611 return Err(ReflectError::OperationFailed {
612 shape: frame.shape,
613 operation: "Type does not support parsing from string",
614 });
615 }
616 };
617
618 if matches!(frame.tracker, Tracker::Init) {
620 if let Some(drop_fn) = (frame.shape.vtable.drop_in_place)() {
621 unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };
622 }
623 }
624
625 if matches!(
627 frame.tracker,
628 Tracker::Option {
629 building_inner: true
630 }
631 ) {
632 return Err(ReflectError::OperationFailed {
633 shape: frame.shape,
634 operation: "Cannot overwrite while building Option inner value",
635 });
636 }
637
638 let result = unsafe { parse_fn(s, frame.data) };
640 match result {
641 Ok(_) => {
642 frame.tracker = Tracker::Init;
643 Ok(self)
644 }
645 Err(_parse_error) => Err(ReflectError::OperationFailed {
646 shape: frame.shape,
647 operation: "Failed to parse string value",
648 }),
649 }
650 }
651
652 pub fn select_variant_named(
654 &mut self,
655 variant_name: &str,
656 ) -> Result<&mut Self, ReflectError<'shape>> {
657 self.require_active()?;
658
659 let fr = self.frames.last_mut().unwrap();
660
661 let enum_type = match fr.shape.ty {
663 Type::User(UserType::Enum(e)) => e,
664 _ => {
665 return Err(ReflectError::OperationFailed {
666 shape: fr.shape,
667 operation: "push_variant_named requires an enum type",
668 });
669 }
670 };
671
672 let variant = match enum_type.variants.iter().find(|v| v.name == variant_name) {
674 Some(v) => v,
675 None => {
676 return Err(ReflectError::OperationFailed {
677 shape: fr.shape,
678 operation: "No variant found with the given name",
679 });
680 }
681 };
682
683 let discriminant = match variant.discriminant {
685 Some(d) => d,
686 None => {
687 return Err(ReflectError::OperationFailed {
688 shape: fr.shape,
689 operation: "Variant has no discriminant value",
690 });
691 }
692 };
693
694 self.select_variant(discriminant)
696 }
697
698 pub fn select_variant(&mut self, discriminant: i64) -> Result<&mut Self, ReflectError<'shape>> {
700 self.require_active()?;
701
702 let fr = self.frames.last().unwrap();
704
705 let enum_type = match fr.shape.ty {
707 Type::User(UserType::Enum(e)) => e,
708 _ => {
709 return Err(ReflectError::WasNotA {
710 expected: "enum",
711 actual: fr.shape,
712 });
713 }
714 };
715
716 let variant = match enum_type
718 .variants
719 .iter()
720 .find(|v| v.discriminant == Some(discriminant))
721 {
722 Some(v) => v,
723 None => {
724 return Err(ReflectError::OperationFailed {
725 shape: fr.shape,
726 operation: "No variant found with the given discriminant",
727 });
728 }
729 };
730
731 match enum_type.enum_repr {
733 EnumRepr::RustNPO => {
734 return Err(ReflectError::OperationFailed {
735 shape: fr.shape,
736 operation: "RustNPO enums are not supported for incremental building",
737 });
738 }
739 EnumRepr::U8
740 | EnumRepr::U16
741 | EnumRepr::U32
742 | EnumRepr::U64
743 | EnumRepr::I8
744 | EnumRepr::I16
745 | EnumRepr::I32
746 | EnumRepr::I64
747 | EnumRepr::USize
748 | EnumRepr::ISize => {
749 }
751 _ => {
752 return Err(ReflectError::OperationFailed {
753 shape: fr.shape,
754 operation: "Unknown enum representation",
755 });
756 }
757 }
758
759 let fr = self.frames.last_mut().unwrap();
761
762 unsafe {
764 match enum_type.enum_repr {
765 EnumRepr::U8 => {
766 let ptr = fr.data.as_mut_byte_ptr();
767 *ptr = discriminant as u8;
768 }
769 EnumRepr::U16 => {
770 let ptr = fr.data.as_mut_byte_ptr() as *mut u16;
771 *ptr = discriminant as u16;
772 }
773 EnumRepr::U32 => {
774 let ptr = fr.data.as_mut_byte_ptr() as *mut u32;
775 *ptr = discriminant as u32;
776 }
777 EnumRepr::U64 => {
778 let ptr = fr.data.as_mut_byte_ptr() as *mut u64;
779 *ptr = discriminant as u64;
780 }
781 EnumRepr::I8 => {
782 let ptr = fr.data.as_mut_byte_ptr() as *mut i8;
783 *ptr = discriminant as i8;
784 }
785 EnumRepr::I16 => {
786 let ptr = fr.data.as_mut_byte_ptr() as *mut i16;
787 *ptr = discriminant as i16;
788 }
789 EnumRepr::I32 => {
790 let ptr = fr.data.as_mut_byte_ptr() as *mut i32;
791 *ptr = discriminant as i32;
792 }
793 EnumRepr::I64 => {
794 let ptr = fr.data.as_mut_byte_ptr() as *mut i64;
795 *ptr = discriminant;
796 }
797 EnumRepr::USize => {
798 let ptr = fr.data.as_mut_byte_ptr() as *mut usize;
799 *ptr = discriminant as usize;
800 }
801 EnumRepr::ISize => {
802 let ptr = fr.data.as_mut_byte_ptr() as *mut isize;
803 *ptr = discriminant as isize;
804 }
805 _ => unreachable!("Already checked enum representation above"),
806 }
807 }
808
809 fr.tracker = Tracker::Enum {
811 variant: *variant,
812 data: ISet::new(variant.data.fields.len()),
813 current_child: None,
814 };
815
816 Ok(self)
817 }
818
819 pub fn begin_field(&mut self, field_name: &str) -> Result<&mut Self, ReflectError<'shape>> {
821 self.require_active()?;
822
823 let frame = self.frames.last_mut().unwrap();
824 match frame.shape.ty {
825 Type::Primitive(_) => Err(ReflectError::OperationFailed {
826 shape: frame.shape,
827 operation: "cannot select a field from a primitive type",
828 }),
829 Type::Sequence(_) => Err(ReflectError::OperationFailed {
830 shape: frame.shape,
831 operation: "cannot select a field from a sequence type",
832 }),
833 Type::User(user_type) => match user_type {
834 UserType::Struct(struct_type) => {
835 let idx = struct_type.fields.iter().position(|f| f.name == field_name);
836 let idx = match idx {
837 Some(idx) => idx,
838 None => {
839 return Err(ReflectError::OperationFailed {
840 shape: frame.shape,
841 operation: "field not found",
842 });
843 }
844 };
845 self.begin_nth_field(idx)
846 }
847 UserType::Enum(_) => {
848 match &frame.tracker {
850 Tracker::Enum { variant, .. } => {
851 let idx = variant
852 .data
853 .fields
854 .iter()
855 .position(|f| f.name == field_name);
856 let idx = match idx {
857 Some(idx) => idx,
858 None => {
859 return Err(ReflectError::OperationFailed {
860 shape: frame.shape,
861 operation: "field not found in current enum variant",
862 });
863 }
864 };
865 self.begin_nth_enum_field(idx)
866 }
867 _ => Err(ReflectError::OperationFailed {
868 shape: frame.shape,
869 operation: "must call push_variant before selecting enum fields",
870 }),
871 }
872 }
873 UserType::Union(_) => Err(ReflectError::OperationFailed {
874 shape: frame.shape,
875 operation: "unions are not supported",
876 }),
877 UserType::Opaque => Err(ReflectError::OperationFailed {
878 shape: frame.shape,
879 operation: "opaque types cannot be reflected upon",
880 }),
881 },
882 Type::Pointer(_) => Err(ReflectError::OperationFailed {
883 shape: frame.shape,
884 operation: "cannot select a field from a pointer type",
885 }),
886 _ => todo!(),
887 }
888 }
889
890 pub fn select_nth_variant(&mut self, index: usize) -> Result<&mut Self, ReflectError<'shape>> {
892 self.require_active()?;
893
894 let fr = self.frames.last().unwrap();
895
896 let enum_type = match fr.shape.ty {
898 Type::User(UserType::Enum(e)) => e,
899 _ => {
900 return Err(ReflectError::OperationFailed {
901 shape: fr.shape,
902 operation: "select_nth_variant requires an enum type",
903 });
904 }
905 };
906
907 if index >= enum_type.variants.len() {
908 return Err(ReflectError::OperationFailed {
909 shape: fr.shape,
910 operation: "variant index out of bounds",
911 });
912 }
913 let variant = &enum_type.variants[index];
914
915 let discriminant = match variant.discriminant {
917 Some(d) => d,
918 None => {
919 return Err(ReflectError::OperationFailed {
920 shape: fr.shape,
921 operation: "Variant has no discriminant value",
922 });
923 }
924 };
925
926 self.select_variant(discriminant)
928 }
929
930 pub fn begin_nth_field(&mut self, idx: usize) -> Result<&mut Self, ReflectError<'shape>> {
932 self.require_active()?;
933 let frame = self.frames.last_mut().unwrap();
934 match frame.shape.ty {
935 Type::User(user_type) => match user_type {
936 UserType::Struct(struct_type) => {
937 if idx >= struct_type.fields.len() {
938 return Err(ReflectError::OperationFailed {
939 shape: frame.shape,
940 operation: "field index out of bounds",
941 });
942 }
943 let field = &struct_type.fields[idx];
944
945 match &mut frame.tracker {
946 Tracker::Uninit => {
947 frame.tracker = Tracker::Struct {
948 iset: ISet::new(struct_type.fields.len()),
949 current_child: Some(idx),
950 }
951 }
952 Tracker::Struct {
953 iset,
954 current_child,
955 } => {
956 if iset.get(idx) {
958 let field_ptr = unsafe { frame.data.field_init_at(field.offset) };
960 if let Some(drop_fn) = (field.shape.vtable.drop_in_place)() {
961 unsafe { drop_fn(field_ptr) };
962 }
963 iset.unset(idx);
965 }
966 *current_child = Some(idx);
967 }
968 _ => unreachable!(),
969 }
970
971 let field_ptr = unsafe { frame.data.field_uninit_at(field.offset) };
973 let field_shape = field.shape;
974 self.frames
975 .push(Frame::new(field_ptr, field_shape, FrameOwnership::Field));
976
977 Ok(self)
978 }
979 UserType::Enum(_) => {
980 match &frame.tracker {
982 Tracker::Enum { variant, .. } => {
983 if idx >= variant.data.fields.len() {
984 return Err(ReflectError::OperationFailed {
985 shape: frame.shape,
986 operation: "enum field index out of bounds",
987 });
988 }
989 self.begin_nth_enum_field(idx)
990 }
991 _ => Err(ReflectError::OperationFailed {
992 shape: frame.shape,
993 operation: "must call select_variant before selecting enum fields",
994 }),
995 }
996 }
997 UserType::Union(_) => Err(ReflectError::OperationFailed {
998 shape: frame.shape,
999 operation: "unions are not supported",
1000 }),
1001 UserType::Opaque => Err(ReflectError::OperationFailed {
1002 shape: frame.shape,
1003 operation: "opaque types cannot be reflected upon",
1004 }),
1005 },
1006 _ => Err(ReflectError::OperationFailed {
1007 shape: frame.shape,
1008 operation: "cannot select a field from this type",
1009 }),
1010 }
1011 }
1012
1013 pub fn begin_nth_element(&mut self, idx: usize) -> Result<&mut Self, ReflectError<'shape>> {
1015 self.require_active()?;
1016 let frame = self.frames.last_mut().unwrap();
1017 match frame.shape.ty {
1018 Type::Sequence(seq_type) => match seq_type {
1019 facet_core::SequenceType::Array(array_def) => {
1020 if idx >= array_def.n {
1021 return Err(ReflectError::OperationFailed {
1022 shape: frame.shape,
1023 operation: "array index out of bounds",
1024 });
1025 }
1026
1027 if array_def.n > 63 {
1028 return Err(ReflectError::OperationFailed {
1029 shape: frame.shape,
1030 operation: "arrays larger than 63 elements are not yet supported",
1031 });
1032 }
1033
1034 if matches!(frame.tracker, Tracker::Uninit) {
1036 frame.tracker = Tracker::Array {
1037 iset: ISet::default(),
1038 current_child: None,
1039 };
1040 }
1041
1042 match &mut frame.tracker {
1043 Tracker::Array {
1044 iset,
1045 current_child,
1046 } => {
1047 let element_layout = match array_def.t.layout.sized_layout() {
1049 Ok(layout) => layout,
1050 Err(_) => {
1051 return Err(ReflectError::Unsized { shape: array_def.t });
1052 }
1053 };
1054 let offset = element_layout.size() * idx;
1055
1056 if iset.get(idx) {
1058 let element_ptr = unsafe { frame.data.field_init_at(offset) };
1060 if let Some(drop_fn) = (array_def.t.vtable.drop_in_place)() {
1061 unsafe { drop_fn(element_ptr) };
1062 }
1063 iset.unset(idx);
1065 }
1066
1067 *current_child = Some(idx);
1068
1069 let element_data = unsafe { frame.data.field_uninit_at(offset) };
1071 self.frames.push(Frame::new(
1072 element_data,
1073 array_def.t,
1074 FrameOwnership::Field,
1075 ));
1076
1077 Ok(self)
1078 }
1079 _ => Err(ReflectError::OperationFailed {
1080 shape: frame.shape,
1081 operation: "expected array tracker state",
1082 }),
1083 }
1084 }
1085 _ => Err(ReflectError::OperationFailed {
1086 shape: frame.shape,
1087 operation: "can only select elements from arrays",
1088 }),
1089 },
1090 _ => Err(ReflectError::OperationFailed {
1091 shape: frame.shape,
1092 operation: "cannot select an element from this type",
1093 }),
1094 }
1095 }
1096
1097 pub fn begin_nth_enum_field(&mut self, idx: usize) -> Result<&mut Self, ReflectError<'shape>> {
1099 self.require_active()?;
1100 let frame = self.frames.last_mut().unwrap();
1101
1102 let (variant, enum_type) = match (&frame.tracker, &frame.shape.ty) {
1104 (Tracker::Enum { variant, .. }, Type::User(UserType::Enum(e))) => (variant, e),
1105 _ => {
1106 return Err(ReflectError::OperationFailed {
1107 shape: frame.shape,
1108 operation: "push_nth_enum_field requires an enum with a variant selected",
1109 });
1110 }
1111 };
1112
1113 if idx >= variant.data.fields.len() {
1115 return Err(ReflectError::OperationFailed {
1116 shape: frame.shape,
1117 operation: "enum field index out of bounds",
1118 });
1119 }
1120
1121 let field = &variant.data.fields[idx];
1122
1123 match &mut frame.tracker {
1125 Tracker::Enum {
1126 data,
1127 current_child,
1128 ..
1129 } => {
1130 if data.get(idx) {
1132 let _discriminant_size = match enum_type.enum_repr {
1134 EnumRepr::U8 | EnumRepr::I8 => 1,
1135 EnumRepr::U16 | EnumRepr::I16 => 2,
1136 EnumRepr::U32 | EnumRepr::I32 => 4,
1137 EnumRepr::U64 | EnumRepr::I64 => 8,
1138 EnumRepr::USize | EnumRepr::ISize => core::mem::size_of::<usize>(),
1139 EnumRepr::RustNPO => {
1140 return Err(ReflectError::OperationFailed {
1141 shape: frame.shape,
1142 operation: "RustNPO enums are not supported",
1143 });
1144 }
1145 _ => {
1146 return Err(ReflectError::OperationFailed {
1147 shape: frame.shape,
1148 operation: "Unknown enum representation",
1149 });
1150 }
1151 };
1152
1153 let field_ptr = unsafe { frame.data.as_mut_byte_ptr().add(field.offset) };
1155
1156 if let Some(drop_fn) = (field.shape.vtable.drop_in_place)() {
1157 unsafe { drop_fn(PtrMut::new(field_ptr)) };
1158 }
1159
1160 data.unset(idx);
1162 }
1163
1164 *current_child = Some(idx);
1166 }
1167 _ => unreachable!("Already checked that we have Enum tracker"),
1168 }
1169
1170 let field_ptr = unsafe { frame.data.as_mut_byte_ptr().add(field.offset) };
1172 let field_shape = field.shape;
1173
1174 self.frames.push(Frame::new(
1176 PtrUninit::new(field_ptr),
1177 field_shape,
1178 FrameOwnership::Field,
1179 ));
1180
1181 Ok(self)
1182 }
1183
1184 pub fn begin_smart_ptr(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
1186 self.require_active()?;
1187 let frame = self.frames.last_mut().unwrap();
1188
1189 match &frame.shape.def {
1191 Def::SmartPointer(smart_ptr_def) => {
1192 match smart_ptr_def.known {
1194 Some(KnownSmartPointer::Box) | Some(KnownSmartPointer::Arc) => {
1195 }
1197 _ => {
1198 return Err(ReflectError::OperationFailed {
1199 shape: frame.shape,
1200 operation: "only Box and Arc smart pointers are currently supported",
1201 });
1202 }
1203 }
1204
1205 let pointee_shape = match smart_ptr_def.pointee() {
1207 Some(shape) => shape,
1208 None => {
1209 return Err(ReflectError::OperationFailed {
1210 shape: frame.shape,
1211 operation: "Box must have a pointee shape",
1212 });
1213 }
1214 };
1215
1216 if matches!(frame.tracker, Tracker::Uninit) {
1218 frame.tracker = Tracker::SmartPointer {
1219 is_initialized: false,
1220 };
1221 }
1222
1223 let inner_layout = match pointee_shape.layout.sized_layout() {
1225 Ok(layout) => layout,
1226 Err(_) => {
1227 return Err(ReflectError::Unsized {
1228 shape: pointee_shape,
1229 });
1230 }
1231 };
1232 let inner_ptr: *mut u8 = unsafe { alloc::alloc::alloc(inner_layout) };
1233
1234 if inner_ptr.is_null() {
1235 return Err(ReflectError::OperationFailed {
1236 shape: frame.shape,
1237 operation: "failed to allocate memory for Box inner value",
1238 });
1239 }
1240
1241 self.frames.push(Frame::new(
1243 PtrUninit::new(inner_ptr),
1244 pointee_shape,
1245 FrameOwnership::Owned,
1246 ));
1247
1248 Ok(self)
1249 }
1250 _ => Err(ReflectError::OperationFailed {
1251 shape: frame.shape,
1252 operation: "push_smart_ptr can only be called on compatible types",
1253 }),
1254 }
1255 }
1256
1257 pub fn begin_list(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
1260 self.require_active()?;
1261 let frame = self.frames.last_mut().unwrap();
1262
1263 let list_def = match &frame.shape.def {
1265 Def::List(list_def) => list_def,
1266 _ => {
1267 return Err(ReflectError::OperationFailed {
1268 shape: frame.shape,
1269 operation: "begin_pushback can only be called on List types",
1270 });
1271 }
1272 };
1273
1274 let init_fn = match list_def.vtable.init_in_place_with_capacity {
1276 Some(f) => f,
1277 None => {
1278 return Err(ReflectError::OperationFailed {
1279 shape: frame.shape,
1280 operation: "list type does not support initialization with capacity",
1281 });
1282 }
1283 };
1284
1285 unsafe {
1287 init_fn(frame.data, 0);
1288 }
1289
1290 frame.tracker = Tracker::List {
1292 is_initialized: true,
1293 current_child: false,
1294 };
1295
1296 Ok(self)
1297 }
1298
1299 pub fn begin_map(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
1302 self.require_active()?;
1303 let frame = self.frames.last_mut().unwrap();
1304
1305 let map_def = match &frame.shape.def {
1307 Def::Map(map_def) => map_def,
1308 _ => {
1309 return Err(ReflectError::OperationFailed {
1310 shape: frame.shape,
1311 operation: "begin_map can only be called on Map types",
1312 });
1313 }
1314 };
1315
1316 let init_fn = map_def.vtable.init_in_place_with_capacity_fn;
1318
1319 unsafe {
1321 init_fn(frame.data, 0);
1322 }
1323
1324 frame.tracker = Tracker::Map {
1326 is_initialized: true,
1327 insert_state: MapInsertState::Idle,
1328 };
1329
1330 Ok(self)
1331 }
1332
1333 pub fn begin_key(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
1336 self.require_active()?;
1337 let frame = self.frames.last_mut().unwrap();
1338
1339 let map_def = match (&frame.shape.def, &mut frame.tracker) {
1341 (
1342 Def::Map(map_def),
1343 Tracker::Map {
1344 is_initialized: true,
1345 insert_state,
1346 },
1347 ) => {
1348 match insert_state {
1349 MapInsertState::Idle => {
1350 *insert_state = MapInsertState::PushingKey { key_ptr: None };
1352 }
1353 MapInsertState::PushingKey { key_ptr } => {
1354 if key_ptr.is_some() {
1355 return Err(ReflectError::OperationFailed {
1356 shape: frame.shape,
1357 operation: "already pushing a key, call end() first",
1358 });
1359 }
1360 }
1361 _ => {
1362 return Err(ReflectError::OperationFailed {
1363 shape: frame.shape,
1364 operation: "must complete current operation before begin_key()",
1365 });
1366 }
1367 }
1368 map_def
1369 }
1370 _ => {
1371 return Err(ReflectError::OperationFailed {
1372 shape: frame.shape,
1373 operation: "must call begin_map() before begin_key()",
1374 });
1375 }
1376 };
1377
1378 let key_shape = map_def.k();
1380
1381 let key_layout = match key_shape.layout.sized_layout() {
1383 Ok(layout) => layout,
1384 Err(_) => {
1385 return Err(ReflectError::Unsized { shape: key_shape });
1386 }
1387 };
1388 let key_ptr_raw: *mut u8 = unsafe { alloc::alloc::alloc(key_layout) };
1389
1390 if key_ptr_raw.is_null() {
1391 return Err(ReflectError::OperationFailed {
1392 shape: frame.shape,
1393 operation: "failed to allocate memory for map key",
1394 });
1395 }
1396
1397 match &mut frame.tracker {
1399 Tracker::Map {
1400 insert_state: MapInsertState::PushingKey { key_ptr: kp },
1401 ..
1402 } => {
1403 *kp = Some(PtrUninit::new(key_ptr_raw));
1404 }
1405 _ => unreachable!(),
1406 }
1407
1408 self.frames.push(Frame::new(
1410 PtrUninit::new(key_ptr_raw),
1411 key_shape,
1412 FrameOwnership::ManagedElsewhere, ));
1414
1415 Ok(self)
1416 }
1417
1418 pub fn begin_value(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
1421 self.require_active()?;
1422 let frame = self.frames.last_mut().unwrap();
1423
1424 let map_def = match (&frame.shape.def, &mut frame.tracker) {
1426 (
1427 Def::Map(map_def),
1428 Tracker::Map {
1429 insert_state: MapInsertState::PushingValue { value_ptr, .. },
1430 ..
1431 },
1432 ) => {
1433 if value_ptr.is_some() {
1434 return Err(ReflectError::OperationFailed {
1435 shape: frame.shape,
1436 operation: "already pushing a value, call pop() first",
1437 });
1438 }
1439 map_def
1440 }
1441 _ => {
1442 return Err(ReflectError::OperationFailed {
1443 shape: frame.shape,
1444 operation: "must complete key before push_value()",
1445 });
1446 }
1447 };
1448
1449 let value_shape = map_def.v();
1451
1452 let value_layout = match value_shape.layout.sized_layout() {
1454 Ok(layout) => layout,
1455 Err(_) => {
1456 return Err(ReflectError::Unsized { shape: value_shape });
1457 }
1458 };
1459 let value_ptr_raw: *mut u8 = unsafe { alloc::alloc::alloc(value_layout) };
1460
1461 if value_ptr_raw.is_null() {
1462 return Err(ReflectError::OperationFailed {
1463 shape: frame.shape,
1464 operation: "failed to allocate memory for map value",
1465 });
1466 }
1467
1468 match &mut frame.tracker {
1470 Tracker::Map {
1471 insert_state: MapInsertState::PushingValue { value_ptr: vp, .. },
1472 ..
1473 } => {
1474 *vp = Some(PtrUninit::new(value_ptr_raw));
1475 }
1476 _ => unreachable!(),
1477 }
1478
1479 self.frames.push(Frame::new(
1481 PtrUninit::new(value_ptr_raw),
1482 value_shape,
1483 FrameOwnership::ManagedElsewhere, ));
1485
1486 Ok(self)
1487 }
1488
1489 pub fn begin_list_item(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
1492 self.require_active()?;
1493 let frame = self.frames.last_mut().unwrap();
1494
1495 let list_def = match &frame.shape.def {
1497 Def::List(list_def) => list_def,
1498 _ => {
1499 return Err(ReflectError::OperationFailed {
1500 shape: frame.shape,
1501 operation: "push can only be called on List types",
1502 });
1503 }
1504 };
1505
1506 match &mut frame.tracker {
1508 Tracker::List {
1509 is_initialized: true,
1510 current_child,
1511 } => {
1512 if *current_child {
1513 return Err(ReflectError::OperationFailed {
1514 shape: frame.shape,
1515 operation: "already pushing an element, call pop() first",
1516 });
1517 }
1518 *current_child = true;
1519 }
1520 _ => {
1521 return Err(ReflectError::OperationFailed {
1522 shape: frame.shape,
1523 operation: "must call begin_pushback() before push()",
1524 });
1525 }
1526 }
1527
1528 let element_shape = list_def.t();
1530
1531 let element_layout = match element_shape.layout.sized_layout() {
1533 Ok(layout) => layout,
1534 Err(_) => {
1535 return Err(ReflectError::Unsized {
1536 shape: element_shape,
1537 });
1538 }
1539 };
1540 let element_ptr: *mut u8 = unsafe { alloc::alloc::alloc(element_layout) };
1541
1542 if element_ptr.is_null() {
1543 return Err(ReflectError::OperationFailed {
1544 shape: frame.shape,
1545 operation: "failed to allocate memory for list element",
1546 });
1547 }
1548
1549 self.frames.push(Frame::new(
1551 PtrUninit::new(element_ptr),
1552 element_shape,
1553 FrameOwnership::Owned,
1554 ));
1555
1556 Ok(self)
1557 }
1558
1559 pub fn end(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
1561 self.require_active()?;
1562 if self.frames.len() <= 1 {
1563 return Err(ReflectError::InvariantViolation {
1565 invariant: "Wip::end() called with only one frame on the stack",
1566 });
1567 }
1568
1569 {
1571 let frame = self.frames.last().unwrap();
1572 trace!(
1573 "end(): Checking full initialization for frame with shape {}",
1574 frame.shape
1575 );
1576 frame.require_full_initialization()?
1577 }
1578
1579 let popped_frame = self.frames.pop().unwrap();
1581 let _is_conversion = false;
1582 trace!(
1583 "end(): Popped frame with shape {}, is_conversion={}",
1584 popped_frame.shape, _is_conversion
1585 );
1586
1587 let parent_frame = self.frames.last_mut().unwrap();
1589
1590 let needs_conversion = matches!(parent_frame.tracker, Tracker::Uninit)
1595 && parent_frame.shape.inner.is_some()
1596 && parent_frame.shape.inner.unwrap()() == popped_frame.shape
1597 && (parent_frame.shape.vtable.try_from)().is_some();
1598
1599 if needs_conversion {
1600 trace!(
1601 "Detected implicit conversion needed from {} to {}",
1602 popped_frame.shape, parent_frame.shape
1603 );
1604 if let Some(try_from_fn) = (parent_frame.shape.vtable.try_from)() {
1606 let inner_ptr = unsafe { popped_frame.data.assume_init().as_const() };
1607 let inner_shape = popped_frame.shape;
1608
1609 trace!("Converting from {} to {}", inner_shape, parent_frame.shape);
1610 let result = unsafe { try_from_fn(inner_ptr, inner_shape, parent_frame.data) };
1611
1612 if let Err(e) = result {
1613 trace!("Conversion failed: {:?}", e);
1614
1615 if let FrameOwnership::Owned = popped_frame.ownership {
1617 if let Ok(layout) = popped_frame.shape.layout.sized_layout() {
1618 if layout.size() > 0 {
1619 trace!(
1620 "Deallocating conversion frame memory after failure: size={}, align={}",
1621 layout.size(),
1622 layout.align()
1623 );
1624 unsafe {
1625 alloc::alloc::dealloc(
1626 popped_frame.data.as_mut_byte_ptr(),
1627 layout,
1628 );
1629 }
1630 }
1631 }
1632 }
1633
1634 return Err(ReflectError::TryFromError {
1635 src_shape: inner_shape,
1636 dst_shape: parent_frame.shape,
1637 inner: e,
1638 });
1639 }
1640
1641 trace!("Conversion succeeded, marking parent as initialized");
1642 parent_frame.tracker = Tracker::Init;
1643
1644 if let FrameOwnership::Owned = popped_frame.ownership {
1646 if let Ok(layout) = popped_frame.shape.layout.sized_layout() {
1647 if layout.size() > 0 {
1648 trace!(
1649 "Deallocating conversion frame memory: size={}, align={}",
1650 layout.size(),
1651 layout.align()
1652 );
1653 unsafe {
1654 alloc::alloc::dealloc(popped_frame.data.as_mut_byte_ptr(), layout);
1655 }
1656 }
1657 }
1658 }
1659
1660 return Ok(self);
1661 }
1662 }
1663
1664 match &mut parent_frame.tracker {
1665 Tracker::Struct {
1666 iset,
1667 current_child,
1668 } => {
1669 if let Some(idx) = *current_child {
1670 iset.set(idx);
1671 *current_child = None;
1672 }
1673 }
1674 Tracker::Array {
1675 iset,
1676 current_child,
1677 } => {
1678 if let Some(idx) = *current_child {
1679 iset.set(idx);
1680 *current_child = None;
1681 }
1682 }
1683 Tracker::SmartPointer { is_initialized } => {
1684 if let Def::SmartPointer(smart_ptr_def) = parent_frame.shape.def {
1686 if let Some(new_into_fn) = smart_ptr_def.vtable.new_into_fn {
1687 let inner_ptr = PtrMut::new(popped_frame.data.as_mut_byte_ptr());
1689
1690 unsafe {
1692 new_into_fn(parent_frame.data, inner_ptr);
1693 }
1694
1695 if let FrameOwnership::Owned = popped_frame.ownership {
1697 if let Ok(layout) = popped_frame.shape.layout.sized_layout() {
1698 if layout.size() > 0 {
1699 unsafe {
1700 alloc::alloc::dealloc(
1701 popped_frame.data.as_mut_byte_ptr(),
1702 layout,
1703 );
1704 }
1705 }
1706 }
1707 }
1708
1709 *is_initialized = true;
1710 } else {
1711 return Err(ReflectError::OperationFailed {
1712 shape: parent_frame.shape,
1713 operation: "SmartPointer missing new_into_fn",
1714 });
1715 }
1716 }
1717 }
1718 Tracker::Enum {
1719 data,
1720 current_child,
1721 ..
1722 } => {
1723 if let Some(idx) = *current_child {
1724 data.set(idx);
1725 *current_child = None;
1726 }
1727 }
1728 Tracker::List {
1729 is_initialized: true,
1730 current_child,
1731 } => {
1732 if *current_child {
1733 if let Def::List(list_def) = parent_frame.shape.def {
1735 if let Some(push_fn) = list_def.vtable.push {
1736 let element_ptr = PtrMut::new(popped_frame.data.as_mut_byte_ptr());
1738
1739 unsafe {
1741 push_fn(
1742 PtrMut::new(parent_frame.data.as_mut_byte_ptr()),
1743 element_ptr,
1744 );
1745 }
1746
1747 if let FrameOwnership::Owned = popped_frame.ownership {
1749 if let Ok(layout) = popped_frame.shape.layout.sized_layout() {
1750 if layout.size() > 0 {
1751 unsafe {
1752 alloc::alloc::dealloc(
1753 popped_frame.data.as_mut_byte_ptr(),
1754 layout,
1755 );
1756 }
1757 }
1758 }
1759 }
1760
1761 *current_child = false;
1762 } else {
1763 return Err(ReflectError::OperationFailed {
1764 shape: parent_frame.shape,
1765 operation: "List missing push function",
1766 });
1767 }
1768 }
1769 }
1770 }
1771 Tracker::Map {
1772 is_initialized: true,
1773 insert_state,
1774 } => {
1775 match insert_state {
1776 MapInsertState::PushingKey { key_ptr } => {
1777 if let Some(key_ptr) = key_ptr {
1779 *insert_state = MapInsertState::PushingValue {
1781 key_ptr: *key_ptr,
1782 value_ptr: None,
1783 };
1784 }
1785 }
1786 MapInsertState::PushingValue { key_ptr, value_ptr } => {
1787 if let (Some(value_ptr), Def::Map(map_def)) =
1789 (value_ptr, parent_frame.shape.def)
1790 {
1791 let insert_fn = map_def.vtable.insert_fn;
1792
1793 unsafe {
1795 insert_fn(
1796 PtrMut::new(parent_frame.data.as_mut_byte_ptr()),
1797 PtrMut::new(key_ptr.as_mut_byte_ptr()),
1798 PtrMut::new(value_ptr.as_mut_byte_ptr()),
1799 );
1800 }
1801
1802 if let Ok(key_shape) = map_def.k().layout.sized_layout() {
1808 if key_shape.size() > 0 {
1809 unsafe {
1810 alloc::alloc::dealloc(key_ptr.as_mut_byte_ptr(), key_shape);
1811 }
1812 }
1813 }
1814 if let Ok(value_shape) = map_def.v().layout.sized_layout() {
1815 if value_shape.size() > 0 {
1816 unsafe {
1817 alloc::alloc::dealloc(
1818 value_ptr.as_mut_byte_ptr(),
1819 value_shape,
1820 );
1821 }
1822 }
1823 }
1824
1825 *insert_state = MapInsertState::Idle;
1827 }
1828 }
1829 MapInsertState::Idle => {
1830 }
1832 }
1833 }
1834 Tracker::Option { building_inner } => {
1835 if *building_inner {
1837 if let Def::Option(option_def) = parent_frame.shape.def {
1838 let init_some_fn = option_def.vtable.init_some_fn;
1840
1841 let inner_value_ptr = unsafe { popped_frame.data.assume_init().as_const() };
1843
1844 unsafe {
1846 init_some_fn(parent_frame.data, inner_value_ptr);
1847 }
1848
1849 if let FrameOwnership::Owned = popped_frame.ownership {
1851 if let Ok(layout) = popped_frame.shape.layout.sized_layout() {
1852 if layout.size() > 0 {
1853 unsafe {
1854 alloc::alloc::dealloc(
1855 popped_frame.data.as_mut_byte_ptr(),
1856 layout,
1857 );
1858 }
1859 }
1860 }
1861 }
1862
1863 *building_inner = false;
1865 } else {
1866 return Err(ReflectError::OperationFailed {
1867 shape: parent_frame.shape,
1868 operation: "Option frame without Option definition",
1869 });
1870 }
1871 }
1872 }
1873 _ => {}
1874 }
1875
1876 Ok(self)
1877 }
1878
1879 pub fn build(&mut self) -> Result<HeapValue<'facet, 'shape>, ReflectError<'shape>> {
1881 self.require_active()?;
1882 if self.frames.len() != 1 {
1883 self.state = PartialState::BuildFailed;
1884 return Err(ReflectError::InvariantViolation {
1885 invariant: "Wip::build() expects a single frame โ pop until that's the case",
1886 });
1887 }
1888
1889 let frame = self.frames.pop().unwrap();
1890
1891 if let Err(e) = frame.require_full_initialization() {
1893 self.frames.push(frame);
1895 self.state = PartialState::BuildFailed;
1896 return Err(e);
1897 }
1898
1899 if let Some(invariants_fn) = (frame.shape.vtable.invariants)() {
1901 let value_ptr = unsafe { frame.data.assume_init().as_const() };
1903 let invariants_ok = unsafe { invariants_fn(value_ptr) };
1904
1905 if !invariants_ok {
1906 self.frames.push(frame);
1908 self.state = PartialState::BuildFailed;
1909 return Err(ReflectError::InvariantViolation {
1910 invariant: "Type invariants check failed",
1911 });
1912 }
1913 }
1914
1915 self.state = PartialState::Built;
1917
1918 match frame
1919 .shape
1920 .layout
1921 .sized_layout()
1922 .map_err(|_| ReflectError::Unsized { shape: frame.shape })
1923 {
1924 Ok(layout) => Ok(HeapValue {
1925 guard: Some(Guard {
1926 ptr: frame.data.as_mut_byte_ptr(),
1927 layout,
1928 }),
1929 shape: frame.shape,
1930 phantom: PhantomData,
1931 }),
1932 Err(e) => {
1933 self.frames.push(frame);
1935 self.state = PartialState::BuildFailed;
1936 Err(e)
1937 }
1938 }
1939 }
1940
1941 pub fn path(&self) -> String {
1944 let mut out = String::new();
1945
1946 let mut path_components = Vec::new();
1947 for (i, frame) in self.frames.iter().enumerate() {
1950 match frame.shape.ty {
1951 Type::User(user_type) => match user_type {
1952 UserType::Struct(struct_type) => {
1953 let mut field_str = None;
1955 if let Tracker::Struct {
1956 current_child: Some(idx),
1957 ..
1958 } = &frame.tracker
1959 {
1960 if let Some(field) = struct_type.fields.get(*idx) {
1961 field_str = Some(field.name);
1962 }
1963 }
1964 if i == 0 {
1965 path_components.push(format!("{}", frame.shape));
1967 }
1968 if let Some(field_name) = field_str {
1969 path_components.push(format!(".{}", field_name));
1970 }
1971 }
1972 UserType::Enum(_enum_type) => {
1973 if let Tracker::Enum {
1975 variant,
1976 current_child,
1977 ..
1978 } = &frame.tracker
1979 {
1980 if i == 0 {
1981 path_components.push(format!("{}", frame.shape));
1983 }
1984 path_components.push(format!("::{}", variant.name));
1985 if let Some(idx) = *current_child {
1986 if let Some(field) = variant.data.fields.get(idx) {
1987 path_components.push(format!(".{}", field.name));
1988 }
1989 }
1990 } else if i == 0 {
1991 path_components.push(format!("{}", frame.shape));
1993 }
1994 }
1995 UserType::Union(_union_type) => {
1996 path_components.push(format!("{}", frame.shape));
1997 }
1998 UserType::Opaque => {
1999 path_components.push("<opaque>".to_string());
2000 }
2001 },
2002 Type::Sequence(seq_type) => match seq_type {
2003 facet_core::SequenceType::Array(_array_def) => {
2004 if let Tracker::Array {
2006 current_child: Some(idx),
2007 ..
2008 } = &frame.tracker
2009 {
2010 path_components.push(format!("[{}]", idx));
2011 }
2012 }
2013 _ => {
2015 path_components.push("[]".to_string());
2017 }
2018 },
2019 Type::Pointer(_) => {
2020 path_components.push("*".to_string());
2022 }
2023 _ => {
2024 }
2026 }
2027 }
2028 for component in path_components {
2030 out.push_str(&component);
2031 }
2032 out
2033 }
2034
2035 pub fn shape(&self) -> &'shape Shape<'shape> {
2037 self.frames
2038 .last()
2039 .expect("Partial always has at least one frame")
2040 .shape
2041 }
2042
2043 pub fn innermost_shape(&self) -> &'shape Shape<'shape> {
2045 self.shape()
2046 }
2047
2048 pub fn is_field_set(&self, index: usize) -> Result<bool, ReflectError<'shape>> {
2050 let frame = self.frames.last().ok_or(ReflectError::NoActiveFrame)?;
2051
2052 match &frame.tracker {
2053 Tracker::Uninit => Ok(false),
2054 Tracker::Init => Ok(true),
2055 Tracker::Struct { iset, .. } => Ok(iset.get(index)),
2056 Tracker::Enum { data, .. } => {
2057 if data.get(index) {
2059 return Ok(true);
2060 }
2061
2062 if let Tracker::Enum { variant, .. } = &frame.tracker {
2064 if let Some(field) = variant.data.fields.get(index) {
2065 if let Type::User(UserType::Struct(field_struct)) = field.shape.ty {
2066 if field_struct.fields.is_empty() {
2067 return Ok(true);
2068 }
2069 }
2070 }
2071 }
2072
2073 Ok(false)
2074 }
2075 Tracker::Option { building_inner } => {
2076 if index == 0 {
2078 Ok(!building_inner)
2079 } else {
2080 Err(ReflectError::InvalidOperation {
2081 operation: "is_field_set",
2082 reason: "Option only has one field (index 0)",
2083 })
2084 }
2085 }
2086 _ => Err(ReflectError::InvalidOperation {
2087 operation: "is_field_set",
2088 reason: "Current frame is not a struct, enum variant, or option",
2089 }),
2090 }
2091 }
2092
2093 pub fn field_index(&self, field_name: &str) -> Option<usize> {
2095 let frame = self.frames.last()?;
2096
2097 match frame.shape.ty {
2098 Type::User(UserType::Struct(struct_def)) => {
2099 struct_def.fields.iter().position(|f| f.name == field_name)
2100 }
2101 Type::User(UserType::Enum(_)) => {
2102 if let Tracker::Enum { variant, .. } = &frame.tracker {
2104 variant
2105 .data
2106 .fields
2107 .iter()
2108 .position(|f| f.name == field_name)
2109 } else {
2110 None
2111 }
2112 }
2113 _ => None,
2114 }
2115 }
2116
2117 pub fn selected_variant(&self) -> Option<Variant<'shape>> {
2119 let frame = self.frames.last()?;
2120
2121 match &frame.tracker {
2122 Tracker::Enum { variant, .. } => Some(*variant),
2123 _ => None,
2124 }
2125 }
2126
2127 pub fn find_variant(&self, variant_name: &str) -> Option<(usize, &'shape Variant<'shape>)> {
2129 let frame = self.frames.last()?;
2130
2131 if let Type::User(UserType::Enum(enum_def)) = frame.shape.ty {
2132 enum_def
2133 .variants
2134 .iter()
2135 .enumerate()
2136 .find(|(_, v)| v.name == variant_name)
2137 } else {
2138 None
2139 }
2140 }
2141
2142 pub fn push_some(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2144 self.require_active()?;
2145 let frame = self.frames.last_mut().unwrap();
2146
2147 let option_def = match frame.shape.def {
2149 Def::Option(def) => def,
2150 _ => {
2151 return Err(ReflectError::WasNotA {
2152 expected: "Option",
2153 actual: frame.shape,
2154 });
2155 }
2156 };
2157
2158 if matches!(frame.tracker, Tracker::Uninit) {
2160 frame.tracker = Tracker::Option {
2161 building_inner: true,
2162 };
2163 }
2164
2165 let inner_shape = option_def.t;
2167
2168 let inner_layout = inner_shape
2170 .layout
2171 .sized_layout()
2172 .map_err(|_| ReflectError::Unsized { shape: inner_shape })?;
2173
2174 let inner_data = if inner_layout.size() == 0 {
2175 PtrUninit::new(core::ptr::NonNull::<u8>::dangling().as_ptr())
2177 } else {
2178 let ptr = unsafe { alloc::alloc::alloc(inner_layout) };
2180 if ptr.is_null() {
2181 alloc::alloc::handle_alloc_error(inner_layout);
2182 }
2183 PtrUninit::new(ptr)
2184 };
2185
2186 let inner_frame = Frame::new(inner_data, inner_shape, FrameOwnership::Owned);
2188 self.frames.push(inner_frame);
2189
2190 Ok(self)
2191 }
2192
2193 pub fn push_pointee(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2195 self.begin_smart_ptr()
2196 }
2197
2198 pub fn push_inner(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2200 self.require_active()?;
2201
2202 let (inner_shape, has_try_from, parent_shape) = {
2204 let frame = self.frames.last().unwrap();
2205 if let Some(inner_fn) = frame.shape.inner {
2206 let inner_shape = inner_fn();
2207 let has_try_from = (frame.shape.vtable.try_from)().is_some();
2208 (Some(inner_shape), has_try_from, frame.shape)
2209 } else {
2210 (None, false, frame.shape)
2211 }
2212 };
2213
2214 if let Some(inner_shape) = inner_shape {
2215 if has_try_from {
2216 let inner_layout = inner_shape
2223 .layout
2224 .sized_layout()
2225 .map_err(|_| ReflectError::Unsized { shape: inner_shape })?;
2226
2227 let inner_data = if inner_layout.size() == 0 {
2228 PtrUninit::new(core::ptr::NonNull::<u8>::dangling().as_ptr())
2230 } else {
2231 let ptr = unsafe { alloc::alloc::alloc(inner_layout) };
2233 if ptr.is_null() {
2234 alloc::alloc::handle_alloc_error(inner_layout);
2235 }
2236 PtrUninit::new(ptr)
2237 };
2238
2239 trace!(
2243 "push_inner: Creating frame for inner type {} (parent is {})",
2244 inner_shape, parent_shape
2245 );
2246 self.frames
2247 .push(Frame::new(inner_data, inner_shape, FrameOwnership::Owned));
2248
2249 Ok(self)
2250 } else {
2251 trace!(
2254 "push_inner: No try_from for {}, using field navigation",
2255 parent_shape
2256 );
2257 self.begin_nth_field(0)
2258 }
2259 } else {
2260 Err(ReflectError::OperationFailed {
2261 shape: parent_shape,
2262 operation: "type does not have an inner value",
2263 })
2264 }
2265 }
2266
2267 pub fn push_map_key(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2269 self.begin_key()
2270 }
2271
2272 pub fn push_map_value(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2274 self.begin_value()
2275 }
2276
2277 pub fn set_from_peek(
2279 &mut self,
2280 peek: &Peek<'_, '_, 'shape>,
2281 ) -> Result<&mut Self, ReflectError<'shape>> {
2282 self.require_active()?;
2283
2284 let src_ptr = peek.data();
2286 let src_shape = peek.shape();
2287
2288 unsafe { self.set_shape(src_ptr, src_shape) }
2291 }
2292
2293 pub fn set_field_from_default(
2296 &mut self,
2297 field_data: PtrConst<'_>,
2298 field_shape: &'shape Shape<'shape>,
2299 ) -> Result<&mut Self, ReflectError<'shape>> {
2300 self.require_active()?;
2301
2302 unsafe { self.set_shape(field_data, field_shape) }
2305 }
2306
2307 pub fn fill_unset_fields_from_default(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2310 self.require_active()?;
2311
2312 let frame = self.frames.last().unwrap();
2313 let shape = frame.shape;
2314
2315 if !shape.has_default_attr() {
2317 return Ok(self);
2318 }
2319
2320 let struct_def = match shape.ty {
2322 Type::User(UserType::Struct(sd)) => sd,
2323 _ => return Ok(self), };
2325
2326 let mut has_unset = false;
2328 for index in 0..struct_def.fields.len() {
2329 if !self.is_field_set(index)? {
2330 has_unset = true;
2331 break;
2332 }
2333 }
2334
2335 if !has_unset {
2336 return Ok(self); }
2338
2339 let default_val = Partial::alloc_shape(shape)?.set_default()?.build()?;
2341 let peek = default_val.peek();
2342
2343 let struct_peek = peek
2345 .into_struct()
2346 .map_err(|_| ReflectError::OperationFailed {
2347 shape,
2348 operation: "expected struct peek for default value",
2349 })?;
2350
2351 for (index, _field) in struct_def.fields.iter().enumerate() {
2353 if !self.is_field_set(index)? {
2354 self.begin_nth_field(index)?;
2355
2356 let def_field =
2358 struct_peek
2359 .field(index)
2360 .map_err(|_| ReflectError::OperationFailed {
2361 shape,
2362 operation: "failed to get field from default struct",
2363 })?;
2364
2365 self.set_from_peek(&def_field)?;
2366 self.end()?;
2367 }
2368 }
2369
2370 Ok(self)
2371 }
2372
2373 pub fn set_nth_element<U>(
2375 &mut self,
2376 idx: usize,
2377 value: U,
2378 ) -> Result<&mut Self, ReflectError<'shape>>
2379 where
2380 U: Facet<'facet>,
2381 {
2382 self.begin_nth_element(idx)?.set(value)?.end()
2383 }
2384
2385 pub fn set_nth_field<U>(
2387 &mut self,
2388 idx: usize,
2389 value: U,
2390 ) -> Result<&mut Self, ReflectError<'shape>>
2391 where
2392 U: Facet<'facet>,
2393 {
2394 self.begin_nth_field(idx)?.set(value)?.end()
2395 }
2396
2397 pub fn set_field<U>(
2399 &mut self,
2400 field_name: &str,
2401 value: U,
2402 ) -> Result<&mut Self, ReflectError<'shape>>
2403 where
2404 U: Facet<'facet>,
2405 {
2406 self.begin_field(field_name)?.set(value)?.end()
2407 }
2408
2409 pub fn set_nth_enum_field<U>(
2411 &mut self,
2412 idx: usize,
2413 value: U,
2414 ) -> Result<&mut Self, ReflectError<'shape>>
2415 where
2416 U: Facet<'facet>,
2417 {
2418 self.begin_nth_enum_field(idx)?.set(value)?.end()
2419 }
2420
2421 pub fn set_key<U>(&mut self, value: U) -> Result<&mut Self, ReflectError<'shape>>
2423 where
2424 U: Facet<'facet>,
2425 {
2426 self.begin_key()?.set(value)?.end()
2427 }
2428
2429 pub fn set_value<U>(&mut self, value: U) -> Result<&mut Self, ReflectError<'shape>>
2431 where
2432 U: Facet<'facet>,
2433 {
2434 self.begin_value()?.set(value)?.end()
2435 }
2436
2437 pub fn push<U>(&mut self, value: U) -> Result<&mut Self, ReflectError<'shape>>
2439 where
2440 U: Facet<'facet>,
2441 {
2442 self.begin_list_item()?.set(value)?.end()
2443 }
2444}
2445
2446pub struct TypedPartial<'facet, 'shape, T> {
2449 inner: Partial<'facet, 'shape>,
2450 phantom: PhantomData<T>,
2451}
2452
2453impl<'facet, 'shape, T> TypedPartial<'facet, 'shape, T> {
2454 pub fn inner_mut(&mut self) -> &mut Partial<'facet, 'shape> {
2456 &mut self.inner
2457 }
2458
2459 pub fn build(&mut self) -> Result<Box<T>, ReflectError<'shape>>
2461 where
2462 T: Facet<'facet>,
2463 'facet: 'shape,
2464 {
2465 trace!(
2466 "TypedPartial::build: Building value for type {}, inner shape: {}",
2467 T::SHAPE,
2468 self.inner.shape()
2469 );
2470 let heap_value = self.inner.build()?;
2471 trace!(
2472 "TypedPartial::build: Built heap value with shape: {}",
2473 heap_value.shape()
2474 );
2475 let result = unsafe { heap_value.into_box_unchecked::<T>() };
2477 trace!("TypedPartial::build: Successfully converted to Box<T>");
2478 Ok(result)
2479 }
2480
2481 pub fn set<U>(&mut self, value: U) -> Result<&mut Self, ReflectError<'shape>>
2483 where
2484 U: Facet<'facet>,
2485 {
2486 self.inner.set(value)?;
2487 Ok(self)
2488 }
2489
2490 pub fn set_shape(
2492 &mut self,
2493 src_value: PtrConst<'_>,
2494 src_shape: &'shape Shape<'shape>,
2495 ) -> Result<&mut Self, ReflectError<'shape>> {
2496 unsafe { self.inner.set_shape(src_value, src_shape)? };
2497 Ok(self)
2498 }
2499
2500 pub fn begin_field(&mut self, field_name: &str) -> Result<&mut Self, ReflectError<'shape>> {
2502 self.inner.begin_field(field_name)?;
2503 Ok(self)
2504 }
2505
2506 pub fn begin_nth_field(&mut self, idx: usize) -> Result<&mut Self, ReflectError<'shape>> {
2508 self.inner.begin_nth_field(idx)?;
2509 Ok(self)
2510 }
2511
2512 pub fn begin_nth_element(&mut self, idx: usize) -> Result<&mut Self, ReflectError<'shape>> {
2514 self.inner.begin_nth_element(idx)?;
2515 Ok(self)
2516 }
2517
2518 pub fn begin_smart_ptr(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2520 self.inner.begin_smart_ptr()?;
2521 Ok(self)
2522 }
2523
2524 pub fn end(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2526 self.inner.end()?;
2527 Ok(self)
2528 }
2529
2530 pub fn set_default(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2532 self.inner.set_default()?;
2533 Ok(self)
2534 }
2535
2536 pub fn set_from_function<F>(&mut self, f: F) -> Result<&mut Self, ReflectError<'shape>>
2538 where
2539 F: FnOnce(PtrUninit<'_>) -> Result<(), ReflectError<'shape>>,
2540 {
2541 self.inner.set_from_function(f)?;
2542 Ok(self)
2543 }
2544
2545 pub fn parse_from_str(&mut self, s: &str) -> Result<&mut Self, ReflectError<'shape>> {
2547 self.inner.parse_from_str(s)?;
2548 Ok(self)
2549 }
2550
2551 pub fn select_variant(&mut self, discriminant: i64) -> Result<&mut Self, ReflectError<'shape>> {
2553 self.inner.select_variant(discriminant)?;
2554 Ok(self)
2555 }
2556
2557 pub fn select_variant_named(
2559 &mut self,
2560 variant_name: &str,
2561 ) -> Result<&mut Self, ReflectError<'shape>> {
2562 self.inner.select_variant_named(variant_name)?;
2563 Ok(self)
2564 }
2565
2566 pub fn select_nth_variant(&mut self, index: usize) -> Result<&mut Self, ReflectError<'shape>> {
2568 self.inner.select_nth_variant(index)?;
2569 Ok(self)
2570 }
2571
2572 pub fn begin_nth_enum_field(&mut self, idx: usize) -> Result<&mut Self, ReflectError<'shape>> {
2574 self.inner.begin_nth_enum_field(idx)?;
2575 Ok(self)
2576 }
2577
2578 pub fn begin_list(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2580 self.inner.begin_list()?;
2581 Ok(self)
2582 }
2583
2584 pub fn begin_list_item(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2586 self.inner.begin_list_item()?;
2587 Ok(self)
2588 }
2589
2590 pub fn begin_map(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2592 self.inner.begin_map()?;
2593 Ok(self)
2594 }
2595
2596 pub fn begin_key(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2598 self.inner.begin_key()?;
2599 Ok(self)
2600 }
2601
2602 pub fn begin_value(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2604 self.inner.begin_value()?;
2605 Ok(self)
2606 }
2607
2608 pub fn path(&self) -> String {
2611 self.inner.path()
2612 }
2613
2614 pub fn shape(&self) -> &'shape Shape<'shape> {
2616 self.inner.shape()
2617 }
2618
2619 pub fn set_nth_element<U>(
2621 &mut self,
2622 idx: usize,
2623 value: U,
2624 ) -> Result<&mut Self, ReflectError<'shape>>
2625 where
2626 U: Facet<'facet>,
2627 {
2628 self.inner.set_nth_element(idx, value)?;
2629 Ok(self)
2630 }
2631
2632 pub fn set_nth_field<U>(
2634 &mut self,
2635 idx: usize,
2636 value: U,
2637 ) -> Result<&mut Self, ReflectError<'shape>>
2638 where
2639 U: Facet<'facet>,
2640 {
2641 self.inner.set_nth_field(idx, value)?;
2642 Ok(self)
2643 }
2644
2645 pub fn set_field<U>(
2647 &mut self,
2648 field_name: &str,
2649 value: U,
2650 ) -> Result<&mut Self, ReflectError<'shape>>
2651 where
2652 U: Facet<'facet>,
2653 {
2654 self.inner.set_field(field_name, value)?;
2655 Ok(self)
2656 }
2657
2658 pub fn set_nth_enum_field<U>(
2660 &mut self,
2661 idx: usize,
2662 value: U,
2663 ) -> Result<&mut Self, ReflectError<'shape>>
2664 where
2665 U: Facet<'facet>,
2666 {
2667 self.inner.set_nth_enum_field(idx, value)?;
2668 Ok(self)
2669 }
2670
2671 pub fn set_key<U>(&mut self, value: U) -> Result<&mut Self, ReflectError<'shape>>
2673 where
2674 U: Facet<'facet>,
2675 {
2676 self.inner.set_key(value)?;
2677 Ok(self)
2678 }
2679
2680 pub fn set_value<U>(&mut self, value: U) -> Result<&mut Self, ReflectError<'shape>>
2682 where
2683 U: Facet<'facet>,
2684 {
2685 self.inner.set_value(value)?;
2686 Ok(self)
2687 }
2688
2689 pub fn push<U>(&mut self, value: U) -> Result<&mut Self, ReflectError<'shape>>
2691 where
2692 U: Facet<'facet>,
2693 {
2694 self.inner.push(value)?;
2695 Ok(self)
2696 }
2697
2698 pub fn push_some(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2700 self.inner.push_some()?;
2701 Ok(self)
2702 }
2703
2704 pub fn push_pointee(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2706 self.inner.push_pointee()?;
2707 Ok(self)
2708 }
2709
2710 pub fn push_inner(&mut self) -> Result<&mut Self, ReflectError<'shape>> {
2712 self.inner.push_inner()?;
2713 Ok(self)
2714 }
2715}
2716
2717impl<'facet, 'shape, T> core::fmt::Debug for TypedPartial<'facet, 'shape, T> {
2718 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2719 f.debug_struct("TypedWip")
2720 .field("shape", &self.inner.frames.last().map(|frame| frame.shape))
2721 .finish()
2722 }
2723}
2724
2725impl<'facet, 'shape> Drop for Partial<'facet, 'shape> {
2726 fn drop(&mut self) {
2727 trace!("๐งน Wip is being dropped");
2728
2729 while let Some(frame) = self.frames.pop() {
2731 match &frame.tracker {
2732 Tracker::Uninit => {
2733 }
2735 Tracker::Init => {
2736 if let Some(drop_fn) = (frame.shape.vtable.drop_in_place)() {
2738 unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };
2739 }
2740 }
2741 Tracker::Array { iset, .. } => {
2742 if let Type::Sequence(facet_core::SequenceType::Array(array_def)) =
2744 frame.shape.ty
2745 {
2746 let element_layout = array_def.t.layout.sized_layout().ok();
2747 if let Some(layout) = element_layout {
2748 for idx in 0..array_def.n {
2749 if iset.get(idx) {
2750 let offset = layout.size() * idx;
2751 let element_ptr = unsafe { frame.data.field_init_at(offset) };
2752 if let Some(drop_fn) = (array_def.t.vtable.drop_in_place)() {
2753 unsafe { drop_fn(element_ptr) };
2754 }
2755 }
2756 }
2757 }
2758 }
2759 }
2760 Tracker::Struct { iset, .. } => {
2761 if let Type::User(UserType::Struct(struct_type)) = frame.shape.ty {
2763 for (idx, field) in struct_type.fields.iter().enumerate() {
2764 if iset.get(idx) {
2765 let field_ptr = unsafe { frame.data.field_init_at(field.offset) };
2767 if let Some(drop_fn) = (field.shape.vtable.drop_in_place)() {
2768 unsafe { drop_fn(field_ptr) };
2769 }
2770 }
2771 }
2772 }
2773 }
2774 Tracker::Enum { variant, data, .. } => {
2775 for (idx, field) in variant.data.fields.iter().enumerate() {
2777 if data.get(idx) {
2778 let field_ptr =
2780 unsafe { frame.data.as_mut_byte_ptr().add(field.offset) };
2781 if let Some(drop_fn) = (field.shape.vtable.drop_in_place)() {
2782 unsafe { drop_fn(PtrMut::new(field_ptr)) };
2783 }
2784 }
2785 }
2786 }
2787 Tracker::SmartPointer { is_initialized } => {
2788 if *is_initialized {
2790 if let Some(drop_fn) = (frame.shape.vtable.drop_in_place)() {
2791 unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };
2792 }
2793 }
2794 }
2797 Tracker::List { is_initialized, .. } => {
2798 if *is_initialized {
2800 if let Some(drop_fn) = (frame.shape.vtable.drop_in_place)() {
2801 unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };
2802 }
2803 }
2804 }
2805 Tracker::Map {
2806 is_initialized,
2807 insert_state,
2808 } => {
2809 if *is_initialized {
2811 if let Some(drop_fn) = (frame.shape.vtable.drop_in_place)() {
2812 unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };
2813 }
2814 }
2815
2816 match insert_state {
2818 MapInsertState::PushingKey { key_ptr } => {
2819 if let Some(key_ptr) = key_ptr {
2820 if let Def::Map(map_def) = frame.shape.def {
2822 if let Ok(key_shape) = map_def.k().layout.sized_layout() {
2823 if key_shape.size() > 0 {
2824 unsafe {
2825 alloc::alloc::dealloc(
2826 key_ptr.as_mut_byte_ptr(),
2827 key_shape,
2828 )
2829 };
2830 }
2831 }
2832 }
2833 }
2834 }
2835 MapInsertState::PushingValue { key_ptr, value_ptr } => {
2836 if let Def::Map(map_def) = frame.shape.def {
2838 if let Some(drop_fn) = (map_def.k().vtable.drop_in_place)() {
2840 unsafe { drop_fn(PtrMut::new(key_ptr.as_mut_byte_ptr())) };
2841 }
2842 if let Ok(key_shape) = map_def.k().layout.sized_layout() {
2843 if key_shape.size() > 0 {
2844 unsafe {
2845 alloc::alloc::dealloc(
2846 key_ptr.as_mut_byte_ptr(),
2847 key_shape,
2848 )
2849 };
2850 }
2851 }
2852
2853 if let Some(value_ptr) = value_ptr {
2855 if let Ok(value_shape) = map_def.v().layout.sized_layout() {
2856 if value_shape.size() > 0 {
2857 unsafe {
2858 alloc::alloc::dealloc(
2859 value_ptr.as_mut_byte_ptr(),
2860 value_shape,
2861 )
2862 };
2863 }
2864 }
2865 }
2866 }
2867 }
2868 MapInsertState::Idle => {}
2869 }
2870 }
2871 Tracker::Option { building_inner } => {
2872 if !building_inner {
2876 if let Some(drop_fn) = (frame.shape.vtable.drop_in_place)() {
2878 unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };
2879 }
2880 }
2881 }
2882 }
2883
2884 if let FrameOwnership::Owned = frame.ownership {
2886 if let Ok(layout) = frame.shape.layout.sized_layout() {
2887 if layout.size() > 0 {
2888 unsafe { alloc::alloc::dealloc(frame.data.as_mut_byte_ptr(), layout) };
2889 }
2890 }
2891 }
2892 }
2893 }
2894}