You don't need a Cursor
most of the time.
object that I can give to BufReader
and BufWriter
BufReader
requires a value that implements Read
:
impl<R: Read> BufReader<R> {
pub fn new(inner: R) -> BufReader<R>
}
BufWriter
requires a value that implements Write
:
impl<W: Write> BufWriter<W> {
pub fn new(inner: W) -> BufWriter<W> {}
}
If you view the implementors of Read
you will find impl<'a> Read for &'a [u8]
.
If you view the implementors of Write
, you will find impl Write for Vec<u8>
.
use std::io::{Read, Write};
fn main() {
// Create fake "file"
let mut file = Vec::new();
// Write into the "file"
file.write_all(&[1, 2, 3, 4, 5]).unwrap();
// Read the "file's" contents into a new vector
let mut out = Vec::new();
let mut c = file.as_slice();
c.read_to_end(&mut out).unwrap();
println!("{:?}", out);
}
Writing to a Vec
will always append to the end. We also take a slice to the Vec
that we can update. Each read of c
will advance the slice further and further until it is empty.
The main differences from Cursor
:
- Cannot seek the data, so you cannot easily re-read data
- Cannot write to anywhere but the end
c.set_position(0)
be equivalent to how you're seeking? – Boutique