• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

facet-rs / facet / 15221452970

24 May 2025 12:26AM UTC coverage: 57.643% (+0.1%) from 57.538%
15221452970

Pull #666

github

web-flow
Merge e32d9af09 into 48c76b4b0
Pull Request #666: Add indirection to vtable fns to fix cyclic types

779 of 1499 new or added lines in 35 files covered. (51.97%)

14 existing lines in 5 files now uncovered.

9880 of 17140 relevant lines covered (57.64%)

137.68 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

75.0
/facet-core/src/impls_alloc/boxed.rs
1
use crate::{
2
    Def, Facet, KnownSmartPointer, PtrConst, PtrMut, PtrUninit, Shape, SmartPointerDef,
3
    SmartPointerFlags, SmartPointerVTable, TryBorrowInnerError, TryFromError, TryIntoInnerError,
4
    Type, UserType, ValueVTable, value_vtable,
5
};
6

7
unsafe 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>>(
2✔
11
            src_ptr: PtrConst<'src>,
2✔
12
            src_shape: &'shape Shape<'shape>,
2✔
13
            dst: PtrUninit<'dst>,
2✔
14
        ) -> Result<PtrMut<'dst>, TryFromError<'shape>> {
2✔
15
            if src_shape.id != T::SHAPE.id {
2✔
16
                return Err(TryFromError::UnsupportedSourceShape {
×
17
                    src_shape,
×
18
                    expected: &[T::SHAPE],
×
19
                });
×
20
            }
2✔
21
            let t = unsafe { src_ptr.read::<T>() };
2✔
22
            let boxed = alloc::boxed::Box::new(t);
2✔
23
            Ok(unsafe { dst.put(boxed) })
2✔
24
        }
2✔
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| {
10✔
42
            write!(f, "Box")?;
10✔
43
            if let Some(opts) = opts.for_children() {
10✔
44
                write!(f, "<")?;
10✔
45
                (T::SHAPE.vtable.type_name)(f, opts)?;
10✔
46
                write!(f, ">")?;
10✔
47
            } else {
48
                write!(f, "<…>")?;
×
49
            }
50
            Ok(())
10✔
51
        });
10✔
52
        vtable.try_from = || Some(try_from::<T>);
2✔
NEW
53
        vtable.try_into_inner = || Some(try_into_inner::<T>);
×
NEW
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> {
4✔
61
            T::SHAPE
4✔
62
        }
4✔
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| {
1✔
79
                                    let ptr = unsafe {
1✔
80
                                        &raw const **this.as_ptr::<alloc::boxed::Box<T>>()
1✔
81
                                    };
82
                                    PtrConst::new(ptr)
1✔
83
                                })
1✔
84
                                .new_into_fn(|this, ptr| {
1✔
85
                                    let t = unsafe { ptr.read::<T>() };
1✔
86
                                    let boxed = alloc::boxed::Box::new(t);
1✔
87
                                    unsafe { this.put(boxed) }
1✔
88
                                })
1✔
89
                                .build()
90
                        },
91
                    )
92
                    .build(),
93
            ))
94
            .inner(inner_shape::<T>)
95
            .build()
96
    };
97
}
98

99
#[cfg(test)]
100
mod tests {
101
    use alloc::boxed::Box;
102
    use alloc::string::String;
103

104
    use super::*;
105

106
    #[test]
107
    fn test_box_type_params() {
1✔
108
        let [type_param_1] = <Box<i32>>::SHAPE.type_params else {
1✔
109
            panic!("Box<T> should only have 1 type param")
×
110
        };
111
        assert_eq!(type_param_1.shape(), i32::SHAPE);
1✔
112
    }
1✔
113

114
    #[test]
115
    fn test_box_vtable_1_new_borrow_drop() -> eyre::Result<()> {
1✔
116
        facet_testhelpers::setup();
1✔
117

118
        let box_shape = <Box<String>>::SHAPE;
1✔
119
        let box_def = box_shape
1✔
120
            .def
1✔
121
            .into_smart_pointer()
1✔
122
            .expect("Box<T> should have a smart pointer definition");
1✔
123

124
        // Allocate memory for the Box
125
        let box_uninit_ptr = box_shape.allocate()?;
1✔
126

127
        // Get the function pointer for creating a new Box from a value
128
        let new_into_fn = box_def
1✔
129
            .vtable
1✔
130
            .new_into_fn
1✔
131
            .expect("Box<T> should have new_into_fn");
1✔
132

133
        // Create the value and initialize the Box
134
        let mut value = String::from("example");
1✔
135
        let box_ptr = unsafe { new_into_fn(box_uninit_ptr, PtrMut::new(&raw mut value)) };
1✔
136
        // The value now belongs to the Box, prevent its drop
137
        core::mem::forget(value);
1✔
138

139
        // Get the function pointer for borrowing the inner value
140
        let borrow_fn = box_def
1✔
141
            .vtable
1✔
142
            .borrow_fn
1✔
143
            .expect("Box<T> should have borrow_fn");
1✔
144

145
        // Borrow the inner value and check it
146
        let borrowed_ptr = unsafe { borrow_fn(box_ptr.as_const()) };
1✔
147
        // SAFETY: borrowed_ptr points to a valid String within the Box
148
        assert_eq!(unsafe { borrowed_ptr.get::<String>() }, "example");
1✔
149

150
        // Get the function pointer for dropping the Box
151
        let drop_fn = (box_shape.vtable.drop_in_place)().expect("Box<T> should have drop_in_place");
1✔
152

153
        // Drop the Box in place
154
        // SAFETY: box_ptr points to a valid Box<String>
155
        unsafe { drop_fn(box_ptr) };
1✔
156

157
        // Deallocate the memory
158
        // SAFETY: box_ptr was allocated by box_shape and is now dropped (but memory is still valid)
159
        unsafe { box_shape.deallocate_mut(box_ptr)? };
1✔
160

161
        Ok(())
1✔
162
    }
1✔
163
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc