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, "Box")?;
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_params(&[crate::TypeParam {
66                name: "T",
67                shape: || T::SHAPE,
68            }])
69            .ty(Type::User(UserType::Opaque))
70            .def(Def::SmartPointer(
71                SmartPointerDef::builder()
72                    .pointee(|| T::SHAPE)
73                    .flags(SmartPointerFlags::EMPTY)
74                    .known(KnownSmartPointer::Box)
75                    .vtable(
76                        &const {
77                            SmartPointerVTable::builder()
78                                .borrow_fn(|this| {
79                                    let ptr = unsafe {
80                                        &raw const **this.as_ptr::<alloc::boxed::Box<T>>()
81                                    };
82                                    PtrConst::new(ptr)
83                                })
84                                .new_into_fn(|this, ptr| {
85                                    let t = unsafe { ptr.read::<T>() };
86                                    let boxed = alloc::boxed::Box::new(t);
87                                    unsafe { this.put(boxed) }
88                                })
89                                .build()
90                        },
91                    )
92                    .build(),
93            ))
94            .inner(inner_shape::<T>)
95            .build()
96    };
97}
98
99#[cfg(test)]
100mod tests {
101    use alloc::boxed::Box;
102    use alloc::string::String;
103
104    use super::*;
105
106    #[test]
107    fn test_box_type_params() {
108        let [type_param_1] = <Box<i32>>::SHAPE.type_params else {
109            panic!("Box<T> should only have 1 type param")
110        };
111        assert_eq!(type_param_1.shape(), i32::SHAPE);
112    }
113
114    #[test]
115    fn test_box_vtable_1_new_borrow_drop() -> eyre::Result<()> {
116        facet_testhelpers::setup();
117
118        let box_shape = <Box<String>>::SHAPE;
119        let box_def = box_shape
120            .def
121            .into_smart_pointer()
122            .expect("Box<T> should have a smart pointer definition");
123
124        // Allocate memory for the Box
125        let box_uninit_ptr = box_shape.allocate()?;
126
127        // Get the function pointer for creating a new Box from a value
128        let new_into_fn = box_def
129            .vtable
130            .new_into_fn
131            .expect("Box<T> should have new_into_fn");
132
133        // Create the value and initialize the Box
134        let mut value = String::from("example");
135        let box_ptr = unsafe { new_into_fn(box_uninit_ptr, PtrMut::new(&raw mut value)) };
136        // The value now belongs to the Box, prevent its drop
137        core::mem::forget(value);
138
139        // Get the function pointer for borrowing the inner value
140        let borrow_fn = box_def
141            .vtable
142            .borrow_fn
143            .expect("Box<T> should have borrow_fn");
144
145        // Borrow the inner value and check it
146        let borrowed_ptr = unsafe { borrow_fn(box_ptr.as_const()) };
147        // SAFETY: borrowed_ptr points to a valid String within the Box
148        assert_eq!(unsafe { borrowed_ptr.get::<String>() }, "example");
149
150        // Get the function pointer for dropping the Box
151        let drop_fn = box_shape
152            .vtable
153            .drop_in_place
154            .expect("Box<T> should have drop_in_place");
155
156        // Drop the Box in place
157        // SAFETY: box_ptr points to a valid Box<String>
158        unsafe { drop_fn(box_ptr) };
159
160        // Deallocate the memory
161        // SAFETY: box_ptr was allocated by box_shape and is now dropped (but memory is still valid)
162        unsafe { box_shape.deallocate_mut(box_ptr)? };
163
164        Ok(())
165    }
166}