Examples
A Read-like trait implemented to better support uninitialized memory.
# use std::io;
use std::mem::MaybeUninit;
use uninit_tools::buffer::{Buffer, BufferRef};
use uninit_tools::traits::Initialize;
#
pub trait MyRead {
fn read<'buffer, T>(&mut self, buffer: BufferRef<'buffer, T>) -> io::Result<()>
where
T: Initialize<Item = u8>,
;
}
impl MyRead for &[u8] {
fn read<'buffer, T>(&mut self, mut buffer: BufferRef<'buffer, T>) -> io::Result<()>
where
T: Initialize<Item = u8>,
{
let min = std::cmp::min(self.len(), buffer.remaining());
buffer.append(&self[..min]);
Ok(())
}
}
# fn main() -> io::Result<()> {
let array = [MaybeUninit::uninit(); 32];
let len = array.len();
let mut buf = Buffer::uninit(array);
let original_stupid_text: &[u8] = b"copying is expensive!";
let mut stupid_text = original_stupid_text;
stupid_text.read(buf.by_ref())?;
assert_eq!(buf.remaining(), len - original_stupid_text.len());
# Ok(())
# }
Note that this may not be the best implementation of the Read trait, but it does show that
uninitialized memory handling can be done entirely in safe code, being moderately ergonomic.
(If this would be incorporated into std::io::Read, there would probably be a simpler unsafe
function, that defaults to the safer wrapper.)