1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use std::{marker::PhantomData, mem::ManuallyDrop, ops::DerefMut};

#[allow(unused_imports)]
use core_extensions::prelude::*;

use crate::{
    pointer_trait::{CallReferentDrop, StableDeref, TransmuteElement},
    traits::{IntoReprRust},
    std_types::utypeid::{UTypeId,new_utypeid},
    return_value_equality::ReturnValueEquality,
    prefix_type::{PrefixTypeTrait,WithMetadata},
};

#[cfg(test)]
mod test;

mod private {
    use super::*;

    /// Ffi-safe equivalent of Box<_>.
    #[repr(C)]
    #[derive(StableAbi)]
    #[sabi(inside_abi_stable_crate)]
    pub struct RBox<T> {
        data: *mut T,
        vtable: *const BoxVtable<T>,
        _marker: PhantomData<T>,
    }

    impl<T> RBox<T> {
        /// Constucts an `RBox<T>` from a value.
        pub fn new(value: T) -> Self {
            Box::new(value).piped(RBox::from_box)
        }
        /// Converts a `Box<T>` to an `RBox<T>`,reusing its heap allocation.
        pub fn from_box(p: Box<T>) -> RBox<T> {
            RBox {
                data: Box::into_raw(p),
                vtable: VTableGetter::<T>::LIB_VTABLE.as_prefix_raw(),
                _marker: PhantomData,
            }
        }

        pub(super) fn data(&self) -> *mut T {
            self.data
        }
        pub(super) fn vtable<'a>(&self) -> &'a BoxVtable<T> {
            unsafe { &*self.vtable }
        }

        #[cfg(test)]
        pub(super) fn set_vtable_for_testing(&mut self) {
            self.vtable = VTableGetter::<T>::LIB_VTABLE_FOR_TESTING.as_prefix_raw();
        }
    }
}

pub use self::private::RBox;

unsafe impl<T> StableDeref for RBox<T> {}

unsafe impl<T, O> TransmuteElement<O> for RBox<T> {
    type TransmutedPtr = RBox<O>;
}

impl<T> RBox<T> {
    /// Converts this `RBox<T>` into a `Box<T>`
    ///
    /// # Allocation
    ///
    /// If this is invoked outside of the dynamic library/binary that created the `RBox<T>`,
    /// it will allocate a new `Box<T>` and move the data into it.
    pub fn into_box(this: Self) -> Box<T> {
        let this = ManuallyDrop::new(this);

        unsafe {
            let this_vtable =this.vtable();
            let other_vtable=VTableGetter::LIB_VTABLE.as_prefix();
            if ::std::ptr::eq(this_vtable,other_vtable)||
                this_vtable.type_id()==other_vtable.type_id()
            {
                Box::from_raw(this.data())
            } else {
                let ret = Box::new(this.data().read());
                // Just deallocating the Box<_>. without dropping the inner value
                (this.vtable().destructor())(this.data(), CallReferentDrop::No);
                ret
            }
        }
    }
    /// Unwraps this `Box<T>` into the value it owns on the heap.
    pub fn into_inner(this: Self) -> T {
        let this = ManuallyDrop::new(this);
        unsafe {
            let value = this.data().read();
            let data: *mut T = this.data();
            (this.vtable().destructor())(data, CallReferentDrop::No);
            value
        }
    }
}

impl<T> DerefMut for RBox<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *self.data() }
    }
}

/////////////////////////////////////////////////////////////////

impl_from_rust_repr! {
    impl[T] From<Box<T>> for RBox<T> {
        fn(this){
            RBox::from_box(this)
        }
    }
}

/////////////////////////////////////////////////////////////////

impl<T> IntoReprRust for RBox<T> {
    type ReprRust = Box<T>;

    fn into_rust(self) -> Self::ReprRust {
        Self::into_box(self)
    }
}

/////////////////////////////////////////////////////////////////

impl<T> Default for RBox<T>
where
    T: Default,
{
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T> Clone for RBox<T>
where
    T: Clone,
{
    fn clone(&self) -> Self {
        (**self).clone().piped(Box::new).into()
    }
}

shared_impls! {pointer
    mod=box_impls
    new_type=RBox[][T],
    original_type=Box,
}

unsafe impl<T: Send> Send for RBox<T> {}
unsafe impl<T: Sync> Sync for RBox<T> {}

///////////////////////////////////////////////////////////////

impl<T> Drop for RBox<T> {
    fn drop(&mut self) {
        unsafe {
            let data = self.data();
            (RBox::vtable(self).destructor())(data, CallReferentDrop::Yes);
        }
    }
}

///////////////////////////////////////////////////////////////

#[derive(StableAbi)]
#[repr(C)]
#[sabi(inside_abi_stable_crate)]
#[sabi(kind(Prefix(prefix_struct="BoxVtable")))]
#[sabi(missing_field(panic))]
pub(crate) struct BoxVtableVal<T> {
    type_id:ReturnValueEquality<UTypeId>,
    #[sabi(last_prefix_field)]
    destructor: unsafe extern "C" fn(*mut T, CallReferentDrop),
}

struct VTableGetter<'a, T>(&'a T);

impl<'a, T: 'a> VTableGetter<'a, T> {
    const DEFAULT_VTABLE:BoxVtableVal<T>=BoxVtableVal{
        type_id:ReturnValueEquality{
            function:new_utypeid::<RBox<()>>
        },
        destructor: destroy_box::<T>,
    };

    // The VTABLE for this type in this executable/library
    const LIB_VTABLE: &'a WithMetadata<BoxVtableVal<T>> = 
        &WithMetadata::new(PrefixTypeTrait::METADATA,Self::DEFAULT_VTABLE);

    #[cfg(test)]
    const LIB_VTABLE_FOR_TESTING: &'a WithMetadata<BoxVtableVal<T>> = 
        &WithMetadata::new(
            PrefixTypeTrait::METADATA,
            BoxVtableVal {
                type_id:ReturnValueEquality{
                    function: new_utypeid::<RBox<i32>>
                },
                ..Self::DEFAULT_VTABLE
            }
        );
}

unsafe extern "C" fn destroy_box<T>(v: *mut T, call_drop: CallReferentDrop) {
    extern_fn_panic_handling! {
        let mut box_ = Box::from_raw(v as *mut ManuallyDrop<T>);
        if call_drop == CallReferentDrop::Yes {
            ManuallyDrop::drop(&mut *box_);
        }
        drop(box_);
    }
}

/////////////////////////////////////////////////////////////////