Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Review of array initialization
I have a trait to deserialize data from a little endian byte stream:
impl<T, const SIZE: usize> FromLeStream for [T; SIZE]
where
T: FromLeStream,
{
fn from_le_stream<I>(mut bytes: I) -> Option<Self>
where
I: Iterator<Item = u8>,
{
let mut array = [const { MaybeUninit::uninit() }; SIZE];
for element in &mut array {
element.write(T::from_le_stream(&mut bytes)?);
}
Some({
// SAFETY:
// - All elements have been initialized.
// - `MaybeUninit` guarantees the same size and layout as `T`.
#[allow(unsafe_code)]
unsafe {
array.as_ptr().cast::<[T; SIZE]>().read()
}
})
}
}
My question is whether
I am aware of e.g. try_from_fn in std::array - Rust but it hasn't been stabilized yet.
I also don't want to use third-party libraries to do this.
13 posts - 4 participants
🏷️ Rust_feed