Vec<u8> to Read

I have a foo: Vec<u8>. I need to create something which implements trait Read. How do I do this?

Are you trying to achieve something like described here with its stop condition in mind looking for an EOF or something more like a buffer like Cursor?

1 Like

I was running into the same issue as rust - How to read (std::io::Read) from a Vec or Slice? - Stack Overflow

It appears the answer is &foo[..], to convert the Vec to a slice, which, as the llink above you provided shows, implements Read.

Yes but if it's not meant to be read as text then it won't work, so keep that in mind.

Read is implemented for &[u8] by copying from the slice.
Note that reading updates the slice to point to the yet unread part. The slice will be empty when EOF is reached.

Although I see no mention of it in the impl

1 Like

This confuses me. Does this modify the originating Vec?

No, as far as I can see it does this:

  1. You create a reference (from now it'll be easier to think of it as a pointer) to the start of the Vec<u8>
  2. You read n u8 from the pointer
  3. This increments the pointer by n u8 (And adjusts the len because a &[T] is a fat pointer)

It doesn't change the Vec.

1 Like

This interpretation makes sense. Thanks!