Getting a reader for a byte array
Asked Answered
E

1

10

I'm trying to test some code which takes a reader. I've got a function:

fn next_byte<R: Read>(reader: &mut R) -> ...

How can I test it on some array of bytes? The docs say that there's a impl<'a> Read for &'a [u8], which would imply this should work:

next_byte(&mut ([0x00u8, 0x00][..]))

But compiler disagrees:

the trait `std::io::Read` is not implemented for the type `[u8]`

Why? I explicitly said &mut.

Using rust 1.2.0

Erebus answered 21/10, 2015 at 0:47 Comment(0)
O
13

You are trying to invoke next_byte::<[u8]>, but [u8] does not implement Read. [u8] and &'a [u8] are not the same type! [u8] is an unsized array type and &'a [u8] is a slice.

When you use the Read implementation on a slice, it needs to mutate the slice in order for the next read to resume from the end of the previous read. Therefore, you need to pass a mutable borrow to a slice.

Here's a simple working example:

use std::io::Read;

fn next_byte<R: Read>(reader: &mut R) {
    let mut b = [0];
    reader.read(&mut b);
    println!("{} ", b[0]);
}

fn main() {
    let mut v = &[1u8, 2, 3] as &[u8];
    next_byte(&mut v);
    next_byte(&mut v);
    next_byte(&mut v);
}
Overset answered 21/10, 2015 at 2:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.