Skip to content

Instantly share code, notes, and snippets.

@jcbritobr
Created October 9, 2020 20:52
Show Gist options
  • Save jcbritobr/d9cafbc318d486f2ae4e82a36b2b2c6d to your computer and use it in GitHub Desktop.
Save jcbritobr/d9cafbc318d486f2ae4e82a36b2b2c6d to your computer and use it in GitHub Desktop.
A buffer using Read trait implementation.
use std::{fmt::Display, io::BufReader, io::Read, io::Write, str};
struct MyBuffer {
buf: Vec<u8>,
off: usize,
}
impl MyBuffer {
fn new(data: &[u8]) -> MyBuffer {
MyBuffer {
buf: data.to_vec(),
off: 0,
}
}
fn empty(&self) -> bool {
self.buf.len() <= self.off
}
}
impl Display for MyBuffer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "off:{}, data:{:?}", self.off, self.buf)
}
}
impl Read for MyBuffer {
fn read(&mut self, mut buffer: &mut [u8]) -> std::io::Result<usize> {
if self.empty() {
self.off = 0;
return Ok(0);
}
let mut _n = 0;
_n = buffer.write(&self.buf[self.off..])?;
self.off += _n;
Ok(_n)
}
}
fn main() {
let mut buffer = MyBuffer::new(b"this is a bla bla bla ");
println!("{}", buffer);
let mut buffer_test = vec![0u8; 3];
while let Ok(l) = buffer.read(&mut buffer_test) {
if l == 0 {
break;
}
let str = str::from_utf8(&buffer_test[..l]).expect("cant decode buffer");
print!("{}", str);
}
println!();
let mut breader = BufReader::new(buffer);
let mut line = Vec::new();
breader.read_to_end(&mut line).expect("cant read buffer");
println!("{}", str::from_utf8(&line).expect("cant decode string"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment