Read Until A Delimiter With read_until

Split byte streams on a delimiter with BufRead::read_until, keeping the separator and handling a final chunk that lacks it.

RustData Fetching

Code

rustsnippet
45 lines
use std::io::{self, BufRead, Cursor};

fn main() -> io::Result<()> {
    let payload: &[u8] = b"alpha;beta;gamma;tail-without-semicolon";
    let mut reader = Cursor::new(payload);
    let mut chunk = Vec::new();
    let mut parts = Vec::new();

    // read_until 把分隔符保留在结果里,返回本次读到的字节数
    loop {
        let n = reader.read_until(b';', &mut chunk)?;
        if n == 0 {
            break;
        }
        if chunk.last() == Some(&b';') {
            chunk.pop();
        }
        parts.push(String::from_utf8_lossy(&chunk).into_owned());
        chunk.clear();
    }
    println!("parts: {:?}", parts);
    println!("count: {}", parts.len());

    // 空输入首次调用即返回 0,循环自然结束
    let mut empty = Cursor::new(Vec::new());
    let mut buf = Vec::new();
    println!("empty read: {}", empty.read_until(b';', &mut buf)?);

    // 缓冲区可复用:每次读完清空即可,不产生临时分配
    let mut direct = Cursor::new(b"x|y|z".to_vec());
    let mut fields = Vec::new();
    loop {
        let n = direct.read_until(b'|', &mut chunk)?;
        if n == 0 {
            break;
        }
        if chunk.last() == Some(&b'|') {
            chunk.pop();
        }
        fields.push(String::from_utf8_lossy(&chunk).into_owned());
        chunk.clear();
    }
    println!("second pass: {:?}", fields);
    Ok(())
}

How the snippet works

Read Until A Delimiter With read_until reduces to the function main.

Fallible operations return Result, and the ? operator short-circuits errors up to the caller.

Points of care

  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Applying it

Signature: fn main() -> io::Result<()>

Look for the parts:, count:, empty read: prefixes when the file runs; they tie each line to its step.

Statements that matter

let n = reader.read_until(b';', &mut chunk)?;
let n = direct.read_until(b'|', &mut chunk)?;
if chunk.last() == Some(&b';') {
    chunk.pop();
}

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.
What does Read Until A Delimiter With read_until print when run?
No setup needed: run the file and look for labeled lines like `parts:`, `count:`, `empty read:` in the output.