Fallible slicing operation on arrays

⚓ rust    📅 2025-05-22    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 38 days ago. The information described in this article may have changed.

Is there a fallible slice operation on arrays, which I am not seeing?

I currently have this code:

fn write<const OFFSET: usize, const BUF_SIZE: usize, W, V>(
    value: V,
    mut dst: W,
) -> std::io::Result<()>
where
    V: AsRef<[u8]>,
    W: Write + Seek,
{
    let mut buf = [0; BUF_SIZE];
    let bytes = value.as_ref();
    buf[..bytes.len()].copy_from_slice(bytes);
    dst.seek(SeekFrom::Start(OFFSET as u64))?;
    dst.write_all(bytes)
}

The problem is, that buf[..bytes.len()] may panic.

I know that instead of buf[0], which may panic, I can use buf.get(0) and handle the Option value.
Is there such a thing for slicing or do I need to implement another workaround?

3 posts - 2 participants

Read full topic

🏷️ rust_feed