facet_core/impls_alloc/
boxed.rs

1use crate::{
2    Def, Facet, KnownSmartPointer, PtrConst, PtrMut, PtrUninit, Shape, SmartPointerDef,
3    SmartPointerFlags, SmartPointerVTable, TryBorrowInnerError, TryFromError, TryIntoInnerError,
4    Type, UserType, ValueVTable, value_vtable,
5};
6
7unsafe impl<'a, T: Facet<'a>> Facet<'a> for alloc::boxed::Box<T> {
8    const VTABLE: &'static ValueVTable = &const {
9        // Define the functions for transparent conversion between Box<T> and T
10        unsafe fn try_from<'a, 'shape, 'src, 'dst, T: Facet<'a>>(
11            src_ptr: PtrConst<'src>,
12            src_shape: &'shape Shape<'shape>,
13            dst: PtrUninit<'dst>,
14        ) -> Result<PtrMut<'dst>, TryFromError<'shape>> {
15            if src_shape.id != T::SHAPE.id {
16                return Err(TryFromError::UnsupportedSourceShape {
17                    src_shape,
18                    expected: &[T::SHAPE],
19                });
20            }
21            let t = unsafe { src_ptr.read::<T>() };
22            let boxed = alloc::boxed::Box::new(t);
23            Ok(unsafe { dst.put(boxed) })
24        }
25
26        unsafe fn try_into_inner<'a, 'src, 'dst, T: Facet<'a>>(
27            src_ptr: PtrMut<'src>,
28            dst: PtrUninit<'dst>,
29        ) -> Result<PtrMut<'dst>, TryIntoInnerError> {
30            let boxed = unsafe { src_ptr.read::<alloc::boxed::Box<T>>() };
31            Ok(unsafe { dst.put(*boxed) })
32        }
33
34        unsafe fn try_borrow_inner<'a, 'src, T: Facet<'a>>(
35            src_ptr: PtrConst<'src>,
36        ) -> Result<PtrConst<'src>, TryBorrowInnerError> {
37            let boxed = unsafe { src_ptr.get::<alloc::boxed::Box<T>>() };
38            Ok(PtrConst::new(&**boxed))
39        }
40
41        let mut vtable = value_vtable!(alloc::boxed::Box<T>, |f, opts| {
42            write!(f, "{}", Self::SHAPE.type_identifier)?;
43            if let Some(opts) = opts.for_children() {
44                write!(f, "<")?;
45                (T::SHAPE.vtable.type_name)(f, opts)?;
46                write!(f, ">")?;
47            } else {
48                write!(f, "<…>")?;
49            }
50            Ok(())
51        });
52        vtable.try_from = || Some(try_from::<T>);
53        vtable.try_into_inner = || Some(try_into_inner::<T>);
54        vtable.try_borrow_inner = || Some(try_borrow_inner::<T>);
55        vtable
56    };
57
58    const SHAPE: &'static crate::Shape<'static> = &const {
59        // Function to return inner type's shape
60        fn inner_shape<'a, T: Facet<'a>>() -> &'static Shape<'static> {
61            T::SHAPE
62        }
63
64        crate::Shape::builder_for_sized::<Self>()
65            .type_identifier("Box")
66            .type_params(&[crate::TypeParam {
67                name: "T",
68                shape: || T::SHAPE,
69            }])
70            .ty(Type::User(UserType::Opaque))
71            .def(Def::SmartPointer(
72                SmartPointerDef::builder()
73                    .pointee(|| T::SHAPE)
74                    .flags(SmartPointerFlags::EMPTY)
75                    .known(KnownSmartPointer::Box)
76                    .vtable(
77                        &const {
78                            SmartPointerVTable::builder()
79                                .borrow_fn(|this| {
80                                    let ptr = unsafe {
81                                        &raw const **this.as_ptr::<alloc::boxed::Box<T>>()
82                                    };
83                                    PtrConst::new(ptr)
84                                })
85                                .new_into_fn(|this, ptr| {
86                                    let t = unsafe { ptr.read::<T>() };
87                                    let boxed = alloc::boxed::Box::new(t);
88                                    unsafe { this.put(boxed) }
89                                })
90                                .build()
91                        },
92                    )
93                    .build(),
94            ))
95            .inner(inner_shape::<T>)
96            .build()
97    };
98}
99
100#[cfg(test)]
101mod tests {
102    use alloc::boxed::Box;
103    use alloc::string::String;
104
105    use super::*;
106
107    #[test]
108    fn test_box_type_params() {
109        let [type_param_1] = <Box<i32>>::SHAPE.type_params else {
110            panic!("Box<T> should only have 1 type param")
111        };
112        assert_eq!(type_param_1.shape(), i32::SHAPE);
113    }
114
115    #[test]
116    fn test_box_vtable_1_new_borrow_drop() -> eyre::Result<()> {
117        facet_testhelpers::setup();
118
119        let box_shape = <Box<String>>::SHAPE;
120        let box_def = box_shape
121            .def
122            .into_smart_pointer()
123            .expect("Box<T> should have a smart pointer definition");
124
125        // Allocate memory for the Box
126        let box_uninit_ptr = box_shape.allocate()?;
127
128        // Get the function pointer for creating a new Box from a value
129        let new_into_fn = box_def
130            .vtable
131            .new_into_fn
132            .expect("Box<T> should have new_into_fn");
133
134        // Create the value and initialize the Box
135        let mut value = String::from("example");
136        let box_ptr = unsafe { new_into_fn(box_uninit_ptr, PtrMut::new(&raw mut value)) };
137        // The value now belongs to the Box, prevent its drop
138        core::mem::forget(value);
139
140        // Get the function pointer for borrowing the inner value
141        let borrow_fn = box_def
142            .vtable
143            .borrow_fn
144            .expect("Box<T> should have borrow_fn");
145
146        // Borrow the inner value and check it
147        let borrowed_ptr = unsafe { borrow_fn(box_ptr.as_const()) };
148        // SAFETY: borrowed_ptr points to a valid String within the Box
149        assert_eq!(unsafe { borrowed_ptr.get::<String>() }, "example");
150
151        // Get the function pointer for dropping the Box
152        let drop_fn = (box_shape.vtable.drop_in_place)().expect("Box<T> should have drop_in_place");
153
154        // Drop the Box in place
155        // SAFETY: box_ptr points to a valid Box<String>
156        unsafe { drop_fn(box_ptr) };
157
158        // Deallocate the memory
159        // SAFETY: box_ptr was allocated by box_shape and is now dropped (but memory is still valid)
160        unsafe { box_shape.deallocate_mut(box_ptr)? };
161
162        Ok(())
163    }
164}