Crate uninit_buffers

Crate uninit_buffers 

Source
Expand description

This crate aims to fill a hole in the currently-unstable MaybeUninit slice-filling API: there is a safe way to fill a slice, but there is no safe way to drop elements of the slice. For this purpose, we introduce a wrapper type, Initialized, which will drop the initialized elements when it goes out of scope.

Regarding safety, we treat the Initialized structure as if it owns the elements that are filled. It is instantiated by using the SliceExt trait, which is implemented on all MaybeUninit slices.

§Usage

This crate is on crates.io and can be used by executing cargo add uninit_buffers or by adding the following to the dependencies in your Cargo.toml file.

[dependencies]
uninit_buffers = "0.1"

From here, you will want to

use uninit_buffers::SliceExt;

This will allow you to write into any MaybeUninit slices.

§Examples

§Fill a buffer from an iterator.

use std::mem::MaybeUninit;
use uninit_buffers::SliceExt;

let mut buf = [const { MaybeUninit::uninit() }; 8];

let original = ["fundamental", "theorem", "of", "calculus"].as_ref();
// strings are allocated in to_owned
let iter = original.iter().map(ToOwned::to_owned);
let (initialized, remainder) = buf.write_iter_owned(iter);

assert_eq!(&*initialized, original);
assert_eq!(remainder.len(), 4);

// this will drop the created strings. no need for unsafe!
drop(initialized);

§Fill a byte buffer from an input stream.

use std::io::Read;
use std::mem::MaybeUninit;

use uninit_buffers::SliceExt;

let input = /* <omitted> */
let mut buf = [const { MaybeUninit::uninit() }; 2048];

let (read_data, _) = buf.try_write_iter_owned(input.bytes())?;

println!("read {} bytes.", read_data.len());

For more examples, see the documentation of the methods of the SliceExt trait.

Structs§

Initialized
This structure owns initialized data contained in a slice of MaybeUninit. To obtain one, use the SliceExt trait, which is automatically implemented on slices of MaybeUninit.
IntoIter
An iterator that moves out of Initialized.

Traits§

SliceExt
This trait implements methods to construct initialized data on a MaybeUninit buffer. It mimics the (currently unstable) API in the standard library. The implementation and documentation are near-identical copies for all but the try_write_iter_owned method.