Write Vectored IoSlice Buffers
Write several IoSlice buffers through Write::write_vectored, handle partial writes in a loop, and verify the assembled byte stream.
Code
use std::io::{self, IoSlice, Write};
fn write_all_vectored(mut writer: impl Write, slices: &[IoSlice<'_>]) -> io::Result<usize> {
let mut total = 0;
let mut index = 0;
let mut offset = 0;
while index < slices.len() {
// write_vectored may consume only part of the remaining buffers
let written = writer.write_vectored(&slices[index..])?;
if written == 0 {
return Err(io::Error::from(io::ErrorKind::WriteZero));
}
total += written;
let mut left = written;
while left > 0 {
let available = slices[index].len() - offset;
if left < available {
offset += left;
left = 0;
} else {
left -= available;
index += 1;
offset = 0;
}
}
}
Ok(total)
}
fn main() -> io::Result<()> {
let header = b"HTTP/1.1 200 OK\r\n";
let content_type = b"Content-Type: text/plain\r\n";
let body = b"\r\nhello vectored\n";
let slices = [
IoSlice::new(header),
IoSlice::new(content_type),
IoSlice::new(body),
];
let mut output = Vec::new();
let written = write_all_vectored(&mut output, &slices)?;
let expected: &[u8] =
b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nhello vectored\n";
println!("written: {written}");
println!("output bytes: {}", output.len());
println!("matches: {}", output.as_slice() == expected);
Ok(())
}Inside the snippet
Structurally, expect the functions write_all_vectored and main and nothing else.
Repetition is confined to while index < slices.len() — the rest of the file is straight-line. Result is the error channel: the caller receives the failure as a value instead of an exception.
Points of care
- Everything it calls is documented as part of the language core.
Resultis the only error channel — remove a?while adapting and that site needs an explicitmatch.
Putting it to use
Signature: fn write_all_vectored(mut writer: impl Write, slices: &[IoSlice<'_>]) -> io::Result<usize>
Expect labeled output — written:, output bytes:, matches: — when the file runs.
The demo flow inside main is write_all_vectored — run the file to see it end to end.
Core lines
return Err(io::Error::from(io::ErrorKind::WriteZero));
let written = write_all_vectored(&mut output, &slices)?;
let written = writer.write_vectored(&slices[index..])?;
Interactive Tools for This Topic
FAQ
- What is the error handling style?
- Each fallible operation returns `Result`; nothing is silently discarded.
- What does Write Vectored IoSlice Buffers print when run?
- The script runs standalone; its 3 labeled outputs include `written:`, `output bytes:`, `matches:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.