CSV Streaming Reader Deserializer

Stream CSV files record by record with the csv crate, validating deserialization per row and quarantining malformed lines.

RustData Integrity

Code

rustsnippet
59 lines
use serde::Deserialize;
use std::io::Cursor;

#[derive(Debug, Deserialize)]
struct Subscriber {
    #[serde(rename = "Email")]
    email: String,
    #[serde(rename = "Plan")]
    plan: String,
    #[serde(rename = "Seats")]
    seats: u32,
}

fn stream_subscribers(
    raw: &str,
) -> Result<(Vec<Subscriber>, Vec<(usize, String)>), csv::Error> {
    let mut reader = csv::ReaderBuilder::new()
        .has_headers(true)
        .trim(csv::Trim::All)
        .flexible(false)
        .from_reader(Cursor::new(raw));

    let mut valid = Vec::new();
    let mut rejected: Vec<(usize, String)> = Vec::new();
    let mut line = 1;

    for outcome in reader.deserialize::<Subscriber>() {
        line += 1;
        match outcome {
            Ok(record) => valid.push(record),
            Err(err) => {
                // 单行结构或类型错误:隔离并保留行号
                rejected.push((line, err.to_string()));
            }
        }
    }
    Ok((valid, rejected))
}

fn main() {
    let payload = "Email,Plan,Seats\n\
ada@example.com,pro,10\n\
bob@example.com,basic,not-a-number\n\
carol@example.com,enterprise,250\n\
broken-line-only-one-field\n";

    match stream_subscribers(payload) {
        Ok((valid, rejected)) => {
            for record in &valid {
                println!("{} on {} x{}", record.email, record.plan, record.seats);
            }
            for (line, reason) in &rejected {
                println!("line {line} rejected: {reason}");
            }
            println!("valid: {}, rejected: {}", valid.len(), rejected.len());
        }
        Err(err) => println!("fatal csv error: {err}"),
    }
}

What the code does

The working surface is the functions stream_subscribers and main — everything else is wiring.

Iteration happens inside for outcome in reader.deserialize::<Subscriber>() — everything outside it runs once. The Result return type makes both outcomes part of the signature. match here is the control flow: arms enumerate the value’s shapes exhaustively.

What to watch for

  • serde::Deserialize must be installed first — the snippet imports it directly.
  • Adapting this code means honoring its Result contract: match each one or pass it up with ?.

Applying it

The entry-point signature is fn stream_subscribers( raw: &str, ) -> Result<(Vec<Subscriber>, Vec<(usize, String)>), csv::Error>

Output lines are prefixed (line, valid:, fatal csv error:), making each step’s effect easy to spot.

The entry point wires stream_subscribers together — run it once and the whole demo flows.

Statements that matter

Ok((valid, rejected)) => {
    for record in &valid {
        println!("{} on {} x{}", record.email, record.plan, record.seats);
    }
    for (line, reason) in &rejected {
        println!("line {line} rejected: {reason}");
    }
    println!("valid: {}, rejected: {}", valid.len(), rejected.len());
}
Err(err) => {
    // 单行结构或类型错误:隔离并保留行号
    rejected.push((line, err.to_string()));
}
Ok((valid, rejected))
}

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
As data, not exceptions: `Result` makes the caller handle both arms.
What does this need from the package registry?
These are real dependencies: `serde::Deserialize`. Without it the snippet will not load.