Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a reader for a byte array

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

like image 772
viraptor Avatar asked Oct 21 '15 00:10

viraptor


1 Answers

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);
}
like image 162
Francis Gagné Avatar answered Sep 26 '22 03:09

Francis Gagné