safer_ffi/
boxed.rs

1#![cfg_attr(rustfmt, rustfmt::skip)]
2//! `#[repr(C)]` [`Box`][`rust::Box`]ed types.
3
4use_prelude!();
5
6ReprC! {
7    #[repr(transparent)]
8    /// Same as [`Box<T>`][`rust::Box`], (_e.g._, same `#[repr(C)]` layout), but
9    /// with **no non-aliasing guarantee**.
10    pub
11    struct Box_[T] (
12        ptr::NonNullOwned<T>,
13    );
14}
15
16impl<T> From<rust::Box<T>>
17    for Box_<T>
18{
19    #[inline]
20    fn from (boxed: rust::Box<T>)
21      -> Box_<T>
22    {
23        Self(
24            ptr::NonNull::from(rust::Box::leak(boxed))
25                .into()
26        )
27    }
28}
29
30impl<T> Box_<T> {
31    #[inline]
32    pub
33    fn new (value: T)
34      -> Self
35    {
36        rust::Box::new(value)
37            .into()
38    }
39
40    #[inline]
41    pub
42    fn into (self: Box_<T>)
43      -> rust::Box<T>
44    {
45        let mut this = mem::ManuallyDrop::new(self);
46        unsafe {
47            rust::Box::from_raw(this.0.as_mut_ptr())
48        }
49    }
50}
51
52impl<T> Drop
53    for Box_<T>
54{
55    #[inline]
56    fn drop (self: &'_ mut Box_<T>)
57    {
58        unsafe {
59            drop::<rust::Box<T>>(
60                rust::Box::from_raw(self.0.as_mut_ptr())
61            );
62        }
63    }
64}
65
66impl<T> Deref
67    for Box_<T>
68{
69    type Target = T;
70
71    #[inline]
72    fn deref (self: &'_ Box_<T>)
73      -> &'_ T
74    {
75        unsafe {
76            &*self.0.as_ptr()
77        }
78    }
79}
80
81impl<T> DerefMut
82    for Box_<T>
83{
84    #[inline]
85    fn deref_mut (self: &'_ mut Box_<T>)
86      -> &'_ mut T
87    {
88        unsafe {
89            &mut *(self.0.as_mut_ptr())
90        }
91    }
92}
93
94unsafe impl<T> Send
95    for Box_<T>
96where
97    rust::Box<T> : Send,
98{}
99
100unsafe impl<T> Sync
101    for Box_<T>
102where
103    rust::Box<T> : Sync,
104{}
105
106impl<T : Clone> Clone
107    for Box_<T>
108{
109    #[inline]
110    fn clone(self: &'_ Self)
111      -> Self
112    {
113        Self::new(T::clone(self))
114    }
115}
116
117impl<T : fmt::Debug> fmt::Debug
118    for Box_<T>
119{
120    fn fmt (self: &'_ Self, fmt: &'_ mut fmt::Formatter<'_>)
121      -> fmt::Result
122    {
123        T::fmt(self, fmt)
124    }
125}
126
127#[doc(no_inline)]
128pub use crate::slice::slice_boxed;
129
130#[doc(no_inline)]
131pub use crate::string::str_boxed;
132
133pub
134type Box<T> = <T as FitForCBox>::CBoxWrapped;
135
136pub
137trait FitForCBox {
138    type CBoxWrapped;
139}
140
141impl<T : Sized> FitForCBox for T {
142    type CBoxWrapped = Box_<T>;
143}
144
145impl<T : Sized> FitForCBox for [T] {
146    type CBoxWrapped = c_slice::Box<T>;
147}
148
149pub
150trait FitForCArc {
151    type CArcWrapped;
152}