Struct abi_stable::sabi_types::StaticRef[][src]

#[repr(transparent)]
pub struct StaticRef<T> { /* fields omitted */ }
Expand description

A wrapper type for vtable static references, and other constants that have non-'static generic parameters but are safe to reference for the lifetime of T.

Purpose

This type is necessary because Rust doesn’t understand that vtables live for 'static, even though they have non-'static type parameters.

Example

This defines a non-extensible vtable,using a StaticRef as the pointer to the vtable.

use abi_stable::{
    marker_type::ErasedObject,
    prefix_type::{PrefixTypeTrait,WithMetadata},
    sabi_types::StaticRef,
    StableAbi,
    sabi_extern_fn,
    staticref,
};

use std::{
    marker::PhantomData,
    ops::Deref,
};

fn main(){
    let boxed = BoxLike::new("foo".to_string());
    assert_eq!(boxed.as_str(), "foo");
}

/// An ffi-safe `Box<T>`
#[repr(C)]
#[derive(StableAbi)]
pub struct BoxLike<T> {
    data: *mut T,
    
    vtable: StaticRef<VTable<T>>,

    _marker: PhantomData<T>,
}

impl<T> BoxLike<T> {
    pub fn new(value: T) -> Self {
        Self{
            data: Box::into_raw(Box::new(value)),
            vtable: VTable::<T>::VTABLE,
            _marker: PhantomData,
        }
    }
}

impl<T> Drop for BoxLike<T> {
    fn drop(&mut self){
        unsafe{
            (self.vtable.drop_)(self.data);
        }
    }
}

impl<T> Deref for BoxLike<T> {
    type Target = T;

    fn deref(&self) -> &T {
        unsafe{
            &*self.data
        }
    }
}

#[repr(C)]
#[derive(StableAbi)]
pub struct VTable<T>{
    drop_:unsafe extern "C" fn(*mut T),
}

impl<T> VTable<T> {
    // The `staticref` macro declares a `StaticRef<VTable<T>>` constant.
    staticref!(const VTABLE: Self = Self{
        drop_: drop_box::<T>,
    });
}


#[sabi_extern_fn]
unsafe fn drop_box<T>(object: *mut T){
    drop(Box::from_raw(object));
}

Implementations

Constructs a PrefixRef<P> from self.

This is most useful when you have a generic type that isn’t 'static for type system reasons, but lives for the entire program.

Example

use abi_stable::{
    for_examples::{Module, Module_Ref},
    prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata},
    std_types::{RNone, RStr},
    staticref,
};
 
// The `staticref` invocation here declares a `StaticRef<WithMetadata<Module>>` constant.
const WITH_META: &WithMetadata<Module> = &WithMetadata::new(
    PrefixTypeTrait::METADATA,
    Module {
        first: RNone,
        second: RStr::from_str("hello"),
        third: 100,
    },
);
 
const MOD: Module_Ref = Module_Ref(WITH_META.static_as_prefix());
 
assert_eq!(MOD.first(), RNone);
assert_eq!(MOD.second().as_str(), "hello");
 

Constructs this StaticRef from a raw pointer.

Safety

You must ensure that the raw pointer is valid for the entire program’s lifetime.

Example

use abi_stable::sabi_types::StaticRef;

struct GetPtr<T>(T);

impl<T> GetPtr<T>{
    const PTR:*const Option<T>=&None;

    const STATIC:StaticRef<Option<T>>=unsafe{
        StaticRef::from_raw(Self::PTR)
    };
}

Constructs this StaticRef from a static reference

This implicitly requires that T:'static.

Example

use abi_stable::sabi_types::StaticRef;

struct GetPtr<T>(T);

impl<T> GetPtr<T>
where
    T:'static
{
    const REF:&'static Option<T>=&None;

    const STATIC:StaticRef<Option<T>>=
        StaticRef::new(Self::REF);
}

Creates a StaticRef by heap allocating and leaking val.

Gets access to the reference.

This returns &'a T instead of &'static T to support vtables of non-'static types.

Example

use abi_stable::sabi_types::StaticRef;

struct GetPtr<T>(T);

impl<T> GetPtr<T>{
    const PTR:*const Option<T>=&None;

    const STATIC:StaticRef<Option<T>>=unsafe{
        StaticRef::from_raw(Self::PTR)
    };
}

