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

facet-rs / facet / 15200164445

23 May 2025 01:21AM UTC coverage: 57.288% (+0.1%) from 57.185%
15200164445

Pull #666

github

web-flow
Merge 4232978c5 into 4b41e5c8a
Pull Request #666: Add indirection to vtable fns to fix cyclic types

715 of 1482 new or added lines in 34 files covered. (48.25%)

14 existing lines in 5 files now uncovered.

9747 of 17014 relevant lines covered (57.29%)

132.73 hits per line

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

65.9
/facet-core/src/impls_alloc/rc.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::rc::Rc<T> {
8
    const VTABLE: &'static ValueVTable = &const {
9
        // Define the functions for transparent conversion between Rc<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 rc = alloc::rc::Rc::new(t);
×
23
            Ok(unsafe { dst.put(rc) })
×
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 rc = unsafe { src_ptr.get::<alloc::rc::Rc<T>>() };
×
31
            match alloc::rc::Rc::try_unwrap(rc.clone()) {
×
32
                Ok(t) => Ok(unsafe { dst.put(t) }),
×
33
                Err(_) => Err(TryIntoInnerError::Unavailable),
×
34
            }
35
        }
×
36

37
        unsafe fn try_borrow_inner<'a, 'src, T: Facet<'a>>(
×
38
            src_ptr: PtrConst<'src>,
×
39
        ) -> Result<PtrConst<'src>, TryBorrowInnerError> {
×
40
            let rc = unsafe { src_ptr.get::<alloc::rc::Rc<T>>() };
×
41
            Ok(PtrConst::new(&**rc))
×
42
        }
×
43

44
        let mut vtable = value_vtable!(alloc::rc::Rc<T>, |f, opts| {
×
45
            write!(f, "Rc")?;
×
46
            if let Some(opts) = opts.for_children() {
×
47
                write!(f, "<")?;
×
48
                (T::SHAPE.vtable.type_name)(f, opts)?;
×
49
                write!(f, ">")?;
×
50
            } else {
51
                write!(f, "<…>")?;
×
52
            }
53
            Ok(())
×
54
        });
×
NEW
55
        vtable.try_from = || Some(try_from::<T>);
×
NEW
56
        vtable.try_into_inner = || Some(try_into_inner::<T>);
×
NEW
57
        vtable.try_borrow_inner = || Some(try_borrow_inner::<T>);
×
58
        vtable
59
    };
60

61
    const SHAPE: &'static crate::Shape<'static> = &const {
62
        // Function to return inner type's shape
63
        fn inner_shape<'a, T: Facet<'a>>() -> &'static Shape<'static> {
×
64
            T::SHAPE
×
65
        }
×
66

67
        crate::Shape::builder_for_sized::<Self>()
68
            .type_params(&[crate::TypeParam {
69
                name: "T",
70
                shape: || T::SHAPE,
71
            }])
72
            .ty(Type::User(UserType::Opaque))
73
            .def(Def::SmartPointer(
74
                SmartPointerDef::builder()
75
                    .pointee(|| T::SHAPE)
76
                    .flags(SmartPointerFlags::EMPTY)
77
                    .known(KnownSmartPointer::Rc)
78
                    .weak(|| <alloc::rc::Weak<T> as Facet>::SHAPE)
79
                    .vtable(
80
                        &const {
81
                            SmartPointerVTable::builder()
82
                                .borrow_fn(|this| {
2✔
83
                                    let ptr = Self::as_ptr(unsafe { this.get() });
2✔
84
                                    PtrConst::new(ptr)
2✔
85
                                })
2✔
86
                                .new_into_fn(|this, ptr| {
3✔
87
                                    let t = unsafe { ptr.read::<T>() };
3✔
88
                                    let rc = alloc::rc::Rc::new(t);
3✔
89
                                    unsafe { this.put(rc) }
3✔
90
                                })
3✔
91
                                .downgrade_into_fn(|strong, weak| unsafe {
92
                                    weak.put(alloc::rc::Rc::downgrade(strong.get::<Self>()))
2✔
93
                                })
2✔
94
                                .build()
95
                        },
96
                    )
97
                    .build(),
98
            ))
99
            .inner(inner_shape::<T>)
100
            .build()
101
    };
