Review of array initialization

⚓ Rust    📅 2025-10-14    👤 surdeus    👁️ 2      

surdeus

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

  1. This code is sound, i.e. does not cause UB.
  2. This code is optimal, i.e. there's no faster and / or simpler way to do this on stable which is sound.

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

Read full topic

🏷️ Rust_feed