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.
Code
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
Resultcontract: 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
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.