Skip to main content

facet_core/impls/alloc/
cow.rs

1use crate::{
2    Def, Facet, KnownPointer, OxPtrConst, OxPtrMut, OxPtrUninit, PointerDef, PointerFlags,
3    PointerVTable, PtrConst, Shape, ShapeBuilder, Type, TypeNameFn, TypeNameOpts, TypeOpsIndirect,
4    TypeParam, UserType, VTableIndirect,
5};
6use crate::{PtrMut, PtrUninit};
7use alloc::borrow::Cow;
8use alloc::borrow::ToOwned;
9
10/// Debug for `Cow<T>` - delegates to inner T's debug
11///
12/// # Safety
13/// The pointer must point to a valid Cow<'_, T> value
14unsafe fn cow_debug<T: ?Sized + ToOwned + 'static>(
15    ox: OxPtrConst,
16    f: &mut core::fmt::Formatter<'_>,
17) -> Option<core::fmt::Result>
18where
19    T::Owned: 'static,
20{
21    let cow_ref: &Cow<'_, T> = unsafe { ox.get::<Cow<'static, T>>() };
22
23    // Get T's shape from the Cow's shape
24    let cow_shape = ox.shape();
25    let t_shape = cow_shape.inner?;
26
27    let inner_ref: &T = cow_ref.as_ref();
28
29    let inner_ptr = PtrConst::new(inner_ref as *const T);
30    unsafe { t_shape.call_debug(inner_ptr, f) }
31}
32
33/// Display for `Cow<T>` - delegates to inner T's display if available
34///
35/// # Safety
36/// The pointer must point to a valid Cow<'_, T> value
37unsafe fn cow_display<T: ?Sized + ToOwned + 'static>(
38    ox: OxPtrConst,
39    f: &mut core::fmt::Formatter<'_>,
40) -> Option<core::fmt::Result>
41where
42    T::Owned: 'static,
43{
44    let cow_ref: &Cow<'_, T> = unsafe { ox.get::<Cow<'static, T>>() };
45
46    // Get T's shape from the Cow's shape
47    let cow_shape = ox.shape();
48    let t_shape = cow_shape.inner?;
49
50    if !t_shape.vtable.has_display() {
51        return None;
52    }
53
54    let inner_ref: &T = cow_ref.as_ref();
55    let inner_ptr = PtrConst::new(inner_ref as *const T);
56
57    unsafe { t_shape.call_display(inner_ptr, f) }
58}
59
60/// PartialEq for `Cow<T>`
61///
62/// # Safety
63/// Both pointers must point to valid Cow<'_, T> values
64unsafe fn cow_partial_eq<T: ?Sized + ToOwned + 'static>(
65    a: OxPtrConst,
66    b: OxPtrConst,
67) -> Option<bool>
68where
69    T::Owned: 'static,
70{
71    let a_cow_ref: &Cow<'_, T> = unsafe { a.get::<Cow<'static, T>>() };
72    let b_cow_ref: &Cow<'_, T> = unsafe { b.get::<Cow<'static, T>>() };
73
74    let cow_shape = a.shape();
75    let t_shape = cow_shape.inner?;
76
77    let a_inner = PtrConst::new(a_cow_ref.as_ref() as *const T);
78    let b_inner = PtrConst::new(b_cow_ref.as_ref() as *const T);
79
80    unsafe { t_shape.call_partial_eq(a_inner, b_inner) }
81}
82
83/// PartialOrd for `Cow<T>`
84///
85/// # Safety
86/// Both pointers must point to valid Cow<'_, T> values
87unsafe fn cow_partial_cmp<T: ?Sized + ToOwned + 'static>(
88    a: OxPtrConst,
89    b: OxPtrConst,
90) -> Option<Option<core::cmp::Ordering>>
91where
92    T::Owned: 'static,
93{
94    let a_cow_ref: &Cow<'_, T> = unsafe { a.get::<Cow<'static, T>>() };
95    let b_cow_ref: &Cow<'_, T> = unsafe { b.get::<Cow<'static, T>>() };
96
97    let cow_shape = a.shape();
98    let t_shape = cow_shape.inner?;
99
100    let a_inner = PtrConst::new(a_cow_ref.as_ref() as *const T);
101    let b_inner = PtrConst::new(b_cow_ref.as_ref() as *const T);
102
103    unsafe { t_shape.call_partial_cmp(a_inner, b_inner) }
104}
105
106/// Ord for `Cow<T>`
107///
108/// # Safety
109/// Both pointers must point to valid Cow<'_, T> values
110unsafe fn cow_cmp<T: ?Sized + ToOwned + 'static>(
111    a: OxPtrConst,
112    b: OxPtrConst,
113) -> Option<core::cmp::Ordering>
114where
115    T::Owned: 'static,
116{
117    let a_cow_ref: &Cow<'_, T> = unsafe { a.get::<Cow<'static, T>>() };
118    let b_cow_ref: &Cow<'_, T> = unsafe { b.get::<Cow<'static, T>>() };
119
120    let cow_shape = a.shape();
121    let t_shape = cow_shape.inner?;
122
123    let a_inner = PtrConst::new(a_cow_ref.as_ref() as *const T);
124    let b_inner = PtrConst::new(b_cow_ref.as_ref() as *const T);
125
126    unsafe { t_shape.call_cmp(a_inner, b_inner) }
127}
128
129/// Borrow the inner value from `Cow<T>`
130///
131/// # Safety
132/// `this` must point to a valid Cow<'_, T> value
133unsafe extern "C" fn cow_borrow<T: ?Sized + ToOwned + 'static>(this: PtrConst) -> PtrConst
134where
135    T::Owned: 'static,
136{
137    // SAFETY: Same layout reasoning as cow_debug
138    let cow_ref: &Cow<'_, T> =
139        unsafe { &*(this.as_byte_ptr() as *const alloc::borrow::Cow<'_, T>) };
140    let inner_ref: &T = cow_ref.as_ref();
141    PtrConst::new(inner_ref as *const T)
142}
143
144/// Create a new `Cow<T>` from a borrowed value
145unsafe extern "C" fn cow_new_into<T: ?Sized + ToOwned + 'static>(
146    this: PtrUninit,
147    ptr: PtrMut,
148) -> PtrMut
149where
150    T::Owned: 'static,
151{
152    unsafe { this.put(Cow::<'_, T>::Borrowed(ptr.read())) }
153}
154
155unsafe impl<'a, T> Facet<'a> for Cow<'a, T>
156where
157    T: 'a + ?Sized + ToOwned + 'static,
158    T: Facet<'a>,
159    T::Owned: Facet<'static>,
160{
161    const SHAPE: &'static Shape = &const {
162        const fn build_cow_vtable<T: ?Sized + ToOwned + 'static>() -> VTableIndirect
163        where
164            T::Owned: Facet<'static> + 'static,
165        {
166            VTableIndirect {
167                debug: Some(cow_debug::<T>),
168                display: Some(cow_display::<T>),
169                partial_eq: Some(cow_partial_eq::<T>),
170                partial_cmp: Some(cow_partial_cmp::<T>),
171                cmp: Some(cow_cmp::<T>),
172                ..VTableIndirect::EMPTY
173            }
174        }
175
176        const fn build_cow_type_ops<'facet, T>() -> TypeOpsIndirect
177        where
178            T: ?Sized + ToOwned + 'static + Facet<'facet>,
179            T::Owned: Facet<'static> + 'static,
180        {
181            unsafe fn drop_in_place<T: ?Sized + ToOwned + 'static>(ox: OxPtrMut)
182            where
183                T::Owned: 'static,
184            {
185                unsafe {
186                    core::ptr::drop_in_place(
187                        ox.ptr().as_ptr::<Cow<'static, T>>() as *mut Cow<'static, T>
188                    )
189                };
190            }
191
192            unsafe fn clone_into<T: ?Sized + ToOwned + 'static>(src: OxPtrConst, dst: OxPtrMut)
193            where
194                T::Owned: 'static,
195            {
196                let src_cow_ref: &Cow<'_, T> = unsafe { src.get::<Cow<'static, T>>() };
197                let cloned = src_cow_ref.clone();
198                // IMPORTANT: `clone_into` must be valid for writes to potentially-uninitialized
199                // destination memory. Do not create `&mut Cow` here (that would assume initialization
200                // and the assignment would drop garbage).
201                let out: *mut Cow<'static, T> =
202                    unsafe { dst.ptr().as_ptr::<Cow<'static, T>>() as *mut Cow<'static, T> };
203                unsafe { core::ptr::write(out, cloned) };
204            }
205
206            /// Default for `Cow<T>` - creates `Cow::Owned(T::Owned::default())`
207            /// by checking if T::Owned supports default at runtime via its shape.
208            ///
209            /// # Safety
210            /// dst must be valid for writes
211            unsafe fn default_in_place<T: ?Sized + ToOwned + 'static>(dst: OxPtrUninit) -> bool
212            where
213                T::Owned: Facet<'static> + 'static,
214            {
215                // Get the Owned type's shape from the second type param
216                let cow_shape = dst.shape();
217                let type_params = cow_shape.type_params;
218                if type_params.len() < 2 {
219                    return false;
220                }
221
222                let owned_shape = type_params[1].shape;
223
224                // Allocate space for T::Owned and call default_in_place
225                let owned_layout = match owned_shape.layout.sized_layout() {
226                    Ok(layout) => layout,
227                    Err(_) => return false,
228                };
229
230                let owned_uninit = crate::alloc_for_layout(owned_layout);
231                if unsafe { owned_shape.call_default_in_place(owned_uninit) }.is_none() {
232                    // Default not supported, deallocate and return
233                    unsafe { crate::dealloc_for_layout(owned_uninit.assume_init(), owned_layout) };
234                    return false;
235                }
236
237                // Move the constructed T::Owned out of the temporary allocation.
238                // This leaves the allocation uninitialized, so we must deallocate the backing storage.
239                let owned_value: T::Owned =
240                    unsafe { core::ptr::read(owned_uninit.as_byte_ptr() as *const T::Owned) };
241                unsafe { crate::dealloc_for_layout(owned_uninit.assume_init(), owned_layout) };
242
243                // Write the Cow::Owned to uninitialized memory
244                unsafe { dst.put(Cow::<'static, T>::Owned(owned_value)) };
245                true
246            }
247
248            unsafe fn truthy<'facet, T>(ptr: PtrConst) -> bool
249            where
250                T: ?Sized + ToOwned + 'static + Facet<'facet>,
251                T::Owned: Facet<'static> + 'static,
252            {
253                let cow_ref: &Cow<'_, T> = unsafe { ptr.get::<Cow<'static, T>>() };
254                let inner_shape = <T as Facet<'facet>>::SHAPE;
255                if let Some(truthy) = inner_shape.truthiness_fn() {
256                    let inner: &T = cow_ref.as_ref();
257                    unsafe { truthy(PtrConst::new(inner as *const T)) }
258                } else {
259                    false
260                }
261            }
262
263            TypeOpsIndirect {
264                drop_in_place: drop_in_place::<T>,
265                default_in_place: Some(default_in_place::<T>),
266                clone_into: Some(clone_into::<T>),
267                is_truthy: Some(truthy::<'facet, T>),
268            }
269        }
270
271        const fn build_type_name<'a, T: Facet<'a> + ?Sized + ToOwned>() -> TypeNameFn {
272            fn type_name_impl<'a, T: Facet<'a> + ?Sized + ToOwned>(
273                _shape: &'static Shape,
274                f: &mut core::fmt::Formatter<'_>,
275                opts: TypeNameOpts,
276            ) -> core::fmt::Result {
277                write!(f, "Cow")?;
278                if let Some(opts) = opts.for_children() {
279                    write!(f, "<")?;
280                    T::SHAPE.write_type_name(f, opts)?;
281                    write!(f, ">")?;
282                } else {
283                    write!(f, "<…>")?;
284                }
285                Ok(())
286            }
287            type_name_impl::<T>
288        }
289
290        ShapeBuilder::for_sized::<Cow<'a, T>>("Cow")
291            .module_path("alloc::borrow")
292            .type_name(build_type_name::<T>())
293            .ty(Type::User(UserType::Opaque))
294            .def(Def::Pointer(PointerDef {
295                vtable: &const {
296                    PointerVTable {
297                        borrow_fn: Some(cow_borrow::<T>),
298                        new_into_fn: Some(cow_new_into::<T>),
299                        ..PointerVTable::new()
300                    }
301                },
302                pointee: Some(T::SHAPE),
303                weak: None,
304                strong: None,
305                flags: PointerFlags::EMPTY,
306                known: Some(KnownPointer::Cow),
307            }))
308            .type_params(&[
309                TypeParam {
310                    name: "T",
311                    shape: T::SHAPE,
312                },
313                TypeParam {
314                    name: "Owned",
315                    shape: <T::Owned>::SHAPE,
316                },
317            ])
318            .inner(T::SHAPE)
319            .vtable_indirect(&const { build_cow_vtable::<T>() })
320            .type_ops_indirect(&const { build_cow_type_ops::<'a, T>() })
321            .build()
322    };
323}
324
325#[cfg(test)]
326mod tests {
327    use core::{mem::ManuallyDrop, ptr::NonNull};
328
329    use alloc::string::String;
330
331    use super::*;
332
333    #[test]
334    fn test_cow_type_params() {
335        let [type_param_1, type_param_2] = <Cow<'_, str>>::SHAPE.type_params else {
336            panic!("Cow<'_, T> should only have 2 type params")
337        };
338        assert_eq!(type_param_1.shape(), str::SHAPE);
339        assert_eq!(type_param_2.shape(), String::SHAPE);
340    }
341
342    #[test]
343    fn test_cow_vtable_1_new_borrow_drop() {
344        facet_testhelpers::setup();
345
346        let cow_shape = <Cow<'_, str>>::SHAPE;
347        let cow_def = cow_shape
348            .def
349            .into_pointer()
350            .expect("Cow<'_, T> should have a smart pointer definition");
351
352        // Allocate memory for the Cow
353        let cow_uninit_ptr = cow_shape.allocate().unwrap();
354
355        // Get the function pointer for creating a new Cow from a value
356        let new_into_fn = cow_def
357            .vtable
358            .new_into_fn
359            .expect("Cow<'_, T> should have new_into_fn");
360
361        // Create the value and initialize the Cow
362        let mut value = ManuallyDrop::new("example");
363        let cow_ptr = unsafe {
364            new_into_fn(
365                cow_uninit_ptr,
366                PtrMut::new(NonNull::from(&mut value).as_ptr()),
367            )
368        };
369        // The value now belongs to the Cow, prevent its drop
370
371        // Get the function pointer for borrowing the inner value
372        let borrow_fn = cow_def
373            .vtable
374            .borrow_fn
375            .expect("Cow<'_, T> should have borrow_fn");
376
377        // Borrow the inner value and check it
378        let borrowed_ptr = unsafe { borrow_fn(cow_ptr.as_const()) };
379        // SAFETY: borrowed_ptr points to a valid String within the Cow
380        assert_eq!(unsafe { borrowed_ptr.get::<str>() }, "example");
381
382        // Drop the value in place
383        // SAFETY: value_ptr points to a valid String
384        unsafe {
385            cow_shape
386                .call_drop_in_place(cow_ptr)
387                .expect("Cow<'_, T> should have drop_in_place");
388        }
389
390        // Deallocate the memory
391        // SAFETY: cow_ptr was allocated by cow_shape and is now dropped (but memory is still valid)
392        unsafe { cow_shape.deallocate_mut(cow_ptr).unwrap() };
393    }
394}