102
}
103

104
unsafe impl<'a, T: Facet<'a>> Facet<'a> for alloc::rc::Weak<T> {
105
    const VTABLE: &'static ValueVTable = &const {
106
        value_vtable!(alloc::rc::Weak<T>, |f, opts| {
×
107
            write!(f, "Weak")?;
×
108
            if let Some(opts) = opts.for_children() {
×
109
                write!(f, "<")?;
×
110
                (T::SHAPE.vtable.type_name)(f, opts)?;
×
111
                write!(f, ">")?;
×
112
            } else {
113
                write!(f, "<…>")?;
×
114
            }
115
            Ok(())
×
116
        })
×
117
    };
118

119
    const SHAPE: &'static crate::Shape<'static> = &const {
120
        // Function to return inner type's shape
121
        fn inner_shape<'a, T: Facet<'a>>() -> &'static Shape<'static> {
×
122
            T::SHAPE
×
123
        }
×
124

125
        crate::Shape::builder_for_sized::<Self>()
126
            .type_params(&[crate::TypeParam {
127
                name: "T",
128
                shape: || T::SHAPE,
129
            }])
130
            .ty(Type::User(UserType::Opaque))
131
            .def(Def::SmartPointer(
132
                SmartPointerDef::builder()
133
                    .pointee(|| T::SHAPE)
134
                    .flags(SmartPointerFlags::WEAK)
135
                    .known(KnownSmartPointer::RcWeak)
136
                    .strong(|| <alloc::rc::Rc<T> as Facet>::SHAPE)
137
                    .vtable(
138
                        &const {
139
                            SmartPointerVTable::builder()
140
                                .upgrade_into_fn(|weak, strong| unsafe {
141
                                    Some(strong.put(weak.get::<Self>().upgrade()?))
2✔
142
                                })
2✔
143
                                .build()
144
                        },
145
                    )
146
                    .build(),
147
            ))
148
            .inner(inner_shape::<T>)
149
            .build()
150
    };
151
}
152

