Vec<u8> to Read

#1

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

#2

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
#3

I was running into the same issue as https://stackoverflow.com/questions/42240663/how-to-read-stdioread-from-a-vec-or-slice

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

#4

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
#5

This confuses me. Does this modify the originating Vec?

#6

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
#7

This interpretation makes sense. Thanks!