let reference:&'static Option<String>=
    GetPtr::<String>::STATIC.get();

Gets access to the referenced value,as a raw pointer.

Example

use abi_stable::sabi_types::StaticRef;
use std::convert::Infallible;

struct GetPtr<T>(T);

impl<T> GetPtr<T>{
    const PTR:*const Option<T>=&None;

    const STATIC:StaticRef<Option<T>>=unsafe{
        StaticRef::from_raw(Self::PTR)
    };
}

let reference:*const Option<Infallible>=
    GetPtr::<Infallible>::STATIC.as_ptr();

Transmutes this StaticRef<T> to a StaticRef<U>.

Safety

StaticRef has the same rules that references have regarding transmuting from one type to another:

Example

use abi_stable::sabi_types::StaticRef;

struct GetPtr<T>(T);

impl<T> GetPtr<T>{
    const PTR:*const Option<T>=&None;

    const STATIC:StaticRef<Option<T>>=unsafe{
        StaticRef::from_raw(Self::PTR)
    };
}

let reference:StaticRef<Option<[();0xFFF_FFFF]>>=unsafe{
    GetPtr::<()>::STATIC
        .transmute::<Option<[();0xFFF_FFFF]>>()
};

Trait Implementations

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

Converts this pointer to an RRef.

The type of the pointer after it’s element type has been changed.

Transmutes the element type of this pointer.. Read more

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

The resulting type after dereferencing.

Dereferences the value.

Formats the value using the given formatter. Read more

The kind of the pointer.

What this pointer points to, if the type implements std::ops::Deref it must be the same as <Self as Deref>::Target. Read more

The kind of the pointer.

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

This method returns an Ordering between self and other. Read more

Compares and returns the maximum of two values. Read more

Compares and returns the minimum of two values. Read more

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method returns an ordering between self and other values if one exists. Read more

This method tests less than (for self and other) and is used by the < operator. Read more

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

This method tests greater than (for self and other) and is used by the > operator. Read more

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Whether this type has a single invalid bit-pattern. Read more

The layout of the type provided by implementors.

const-equivalents of the associated types.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

The owned type, stored in RCow::Owned

The borrowed type, stored in RCow::Borrowed

Performs the conversion.

This is always WithMetadata_<Self, Self>

Performs the conversion.

Gets a reference to a field, determined by offset. Read more

Gets a muatble reference to a field, determined by offset. Read more

Gets a const pointer to a field, the field is determined by offset. Read more

Gets a mutable pointer to a field, determined by offset. Read more

Replaces a field (determined by offset) with value, returning the previous value of the field. Read more

Swaps a field (determined by offset) with the same field in right. Read more

Gets a copy of a field (determined by offset). The field is determined by offset. Read more

Replaces a field (determined by offset) with value, returning the previous value of the field. Read more

Swaps a field (determined by offset) with the same field in right. Read more

Gets a copy of a field (determined by offset). The field is determined by offset. Read more

Compares the address of self with the address of other. Read more

Emulates the pipeline operator, allowing method syntax in more places. Read more

The same as piped except that the function takes &Self Useful for functions that take &Self instead of Self. Read more

The same as piped, except that the function takes &mut Self. Useful for functions that take &mut Self instead of Self. Read more

Mutates self using a closure taking self by mutable reference, passing it along the method chain. Read more

Observes the value of self, passing it along unmodified. Useful in long method chains. Read more

Performs a conversion with Into. using the turbofish .into_::<_>() syntax. Read more

Performs a reference to reference conversion with AsRef, using the turbofish .as_ref_::<_>() syntax. Read more

Performs a mutable reference to mutable reference conversion with AsMut, using the turbofish .as_mut_::<_>() syntax. Read more

Drops self using method notation. Alternative to std::mem::drop. Read more

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

Converts the given value to a String. Read more

Transmutes the element type of this pointer.. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

This is always Self.

Converts a value back to the original type.

Converts a reference back to the original type.

Converts a mutable reference back to the original type.

Converts a box back to the original type.

Converts an Arc back to the original type. Read more

Converts an Rc back to the original type. Read more

Converts a value back to the original type.

Converts a reference back to the original type.

Converts a mutable reference back to the original type.

Converts a box back to the original type.

Converts an Arc back to the original type.

Converts an Rc back to the original type.