abi_stable::pointer_trait

Trait AsPtr

Source
pub unsafe trait AsPtr: GetPointerKind {
    // Required method
    fn as_ptr(&self) -> *const Self::PtrTarget;

    // Provided method
    fn as_rref(&self) -> RRef<'_, Self::PtrTarget> { ... }
}
Expand description

For getting a const raw pointer to the value that this points to.

§Safety

The implementor of this trait must return a pointer to the same data as Deref::deref, without constructing a &Self::Target in as_ptr (or any function it calls),

The implementor of this trait must not override the defaulted methods.

§Example

use abi_stable::{
    erased_types::interfaces::DebugDefEqInterface,
    pointer_trait::{
        PK_Reference,
        AsPtr, CanTransmuteElement, GetPointerKind, TransmuteElement,
    },
    sabi_types::StaticRef,
    DynTrait,
};

fn main() {
    let reff: DynTrait<BarRef<()>, DebugDefEqInterface> =
        DynTrait::from_ptr(BarRef::new(&1234i32));
     
    assert_eq!(format!("{:?}", reff), "1234");
}


#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
struct BarRef<T>(StaticRef<T>);

impl<T: 'static> BarRef<T> {
    pub const fn new(reff: &'static T) -> Self {
        Self(StaticRef::new(reff))
    }
}

unsafe impl<T: 'static> GetPointerKind for BarRef<T> {
    type PtrTarget = T;
    type Kind = PK_Reference;
}

unsafe impl<T, U> CanTransmuteElement<U> for BarRef<T>
where
    T: 'static,
    U: 'static,
{
    type TransmutedPtr = BarRef<U>;
     
    unsafe fn transmute_element_(self) -> Self::TransmutedPtr {
        BarRef(self.0.transmute_element_())
    }
}

unsafe impl<T: 'static> AsPtr for BarRef<T> {
    fn as_ptr(&self) -> *const T {
        self.0.as_ptr()
    }
}

Required Methods§

Source

fn as_ptr(&self) -> *const Self::PtrTarget

Gets a const raw pointer to the value that this points to.

Provided Methods§

Source

fn as_rref(&self) -> RRef<'_, Self::PtrTarget>

Converts this pointer to an RRef.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<'a, T> AsPtr for RMut<'a, T>

Source§

impl<T> AsPtr for RRef<'_, T>

Source§

impl<T> AsPtr for StaticRef<T>

Source§

impl<T> AsPtr for RArc<T>

Source§

impl<T> AsPtr for RBox<T>

Source§

impl<T, Inline> AsPtr for RSmallBox<T, Inline>