I'm back with another newbie question (so soon). I've spent the afternoon trying all sorts of things to solve this one ;).
I have one way to convert a series of u8 in a vector to u16,
n main() {
let mut vec = Vec::<u8>::new();
vec.push(20); vec.push(21);
vec.push(22); vec.push(23);
// OK
let mut i = 0;
let b = u16::from_be_bytes(vec[i..2].try_into().unwrap());
i += 2;
let b = u16::from_be_bytes(vec[i..2].try_into().unwrap());
let t = vec.iter();
// not so OK
let b: &u8 = t.take(2).collect();
let u = u16::from_be_bytes(b.try_into().unwrap());
let b: &u8 = t.take(2).collect();
let u = u16::from_be_bytes(b.try_into().unwrap());
}
I wanted to try the same with an iterator and avoid having to update my offset all the time.
20 | let b: &u8 = t.take(2).collect();
| ^^^^^^^^^ ------- required by a bound introduced by this call
| |
| value of type `&u8` cannot be built from `std::iter::Iterator<Item=&u8>`
|
21 | let u = u16::from_be_bytes(b.try_into().unwrap());
| ^ -------- required by a bound introduced by this call
| |
| the trait `From<&u8>` is not implemented for `[u8; 2]`
I suppose I could wrap the way which works in some kind of struct so I can just do
let u = thingy.get_u16(); // 0..2
let u = thingy.get_u16(); //2..2
When I was reading bytes from a file, this worked really well
let mut buf = [0; 2];
match .file.read_exact(&mut buf) {
Ok(_) => u16::from_be_bytes(buf),
and was hoping for something neat when reading from a Vec.
Thanks.