153
#[cfg(test)]
154
mod tests {
155
    use alloc::rc::{Rc, Weak as RcWeak};
156
    use alloc::string::String;
157

158
    use super::*;
159

160
    #[test]
161
    fn test_rc_type_params() {
1✔
162
        let [type_param_1] = <Rc<i32>>::SHAPE.type_params else {
1✔
163
            panic!("Rc<T> should only have 1 type param")
×
164
        };
165
        assert_eq!(type_param_1.shape(), i32::SHAPE);
1✔
166
    }
1✔
167

168
    #[test]
169
    fn test_rc_vtable_1_new_borrow_drop() -> eyre::Result<()> {
1✔
170
        facet_testhelpers::setup();
1✔
171

172
        let rc_shape = <Rc<String>>::SHAPE;
1✔
173
        let rc_def = rc_shape
1✔
174
            .def
1✔
175
            .into_smart_pointer()
1✔
176
            .expect("Rc<T> should have a smart pointer definition");
1✔
177

178
        // Allocate memory for the Rc
179
        let rc_uninit_ptr = rc_shape.allocate()?;
1✔
180

181
        // Get the function pointer for creating a new Rc from a value
182
        let new_into_fn = rc_def
1✔
183
            .vtable
1✔
184
            .new_into_fn
1✔
185
            .expect("Rc<T> should have new_into_fn");
1✔
186

187
        // Create the value and initialize the Rc
188
        let mut value = String::from("example");
1✔
189
        let rc_ptr = unsafe { new_into_fn(rc_uninit_ptr, PtrMut::new(&raw mut value)) };
1✔
190
        // The value now belongs to the Rc, prevent its drop
191
        core::mem::forget(value);
1✔
192

193
        // Get the function pointer for borrowing the inner value
194
        let borrow_fn = rc_def
1✔
195
            .vtable
1✔
196
            .borrow_fn
1✔
197
            .expect("Rc<T> should have borrow_fn");
1✔
198

199
        // Borrow the inner value and check it
200
        let borrowed_ptr = unsafe { borrow_fn(rc_ptr.as_const()) };
1✔
201
        // SAFETY: borrowed_ptr points to a valid String within the Rc
202
        assert_eq!(unsafe { borrowed_ptr.get::<String>() }, "example");
1✔
203

204
        // Get the function pointer for dropping the Rc
205
        let drop_fn = (rc_shape.vtable.drop_in_place)().expect("Rc<T> should have drop_in_place");
1✔
206

207
        // Drop the Rc in place
208
        // SAFETY: rc_ptr points to a valid Rc<String>
209
        unsafe { drop_fn(rc_ptr) };
1✔
210

211
        // Deallocate the memory
212
        // SAFETY: rc_ptr was allocated by rc_shape and is now dropped (but memory is still valid)
213
        unsafe { rc_shape.deallocate_mut(rc_ptr)? };
1✔
214

215
        Ok(())
1✔
216
    }
1✔
217

218
    #[test]
219
    fn test_rc_vtable_2_downgrade_upgrade_drop() -> eyre::Result<()> {
1✔
220
        facet_testhelpers::setup();
1✔
221

222
        let rc_shape = <Rc<String>>::SHAPE;
1✔
223
        let rc_def = rc_shape
1✔
224
            .def
1✔
225
            .into_smart_pointer()
1✔
226
            .expect("Rc<T> should have a smart pointer definition");
1✔
227

228
        let weak_shape = <RcWeak<String>>::SHAPE;
1✔
229
        let weak_def = weak_shape
1✔
230
            .def
1✔
231
            .into_smart_pointer()
1✔
232
            .expect("RcWeak<T> should have a smart pointer definition");
1✔
233

234
        // 1. Create the first Rc (rc1)
235
        let rc1_uninit_ptr = rc_shape.allocate()?;
1✔
236
        let new_into_fn = rc_def.vtable.new_into_fn.unwrap();
1✔
237
        let mut value = String::from("example");
1✔
238
        let rc1_ptr = unsafe { new_into_fn(rc1_uninit_ptr, PtrMut::new(&raw mut value)) };
1✔
239
        core::mem::forget(value); // Value now owned by rc1
1✔
240

241
        // 2. Downgrade rc1 to create a weak pointer (weak1)
242
        let weak1_uninit_ptr = weak_shape.allocate()?;
1✔
243
        let downgrade_into_fn = rc_def.vtable.downgrade_into_fn.unwrap();
1✔
244
        // SAFETY: rc1_ptr points to a valid Rc, weak1_uninit_ptr is allocated for a Weak
245
        let weak1_ptr = unsafe { downgrade_into_fn(rc1_ptr, weak1_uninit_ptr) };
1✔
246

247
        // 3. Upgrade weak1 to create a second Rc (rc2)
248
        let rc2_uninit_ptr = rc_shape.allocate()?;
1✔
249
        let upgrade_into_fn = weak_def.vtable.upgrade_into_fn.unwrap();
1✔
250
        // SAFETY: weak1_ptr points to a valid Weak, rc2_uninit_ptr is allocated for an Rc.
251
        // Upgrade should succeed as rc1 still exists.
252
        let rc2_ptr = unsafe { upgrade_into_fn(weak1_ptr, rc2_uninit_ptr) }
1✔
253
            .expect("Upgrade should succeed while original Rc exists");
1✔
254

255
        // Check the content of the upgraded Rc
256
        let borrow_fn = rc_def.vtable.borrow_fn.unwrap();
1✔
257
        // SAFETY: rc2_ptr points to a valid Rc<String>
258
        let borrowed_ptr = unsafe { borrow_fn(rc2_ptr.as_const()) };
1✔
259
        // SAFETY: borrowed_ptr points to a valid String
260
        assert_eq!(unsafe { borrowed_ptr.get::<String>() }, "example");
1✔
261

262
        // 4. Drop everything and free memory
263
        let rc_drop_fn = (rc_shape.vtable.drop_in_place)().unwrap();
1✔
264
        let weak_drop_fn = (weak_shape.vtable.drop_in_place)().unwrap();
1✔
265

266
        unsafe {
267
            // Drop Rcs
268
            rc_drop_fn(rc1_ptr);
1✔
269
            rc_shape.deallocate_mut(rc1_ptr)?;
1✔
270
            rc_drop_fn(rc2_ptr);
1✔
271
            rc_shape.deallocate_mut(rc2_ptr)?;
1✔
272

273
            // Drop Weak
274
            weak_drop_fn(weak1_ptr);
1✔
275
            weak_shape.deallocate_mut(weak1_ptr)?;
1✔
276
        }
277

278
        Ok(())
1✔
279
    }
1✔
280

281
    #[test]
282
    fn test_rc_vtable_3_downgrade_drop_try_upgrade() -> eyre::Result<()> {
1✔
283
        facet_testhelpers::setup();
1✔
284

285
        let rc_shape = <Rc<String>>::SHAPE;
1✔
286
        let rc_def = rc_shape
1✔
287
            .def
1✔
288
            .into_smart_pointer()
1✔
289
            .expect("Rc<T> should have a smart pointer definition");
1✔
290

291
        let weak_shape = <RcWeak<String>>::SHAPE;
1✔
292
        let weak_def = weak_shape
1✔
293
            .def
1✔
294
            .into_smart_pointer()
1✔
295
            .expect("RcWeak<T> should have a smart pointer definition");
1✔
296

297
        // 1. Create the strong Rc (rc1)
298
        let rc1_uninit_ptr = rc_shape.allocate()?;
1✔
299
        let new_into_fn = rc_def.vtable.new_into_fn.unwrap();
1✔
300
        let mut value = String::from("example");
1✔
301
        let rc1_ptr = unsafe { new_into_fn(rc1_uninit_ptr, PtrMut::new(&raw mut value)) };
1✔
302
        core::mem::forget(value);
1✔
303

304
        // 2. Downgrade rc1 to create a weak pointer (weak1)
305
        let weak1_uninit_ptr = weak_shape.allocate()?;
1✔
306
        let downgrade_into_fn = rc_def.vtable.downgrade_into_fn.unwrap();
1✔
307
        // SAFETY: rc1_ptr is valid, weak1_uninit_ptr is allocated for Weak
308
        let weak1_ptr = unsafe { downgrade_into_fn(rc1_ptr, weak1_uninit_ptr) };
1✔
309

310
        // 3. Drop and free the strong pointer (rc1)
311
        let rc_drop_fn = (rc_shape.vtable.drop_in_place)().unwrap();
1✔
312
        unsafe {
313
            rc_drop_fn(rc1_ptr);
1✔
314
            rc_shape.deallocate_mut(rc1_ptr)?;
1✔
315
        }
316

317
        // 4. Attempt to upgrade the weak pointer (weak1)
318
        let upgrade_into_fn = weak_def.vtable.upgrade_into_fn.unwrap();
1✔
319
        let rc2_uninit_ptr = rc_shape.allocate()?;
1✔
320
        // SAFETY: weak1_ptr is valid (though points to dropped data), rc2_uninit_ptr is allocated for Rc
321
        let upgrade_result = unsafe { upgrade_into_fn(weak1_ptr, rc2_uninit_ptr) };
1✔
322

323
        // Assert that the upgrade failed
324
        assert!(
1✔
325
            upgrade_result.is_none(),
1✔
326
            "Upgrade should fail after the strong Rc is dropped"
×
327
        );
328

329
        // 5. Clean up: Deallocate the memory intended for the failed upgrade and drop/deallocate the weak pointer
330
        let weak_drop_fn = (weak_shape.vtable.drop_in_place)().unwrap();
1✔
331
        unsafe {
332
            // Deallocate the *uninitialized* memory allocated for the failed upgrade attempt
333
            rc_shape.deallocate_uninit(rc2_uninit_ptr)?;
1✔
334

335
            // Drop and deallocate the weak pointer
336
            weak_drop_fn(weak1_ptr);
1✔
337
            weak_shape.deallocate_mut(weak1_ptr)?;
1✔
338
        }
339

340
        Ok(())
1✔
341
    }
1✔
342
}
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