symbolic_common

Struct SelfCell

Source
pub struct SelfCell<O, D>
where O: StableDeref,
{ /* private fields */ }
Expand description

A container carrying a derived object alongside its owner.

Warning: This is an inherently unsafe type that builds on top of StableDeref and AsSelf to establish somewhat safe memory semantics. Always try to avoid self-references by storing data in an outer scope or avoiding the need alltogether, first.

SelfCell stores an owner object that must implement StableDeref. This guarantees that the reference pointed to by the dependent object never moves over the lifetime of this object. This is already implemented for most heap-allocating types, like Box, Rc, Arc or ByteView.

Additionally, the dependent object must implement AsSelf. This guarantees that the borrow’s lifetime and its lifetime bounds never exceed the lifetime of the owner. As such, an object Foo<'a> that borrows data from the owner, will be coerced down to Foo<'self> when borrowing. There are two constructor functions, new and try_new, each of which are passed a pointer to the owned data. Dereferencing this pointer is intentionally unsafe, and beware that a borrow of that pointer must not leave the callback.

While it is possible to store derived references in a SelfCell, too, there are simpler alternatives, such as owning_ref::OwningRef. Consider using such types before using SelfCell.

§Example

use symbolic_common::{AsSelf, SelfCell};

struct Foo<'a>(&'a str);

impl<'slf> AsSelf<'slf> for Foo<'_> {
    type Ref = Foo<'slf>;

    fn as_self(&'slf self) -> &Self::Ref {
        self
    }
}

let owner = String::from("hello world");
let cell = SelfCell::new(owner, |s| Foo(unsafe { &*s }));
assert_eq!(cell.get().0, "hello world");

Implementations§

Source§

impl<'slf, O, T> SelfCell<O, T>
where O: StableDeref + 'slf, T: AsSelf<'slf>,

Source

pub fn new<F>(owner: O, derive: F) -> Self
where F: FnOnce(*const <O as Deref>::Target) -> T,

Creates a new SelfCell.

§Safety

The callback receives a pointer to the owned data. Dereferencing the pointer is unsafe. Note that a borrow to that data can only safely be used to derive the object and must not leave the callback.

§Example
use symbolic_common::SelfCell;

let owner = String::from("hello world");
let cell = SelfCell::new(owner, |s| unsafe { &*s });
Source

pub fn try_new<E, F>(owner: O, derive: F) -> Result<Self, E>
where F: FnOnce(*const <O as Deref>::Target) -> Result<T, E>,

Creates a new SelfCell which may fail to construct.

§Safety

The callback receives a pointer to the owned data. Dereferencing the pointer is unsafe. Note that a borrow to that data can only safely be used to derive the object and must not leave the callback.

§Example
use symbolic_common::SelfCell;

fn main() -> Result<(), std::str::Utf8Error> {
    let owner = Vec::from("hello world");
    let cell = SelfCell::try_new(owner, |s| unsafe { std::str::from_utf8(&*s) })?;
    Ok(())
}
Source

pub unsafe fn from_raw(owner: O, derived: T) -> Self

Unsafely creates a new SelfCell from a derived object by moving the owner.

§Safety

This is an inherently unsafe process. The caller must guarantee that the derived object only borrows from the owner that is moved into this container and the borrowed reference has a stable address. This is useful, when cloning the owner by deriving a sub-object.

§Example
use std::sync::Arc;
use symbolic_common::{AsSelf, SelfCell};

struct Foo<'a>(&'a str);

impl<'slf> AsSelf<'slf> for Foo<'_> {
    type Ref = Foo<'slf>;

    fn as_self(&'slf self) -> &Self::Ref {
        self
    }
}

// Create a clonable owner and move it into cell
let owner = Arc::<str>::from("  hello  ");
let cell = SelfCell::new(owner, |s| Foo(unsafe { &*s }));

// Create a second derived object and clone the owner
let trimmed = Foo(cell.get().0.trim());
let cell2 = unsafe { SelfCell::from_raw(cell.owner().clone(), trimmed) };

// Now, drop the original cell and continue using the clone
assert_eq!(cell2.get().0, "hello");
Source

pub fn owner(&self) -> &O

Returns a reference to the owner of this cell.

§Example
use symbolic_common::SelfCell;

let owner = String::from("  hello  ");
let cell = SelfCell::new(owner, |s| unsafe { (*s).trim() });
assert_eq!(cell.owner(), "  hello  ");
Source

pub fn get(&'slf self) -> &'slf <T as AsSelf<'slf>>::Ref

Returns a safe reference to the derived object in this cell.

§Example
use symbolic_common::SelfCell;

let owner = String::from("  hello  ");
let cell = SelfCell::new(owner, |s| unsafe { (*s).trim() });
assert_eq!(cell.get(), "hello");

Trait Implementations§

Source§

impl<O, D: Clone> Clone for SelfCell<O, D>
where O: StableDeref + Clone,

Source§

fn clone(&self) -> SelfCell<O, D>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<O, D: Debug> Debug for SelfCell<O, D>
where O: StableDeref + Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<O, D> Freeze for SelfCell<O, D>
where O: Freeze, D: Freeze,

§

impl<O, D> RefUnwindSafe for SelfCell<O, D>

§

impl<O, D> Send for SelfCell<O, D>
where O: Send, D: Send,

§

impl<O, D> Sync for SelfCell<O, D>
where O: Sync, D: Sync,

§

impl<O, D> Unpin for SelfCell<O, D>
where O: Unpin, D: Unpin,

§

impl<O, D> UnwindSafe for SelfCell<O, D>
where O: UnwindSafe, D: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

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

fn clone_into(&self, target: &mut T)

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

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.