[][src]Struct uninit::out_ref::Out

#[repr(transparent)]pub struct Out<'out, T: 'out + ?Sized>(_, _);

Wrapper expressing the semantics of &out T references

In other words, this has the semantics of &'out mut MaybeUninit<T> but for the ability to write garbage (MaybeUninit::uninit()) into it (else coercing &mut T to &out T = Out<T> would be unsound).

This means that the reference may point to uninitialized memory (or not), and thus that writes to the pointee will not call the .drop() destructor.

This type can be trivially constructed from:

  • a &'out mut MaybeUninit<T> (main point of the type),

  • a &'out mut T (to keep the ergonomics of being able to overwrite an already initialized value).

    • To avoid "accidentally" leaking memory in this second case, either T must be Copy (sufficient condition to prove there is no drop glue), or you must first call .manually_drop_mut() before the .as_out() "coercion".

Implementations

impl<'out, T: 'out + ?Sized> Out<'out, T>[src]

pub fn reborrow<'reborrow>(
    self: &'reborrow mut Out<'out, T>
) -> Out<'reborrow, T> where
    'out: 'reborrow, 
[src]

Reborrows the &out _ reference for a shorter lifetime.

pub fn r<'reborrow>(self: &'reborrow mut Out<'out, T>) -> Out<'reborrow, T> where
    'out: 'reborrow, 
[src]

Shorthand for .reborrow().

impl<'out, T: 'out> Out<'out, T>[src]

