Custom Read Transforms Bytes

Implement Read once to uppercase bytes as they stream through, then compose the reader with BufReader like any other Read source.

RustData Integrity

Code

rustsnippet
31 lines
use std::io::{self, Read};

// a custom reader transforms bytes while they stream through
struct UpperReader<R> {
    inner: R,
}

impl<R: Read> Read for UpperReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let n = self.inner.read(buf)?;
        buf[..n].make_ascii_uppercase();
        Ok(n)
    }
}

fn main() {
    let mut reader = UpperReader { inner: b"deploy build 42 ok
".as_slice() };

    let mut out = Vec::new();
    reader.read_to_end(&mut out).unwrap();
    println!("{}", String::from_utf8(out).unwrap());

    // the wrapper composes with other readers: buffer it, then read a line
    let mut buffered = io::BufReader::new(UpperReader { inner: b"line one
line two
".as_slice() });
    let mut line = String::new();
    buffered.read_line(&mut line).unwrap();
    print!("{line}");
}

How the snippet works

Structurally, expect the functions read and main and nothing else.

The Result return type makes both outcomes part of the signature.

What to watch for

  • Adapting this code means honoring its Result contract: match each one or pass it up with ?.

Applying it

The primary signature is fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>

Statements that matter

fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
    let n = self.inner.read(buf)?;
    buf[..n].make_ascii_uppercase();
    Ok(n)
}
buffered.read_line(&mut line).unwrap();
reader.read_to_end(&mut out).unwrap();

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
As `Result` values — each fallible call returns one, and the caller matches or propagates it.
How do you run Custom Read Transforms Bytes?
Nothing to install first — run the file and the program does the rest.