Skip to main content

multiversx_sc/types/managed/
managed_type_trait.rs

1use crate::api::{HandleConstraints, ManagedTypeApi, RawHandle};
2
3use super::ManagedRef;
4
5/// Commonalities between all managed types.
6pub trait ManagedType<M: ManagedTypeApi>: Sized {
7    type OwnHandle: HandleConstraints;
8
9    #[doc(hidden)]
10    unsafe fn from_handle(handle: Self::OwnHandle) -> Self;
11
12    fn get_handle(&self) -> Self::OwnHandle;
13
14    /// Forgets current object (does not run destructor), but extracts the handle.
15    ///
16    /// The handle remains an owned object, so the handle's destructor will run later, when dropped.
17    ///
18    /// ## Safety
19    ///
20    /// Destructures the object, without running a constructor.
21    ///
22    /// To avoid a memory leak, it is necessary for the object to be later
23    /// reconstructed from handle and its destructor run.
24    ///
25    /// It is designed to be used ManagedVec and ManagedOption,
26    /// where items are dropped later, together with their container.
27    unsafe fn forget_into_handle(self) -> Self::OwnHandle;
28
29    #[doc(hidden)]
30    unsafe fn from_raw_handle(handle: RawHandle) -> Self {
31        unsafe { Self::from_handle(Self::OwnHandle::new(handle)) }
32    }
33
34    fn get_raw_handle(&self) -> RawHandle {
35        self.get_handle().cast_or_signal_error::<M, _>()
36    }
37
38    fn get_raw_handle_unchecked(&self) -> RawHandle {
39        self.get_handle().get_raw_handle_unchecked()
40    }
41
42    /// Implement carefully, since the underlying transmutation is an unsafe operation.
43    /// For types that wrap a handle to some VM-managed data,
44    /// make sure the type only contains the handle (plus ZSTs if necessary).
45    /// For types that just wrap another managed type it is easier, call for the wrapped object.
46    fn transmute_from_handle_ref(handle_ref: &Self::OwnHandle) -> &Self;
47
48    fn transmute_from_handle_ref_mut(handle_ref: &mut Self::OwnHandle) -> &mut Self;
49
50    fn as_ref(&self) -> ManagedRef<'_, M, Self> {
51        ManagedRef::new(self)
52    }
53}