Struct abi_stable::sabi_types::RRef[][src]

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

Equivalent to &'a T, which allows a few more operations without causing Undefined Behavior.

Purpose

This type is used as the &self parameter in abi_stable trait objects because it can be soundly transmuted to point to other smaller but compatible types, then back to the original type.

This crate is tested with miri to detect bugs in unsafe code, which implements the Stacked Borrows model. Because that model forbids &T to &() to &T transmutes (when T isn’t zero-sized), it required defining RRef to allow a reference-like type that can be transmuted.

Example

This example demonstrates how a simple &dyn Any-like type can be implemented.

use abi_stable::{
    marker_type::ErasedObject,
    std_types::UTypeId,
    RRef,
};
 
fn main(){ 
    let value = WithTypeId::new(5u32);
    let erased = value.erase();
 
    assert_eq!(WithTypeId::downcast::<i32>(erased), None);
    assert_eq!(WithTypeId::downcast::<bool>(erased), None);
    assert_eq!(WithTypeId::downcast::<u32>(erased), Some(&value));
}
 
// `#[repr(C))]` with a trailing `T` field is required for soundly transmuting from 
// `RRef<'a, WithTypeId<T>>` to `RRef<'a, WithTypeId<ErasedObject>>`.
#[repr(C)]
#[derive(Debug, PartialEq)]
struct WithTypeId<T>{
    type_id: UTypeId,
    value: T,
}
 
impl<T> WithTypeId<T> {
    pub fn new(value: T) -> Self
    where
        T: 'static
    {
        Self{
            type_id: UTypeId::new::<T>(),
            value,
        }
    }
 
    pub fn erase(&self) -> RRef<'_, WithTypeId<ErasedObject>> {
        unsafe{ RRef::new(self).transmute::<WithTypeId<ErasedObject>>() }
    }
}
 
impl WithTypeId<ErasedObject> {
    pub fn downcast<T>(this: RRef<'_, Self>) -> Option<&WithTypeId<T>> 
    where
        T: 'static
    {
        if this.get().type_id == UTypeId::new::<T>() {
            // safety: we checked that type parameter was `T`
            unsafe{ Some(this.transmute_into_ref::<WithTypeId<T>>()) }
        } else {
            None
        }
    }
}
 
 

Type Prefix

A type parameter U is considered a prefix of T in all of these cases:

  • U is a zero-sized type with an alignment equal or lower than T

  • U is a #[repr(transparent)] wrapper over T

  • U and T are both #[repr(C)] structs, in which T starts with the fields of U in the same order, and U has an alignment equal to or lower than T.

Please note that it can be unsound to transmute a non-local type if it has private fields, since it may assume it was constructed in a particular way.

Implementations

Constructs this RRef from a reference.

Example

use abi_stable::sabi_types::RRef;

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

impl<'a,T:'a> GetPtr<'a,T>{
    const REF:&'a Option<T>=&None;

    const STATIC:RRef<'a,Option<T>>=
        RRef::new(Self::REF);
}

Constructs this RRef from a raw pointer.

Safety

You must ensure that the raw pointer is valid for the 'a lifetime, and points to a fully initialized and aligned T.

Example

use abi_stable::sabi_types::RRef;

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

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

    const STATIC:RRef<'a,Option<T>>=unsafe{
        RRef::from_raw(Self::PTR)
    };
}

Casts this to an equivalent reference.

Example

use abi_stable::RRef;
 
let rref = RRef::new(&89);
 
assert_eq!(rref.get(), &89);
 

Copies the value that this points to.

Example

use abi_stable::RRef;
 
let rref = RRef::new(&55);
 
assert_eq!(rref.get_copy(), 55);
 

Casts this to an equivalent raw pointer.

Example

use abi_stable::RRef;
 
let rref = RRef::new(&89);
 
unsafe{
    assert_eq!(*rref.as_ptr(), 89);
}

Transmutes this RRef<'a,T> to a RRef<'a,U>.

Safety

Either of these must be the case:

Example

use abi_stable::RRef;

use std::num::Wrapping;

let rref = RRef::new(&13u32);

// safety: Wrapping is a `#[repr(transparent)]` wrapper with one `pub` field.
let trans = unsafe{ rref.transmute::<Wrapping<u32>>() };
 
assert_eq!(trans, RRef::new(&Wrapping(13u32)));
 

Transmutes this to a raw pointer pointing to a different type.

Transmutes this to a reference pointing to a different type.

Safety

Either of these must be the case:

Example

use abi_stable::{
    RRef,
    std_types::Tuple2,
};

unsafe{
    let reff = RRef::new(&Tuple2(3u32, 5u64));
    assert_eq!(reff.transmute_into_ref::<u32>(), &3u32);
}

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

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.