pub struct UniqueRef<T: ?Sized> { /* private fields */ }
Expand description
A refcounted object that is known to have a refcount of 1.
It is mutable and can be converted to a Ref
so that it can be shared.
Invariants
inner
always has a reference count of 1.
Examples
In the following example, we make changes to the inner object before turning it into a
Ref<Test>
object (after which point, it cannot be mutated directly). Note that x.into()
cannot fail.
use kernel::sync::{Ref, UniqueRef};
struct Example {
a: u32,
b: u32,
}
fn test() -> Result<Ref<Example>> {
let mut x = UniqueRef::try_new(Example { a: 10, b: 20 })?;
x.a += 1;
x.b += 1;
Ok(x.into())
}
In the following example we first allocate memory for a ref-counted Example
but we don’t
initialise it on allocation. We do initialise it later with a call to UniqueRef::write
,
followed by a conversion to Ref<Example>
. This is particularly useful when allocation happens
in one context (e.g., sleepable) and initialisation in another (e.g., atomic):
use kernel::sync::{Ref, UniqueRef};
struct Example {
a: u32,
b: u32,
}
fn test() -> Result<Ref<Example>> {
let x = UniqueRef::try_new_uninit()?;
Ok(x.write(Example { a: 10, b: 20 }).into())
}
In the last example below, the caller gets a pinned instance of Example
while converting to
Ref<Example>
; this is useful in scenarios where one needs a pinned reference during
initialisation, for example, when initialising fields that are wrapped in locks.
use kernel::sync::{Ref, UniqueRef};
struct Example {
a: u32,
b: u32,
}
fn test() -> Result<Ref<Example>> {
let mut pinned = Pin::from(UniqueRef::try_new(Example { a: 10, b: 20 })?);
// We can modify `pinned` because it is `Unpin`.
pinned.as_mut().a += 1;
Ok(pinned.into())
}
Implementations
sourceimpl<T> UniqueRef<T>
impl<T> UniqueRef<T>
sourcepub fn try_new_uninit() -> Result<UniqueRef<MaybeUninit<T>>>
pub fn try_new_uninit() -> Result<UniqueRef<MaybeUninit<T>>>
Tries to allocate a new UniqueRef
instance whose contents are not initialised yet.
Trait Implementations
Auto Trait Implementations
impl<T> !RefUnwindSafe for UniqueRef<T>
impl<T: ?Sized> Send for UniqueRef<T> where
T: Send + Sync,
impl<T: ?Sized> Sync for UniqueRef<T> where
T: Send + Sync,
impl<T: ?Sized> Unpin for UniqueRef<T> where
T: Unpin,
impl<T> !UnwindSafe for UniqueRef<T>
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more