Search code examples
rustbufferreadersdp

Wrapping Vec<u8> to something, that would implement BufRead + Seek


I want to parse an SDP message that I stored in Vec<u8>, using the sdp crate. I found this function to do it so:

pub fn unmarshal<R>(reader: &mut R) -> Result<Self>
where
    R: io::BufRead + io::Seek { ... }

However I do not know how to create a reader that would implement both Seek and BufRead from Vec<u8>. I hope there is something std lib, but I'm new to rust and I'm not familiar with it.

I managed to create BufReader from vec:

let body: Vec<u8> = ....;
let mut reader = BufReader::new(body.as_slice());

But it seems to not implement Seek trait.

let sdp = SessionDescription::unmarshal(&mut reader);

Error:

the trait bound `&[u8]: std::io::Seek` is not satisfied
the trait `std::io::Seek` is implemented for `std::io::BufReader<R>`
required for `std::io::BufReader<&[u8]>` to implement `std::io::Seek`

Solution

  • std::io::Cursor wraps anything that implements AsRef<[u8]> (including byte slices, references to byte slices, Vec<u8>s and more) and provides Read and Seek implementations (regular references to byte slices (&[u8], not [u8]) only implement Read, since they have no way of maintaining a "current position").