pub fn write(self: Out<'out, T>, value: T) -> &'out mut T[src]

Write a value into the pointee, returning an .assume_init()-ed reference to it.

Guarantees (that unsafe code may rely on)

After the function returns, the pointee is guaranteed to have been initialized; it is thus sound to use that property to manually assume_init() it or any chunk of such items.

pub fn replace(self: Out<'out, T>, value: T) -> (MaybeUninit<T>, &'out mut T)[src]

Similar to .write(), but getting the previous value back. Such previous value may or may not be initialized.

Guarantees (that unsafe code may rely on)

  • After the function returns, the pointee is guaranteed to have been initialized; it is thus sound to use that property to manually assume_init() it or any chunk of such items.

  • there is no such guarantee regarding the previous value, which is thus only sound to assume_init() if the pointee already was (before the call to .replace()).

pub fn as_mut_ptr(self: &mut Out<'out, T>) -> *mut T[src]

Returns a raw mutable pointer to the pointee.

Guarantees (that unsafe code may rely on)

  • The returned pointer does point to the pointee, meaning that if such returned pointer is used to .write() to the pointee, then it is safe to assume_init() it.

  • The returned pointer is non null, well-aligned, and writeable.

    It is also technically readable:

    • you can read a MaybeUninit<T> out of it after .cast()ing it,

    • otherwise, except when sound to assume_init(), the obtained pointer cannot be used to read the value : T of the pointee!

pub unsafe fn assume_init(self: Out<'out, T>) -> &'out mut T[src]

Upgrades the &out _ (write-only) reference to a read-writeable &mut _.

Safety

Don't be lured by the &mut reference: Rust validity invariants imply that an &mut reference is only sound to produce if it points to an initialized value; it is otherwise instant UB. See MaybeUninit::assume_init for more info about it. Thus:

  • The pointee must have been initialized.

This is a validity invariant, meaning that UB does happen from just calling that function to produce an ill-formed reference, even if the obtained reference is "never actually used".

Counterexample

The following program exhibits Undefined Behavior:

use ::uninit::prelude::*;

let mut x = MaybeUninit::uninit();
let _unused: &mut u8 = unsafe {
    x   .as_out()
        .assume_init() // UB!
};

pub unsafe fn as_mut_uninit(self: Out<'out, T>) -> &'out mut MaybeUninit<T>[src]

Upgrades the &out _ (write-valid-values-only) reference to a &mut MaybeUninit<_> (write-anything) reference.

Safety

  • The obtained reference cannot be used to write garbage (MaybeUninit::uninit()) into the pointee.

    This means that it can thus not be fed to opaque APIs!!

  • Exception: if the given &out reference has originated from a &mut MaybeUninit<_>, then calling .as_mut_uninit() is a sound way to make the trip back.

This is a safety invariant (i.e., even if it is never "instant" UB to produce such a value, it does break the safety invariant of &mut MaybeUninit<_> (that of being allowed to write MaybeUninit::uninit() garbage into the pointee), so UB can happen afterwards). This is different than .assume_init() soundness relying on a validity invariant, meaning that UB does happen from just calling that function to produce an ill-formed reference, even if the obtained reference is never actually used.

Counter-example

The following code is Undefined Behavior:

use ::uninit::prelude::*;

let mut my_box = Box::new(42);
let at_my_box: Out<'_, Box<i32>> =
    my_box
        .manually_drop_mut()
        .as_out()
;
// Overwrite `my_box` with uninitialized bytes / garbage content.
unsafe {
    *at_my_box.as_mut_uninit() = MaybeUninit::uninit();
}
// Runs the destructor for a `Box<i32>` using a garbage pointer that
// may thus point anywhere in memory!
drop(my_box)

A function from an external library must always be seen as opaque (unless its documentation makes implementation-detail guarantees, such as this very crate does), so one cannot rely on its implementation (unless the lib is open source AND you pin-point to that version of the crate, either through version = "=x.y.z" or through git = ..., rev = ... in Cargo.toml).

This example is not tested
// `fn zeroize (out: &'_ mut MaybeUninit<u8>) -> &'_ mut u8;`
// The author of the crate says it uses that `out` reference to write
// `0` to the pointee.
use ::some_lib::zeroize;

let mut x = 42;
let at_x = x.as_out();
// Unsound! The lib implementation is free to write
// `MaybeUninit::uninit()` garbage to the pointee!
zeroize(unsafe { at_x.as_mut_uninit() });

impl<'out, T: 'out> Out<'out, [T]>[src]

pub fn from_out(out: Out<'out, T>) -> Out<'out, [T]>[src]

Converts a single item out reference into a 1-long out slice.

This is the &out version of slice::from_ref and slice::from_mut.

pub fn as_ptr(&self) -> *const T[src]

Obtains a read-only non-NULL and well-aligned raw pointer to a potentially uninitialized T.

Unless maybe with interior mutability through raw pointers, there is no case where using this function is more useful than going through <[MaybeUninit<_>]>::assume_init_by_ref().

Worse, the lack of unsafe-ty of the method (ignoring the one needed to use the pointer) and its "boring" name may lead to code read-dereferencing the pointer (which implicitly assume_init()s it) without having ensured the soundness of such (implicit) assume_init().

pub fn as_mut_ptr(&mut self) -> *mut T[src]

Returns a raw mutable pointer to the pointee.

See Out::as_mut_ptr for more info regarding safety and guarantees.

pub unsafe fn as_mut_uninit(self: Out<'out, [T]>) -> &'out mut [MaybeUninit<T>][src]

Upgrades the &out _ (write-valid-values-only) reference to a &mut MaybeUninit<_> (write-anything) reference.

See Out::as_mut_uninit for more info regarding safety.

pub fn get_out<Index>(self: Out<'out, [T]>, idx: Index) -> Option<Index::Output> where
    Index: UsizeOrRange<'out, T>, 
[src]

Main indexing operation on an &out [_].

The type Index of idx may be:

  • a usize, and then Index::Output is a Out<T> reference to a single element.

  • a Range<usize> (e.g., a .. b), and then Index::Output is a Out<[T]> reference to a subslice.

Example

use ::uninit::prelude::*;

let src: &[u8] = b"Hello, World!";
// Stack-allocate an uninitialized buffer.
let mut buf = uninit_array![u8; 256];
// copy `src` into this stack allocated buffer, effectively initializing it.
let buf: &mut [u8] =
    // buf[.. src.len()].as_out()
    buf.as_out().get_out(.. src.len()).unwrap()
        .copy_from_slice(src)
;
assert_eq!(buf, b"Hello, World!");
buf[7 ..].copy_from_slice(b"Earth!");
assert_eq!(buf, b"Hello, Earth!");

pub unsafe fn get_unchecked_out<Index>(
    self: Out<'out, [T]>,
    idx: Index
) -> Index::Output where
    Index: UsizeOrRange<'out, T>, 
[src]

Same as .get_out(), but with the bound check being elided.

Safety

The given idx mut be in bounds:

  • if idx: usize, then idx must be < self.len().

  • if idx is an upper-bounded range (e.g., .. b, a ..= b), then the upper bound (b in the example) must be < self.len().

  • etc.

See .get_unchecked_mut() for more info about the safety of such call.

pub fn as_uninit(self: Out<'out, [T]>) -> &'out [MaybeUninit<T>][src]

Downgrades the Out<'_, [T]> slice into a &'_ [MaybeUninit<T>].

This leads to a read-only1 "unreadable" slice which is thus only useful for accessing &'_ [] metadata, mainly the length of the slice.

In practice, calling this function explicitely is not even needed given that Out<'_, [T]> : Deref<Target = [MaybeUninit<T>], so one can do:

use ::uninit::prelude::*;

let mut backing_array = uninit_array![_; 42];
let buf: Out<'_, [u8]> = backing_array.as_out();
assert_eq!(buf.len(), 42); // no need to `.r().as_uninit()`

1 Unless Interior Mutability is involved; speaking of which:

Interior Mutability

The whole design of Out references is to forbid any non-unsafe API that would allow writing MaybeUninit::uninit() garbage into the pointee. So, for instance, this crate does not offer any API like:

use ::core::{cell::Cell, mem::MaybeUninit};

// /!\ This is UNSOUND when combined with the `::uninit` crate!
fn swap_mb_uninit_and_cell<T> (
    p: &'_ MaybeUninit<Cell<T>>,
) -> &'_ Cell<MaybeUninit<T>>
{
    unsafe {
        // Safety: both `Cell` and `MaybeUninit` are `#[repr(transparent)]`
        ::core::mem::transmute(p)
    }
}

Indeed, if both such non-unsafe API and the uninit crate were present, then one could trigger UB with:

This example is not tested
let mut x = [Cell::new(42)];
let at_mb_uninit_cell: &'_ MaybeUninit<Cell<u8>> =
    &x.as_out().as_uninit()[0]
;
swap_mb_uninit_and_cell(at_mb_uninit_cell)
    .set(MaybeUninit::uninit()) // UB!
;

The author of the crate believes that such UB is the responsibility of the one who defined swap_mb_uninit_and_cell, and that in general that function is unsound: MaybeUninit-ness and interior mutability do not commute!

  • the Safety annotation in the given example only justifies that it is not breaking any layout-based validity invariants, but it is actually impossible to semantically prove that it is safe for these properties to commute.

If you are strongly convinced of the opposite, please file an issue (if there isn't already one: since this question is not that clear the author is very likely to create an issue themself).

pub unsafe fn assume_all_init(self: Out<'out, [T]>) -> &'out mut [T][src]

Upgrades the &out [_] (write-only) reference to a read-writeable &mut [_].

Safety

Don't be lured by the &mut reference: Rust validity invariants imply that an &mut reference is only sound to produce if it points to initialized values; it is otherwise instant UB. See MaybeUninit::assume_init for more info about it. Thus:

  • The pointee(s) must have been initialized.

This is a validity invariant, meaning that UB does happen from just calling that function to produce an ill-formed reference, even if the obtained reference is "never actually used".

pub fn copy_from_slice(
    self: Out<'out, [T]>,
    source_slice: &[T]
) -> &'out mut [T] where
    T: Copy
[src]

Initialize the buffer with a copy from another (already initialized) buffer.

It returns a read-writable slice to the initialized bytes for convenience (automatically assume_init-ed).

Panic

The function panics if the slices' lengths are not equal.

Guarantees (that unsafe code may rely on)

A non-panic!king return from this function guarantees that the input slice has been (successfully) initialized, and that it is thus then sound to .assume_init().

It also guarantees that the returned slice does correspond to the input slice (e.g., for crate::ReadIntoUninit's safety guarantees).

Example

use ::uninit::prelude::*;

let mut array = uninit_array![_; 13];
assert_eq!(
    array.as_out().copy_from_slice(b"Hello, World!"),
    b"Hello, World!",
);
// we can thus soundly `assume_init` our array:
let array = unsafe {
    mem::transmute::<
        [MaybeUninit<u8>; 13],
        [            u8 ; 13],
    >(array)
};
assert_eq!(
    array,
    *b"Hello, World!",
);

pub fn init_with(
    self: Out<'out, [T]>,
    iterable: impl IntoIterator<Item = T>
) -> &'out mut [T]
[src]

Fills the buffer with values from up to the first self.len() elements of an iterable.

Guarantees (that unsafe code may rely on)

A non-panicking return from this function guarantees that the first k values of the buffer have been initialized and are thus sound to .assume_init(), where k, the numbers of elements that iterable has yielded (capped at self.len()), is the length of the returned buffer.

pub fn iter_out<'reborrow>(
    self: &'reborrow mut Out<'out, [T]>
) -> IterOut<'reborrow, T>

Notable traits for IterOut<'out, T>

impl<'out, T: 'out> Iterator for IterOut<'out, T> type Item = Out<'out, T>;
[src]

.reborrow().into_iter()

pub fn split_at_out(
    self: Out<'out, [T]>,
    idx: usize
) -> (Out<'out, [T]>, Out<'out, [T]>)
[src]

Same as .split_at_mut(), but with &out [_] references.

Panic

Panics if idx > len.

Trait Implementations

impl<'out, T: Debug + 'out + ?Sized> Debug for Out<'out, T>[src]

impl<'out, T: 'out> Default for Out<'out, [T]>[src]

This can be useful to get a Out<'long ...> out of a &'short mut Out<'long ...> by mem::replace-ing with a Out::default() (e.g., to implement an Iterator).

impl<'out, T: 'out> Deref for Out<'out, [T]>[src]

Deref into [MaybeUninit<T>] to get access to the slice length related getters.

type Target = [MaybeUninit<T>]

The resulting type after dereferencing.

impl<'out, T: 'out> From<&'out mut [ManuallyDrop<T>]> for Out<'out, [T]>[src]

impl<'out, T: 'out> From<&'out mut [MaybeUninit<T>]> for Out<'out, [T]>[src]

impl<'out, T: 'out> From<&'out mut [T]> for Out<'out, [T]> where
    T: Copy
[src]

impl<'out, T: 'out> From<&'out mut ManuallyDrop<T>> for Out<'out, T>[src]

For non-Copy types, explicitely transmuting the mut reference into one that points to a ManuallyDrop is required, so as to express how likely it is that memory be leaked. This can be safely achieved by using the ManuallyDropMut helper.

impl<'out, T: 'out> From<&'out mut MaybeUninit<T>> for Out<'out, T>[src]

impl<'out, T: 'out> From<&'out mut T> for Out<'out, T> where
    T: Copy
[src]

impl<'out, T: 'out> IntoIterator for Out<'out, [T]>[src]

type Item = Out<'out, T>

The type of the elements being iterated over.

type IntoIter = IterOut<'out, T>

Which kind of iterator are we turning this into?

impl<'out, 'inner: 'out, T: 'inner> IntoIterator for &'out mut Out<'inner, [T]>[src]

type Item = Out<'out, T>

The type of the elements being iterated over.

type IntoIter = IterOut<'out, T>

Which kind of iterator are we turning this into?

impl<'out, T: ?Sized + 'out> Send for Out<'out, T> where
    &'out mut T: Send
[src]

impl<'out, T: ?Sized + 'out> Sync for Out<'out, T> where
    &'out mut T: Sync
[src]

Auto Trait Implementations

impl<'out, T: ?Sized> RefUnwindSafe for Out<'out, T> where
    T: RefUnwindSafe

impl<'out, T: ?Sized> Unpin for Out<'out, T>

impl<'out, T> !UnwindSafe for Out<'out, T>

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<I> IntoIterator for I where
    I: Iterator
[src]

type Item = <I as Iterator>::Item

The type of the elements being iterated over.

type IntoIter = I

Which kind of iterator are we turning this into?

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.