This code works, but I have questions about it. See my questions/comments in the TODO comments below.
use std::io::{Error, ErrorKind, Read, Result, Write};
#[derive(Debug)]
struct Color {
r: u8,
g: u8,
b: u8,
}
impl Color {
fn new() -> Color {
Color { r: 0, g: 0, b: 0 }
}
}
impl Read for Color {
// Writes bytes from a Color instance into a byte buffer.
//TODO: Why does the Read trait require self to be mutable here?
fn read(&mut self, buf: &mut[u8]) -> Result<usize> {
if buf.len() < 3 {
return Err(Error::new(ErrorKind::Other, "buffer is too short"));
}
buf[0] = self.r;
buf[1] = self.g;
buf[2] = self.b;
Ok(3)
}
}
impl Write for Color {
// Writes bytes from a byte buffer into a Color instance.
fn write(&mut self, buf: &[u8]) -> Result<usize> {
if buf.len() < 3 {
return Err(Error::new(ErrorKind::Other, "buffer is too short"));
}
self.r = buf[0];
self.g = buf[1];
self.b = buf[2];
Ok(3)
}
fn flush(&mut self) -> Result<()> {
Ok(())
}
}
fn main() {
let mut color = Color {
r: 100,
g: 0,
b: 150,
};
let mut buffer = [0; 3];
//TODO: This reads backwards to me. I would guess this is
// reading from the buffer INTO the color, but it's the opposite.
color.read(&mut buffer).unwrap();
println!("buffer = {:?}", buffer);
let mut new_color = Color::new();
//TODO: This reads backwards to me. I would guess this is
// writing the color into the buffer, but it's the opposite.
new_color.write(&buffer).unwrap();
println!("new_color = {:?}", new_color);
}
Output:
buffer = [100, 0, 150]
new_color = Color { r: 100, g: 0, b: 150 }
Errors:
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 0.91s
Running `target/debug/playground`