### Configure and Build CSV Writer with WriterBuilder in Rust Source: https://context7.com/burntsushi/rust-csv/llms.txt Shows how to configure a CSV writer using `WriterBuilder` with custom delimiters, quote styles, and terminators. The example demonstrates building a writer and writing records with specific formatting. The output is a debug representation of the CSV data. ```rust use std::error::Error; use csv::{WriterBuilder, QuoteStyle, Terminator}; fn main() -> Result<(), Box> { let mut wtr = WriterBuilder::new() .delimiter(b';') .quote_style(QuoteStyle::NonNumeric) .terminator(Terminator::CRLF) .from_writer(vec![]); wtr.write_record(&["name", "age", "score"])?; wtr.write_record(&["Alice", "30", "95.5"])?; let data = String::from_utf8(wtr.into_inner()?)?; println!("{:?}", data); Ok(()) } ``` -------------------------------- ### Work with StringRecord CSV Data in Rust Source: https://context7.com/burntsushi/rust-csv/llms.txt Demonstrates the usage of `StringRecord` for handling CSV data as UTF-8 strings. It shows how to create a record from a vector, access fields by index, iterate over fields, and get the total number of fields in the record. ```rust use std::error::Error; use csv::StringRecord; fn main() -> Result<(), Box> { let record = StringRecord::from(vec!["Boston", "United States", "4628910"]); println!("City: {}", &record[0]); println!("Country: {}", &record[1]); for field in record.iter() { println!("Field: {}", field); } println!("Field count: {}", record.len()); Ok(()) } ``` -------------------------------- ### Writing CSV Data with csv-core Source: https://github.com/burntsushi/rust-csv/blob/master/csv-core/README.md Illustrates how to use the `csv_core::Writer` to construct CSV data programmatically. This example shows writing fields, delimiters, and terminators, including proper handling of quoting for fields containing special characters like commas. The `finish` method must be called to ensure correct CSV formatting. ```rust use csv_core::Writer; // This is where we'll write out CSV data. let mut out = &mut [0; 1024]; // The number of bytes we've written to `out`. let mut nout = 0; // Create a CSV writer with a default configuration. let mut wtr = Writer::new(); // Write a single field. Note that we ignore the `WriteResult` and the number // of input bytes consumed since we're doing this by hand. let (_, _, n) = wtr.field(&b"foo"[..], &mut out[nout..]); nout += n; // Write a delimiter and then another field that requires quotes. let (_, n) = wtr.delimiter(&mut out[nout..]); nout += n; let (_, _, n) = wtr.field(&b"bar,baz"[..], &mut out[nout..]); nout += n; let (_, n) = wtr.terminator(&mut out[nout..]); nout += n; // Now write another record. let (_, _, n) = wtr.field(&b"a \"b\" c"[..], &mut out[nout..]); nout += n; let (_, n) = wtr.delimiter(&mut out[nout..]); nout += n; let (_, _, n) = wtr.field(&b"quux"[..], &mut out[nout..]); nout += n; // We must always call finish once done writing. // This ensures that any closing quotes are written. let (_, n) = wtr.finish(&mut out[nout..]); nout += n; assert_eq!(&out[..nout], &b"foo,\"bar,baz\"\n\"a \"\"b\"\" c\",quux"[..]); ``` -------------------------------- ### Reading CSV Data with csv-core Source: https://github.com/burntsushi/rust-csv/blob/master/csv-core/README.md Demonstrates how to use the `csv_core::Reader` to parse CSV data and count the number of records and fields. It handles input byte slices and processes fields, detecting record endings. This example is suitable for environments where the standard library is not available. ```rust use csv_core::{Reader, ReadFieldResult}; let data = "\nfoo,bar,baz\na,b,c\nxxx,yyy,zzz\n"; let mut rdr = Reader::new(); let mut bytes = data.as_bytes(); let mut count_fields = 0; let mut count_records = 0; loop { // We skip handling the output since we don't need it for counting. let (result, nin, _) = rdr.read_field(bytes, &mut [0; 1024]); bytes = &bytes[nin..]; match result { ReadFieldResult::InputEmpty => {}, ReadFieldResult::OutputFull => panic!("field too large"), ReadFieldResult::Field { record_end } => { count_fields += 1; if record_end { count_records += 1; } } ReadFieldResult::End => break, } } assert_eq!(3, count_records); assert_eq!(9, count_fields); ``` -------------------------------- ### Seek to Position in CSV File with Reader::seek in Rust Source: https://context7.com/burntsushi/rust-csv/llms.txt Demonstrates how to use `Reader::seek` and `Position` to move to a specific location within a CSV file and re-read records. This functionality requires the underlying reader to implement `io::Seek`. The example seeks back to the last record and prints it. ```rust use std::error::Error; use std::io::Cursor; use csv::{Reader, Position}; fn main() -> Result<(), Box> { let data = "a,b,c\n1,2,3\n4,5,6\n7,8,9"; let mut rdr = Reader::from_reader(Cursor::new(data)); let mut last_pos = Position::new(); for result in rdr.records() { last_pos = result?.position().unwrap().clone(); } rdr.seek(last_pos)?; if let Some(result) = rdr.records().next() { println!("Last record again: {:?}", result?); } Ok(()) } ``` -------------------------------- ### ReaderBuilder::comment Source: https://context7.com/burntsushi/rust-csv/llms.txt Sets a character to identify comment lines. Lines starting with this character are ignored during CSV parsing. ```APIDOC ## ReaderBuilder::comment ### Description Sets a comment character. Lines starting with this character are ignored during parsing. ### Method `ReaderBuilder::comment(comment: Option)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use std::error::Error; use csv::ReaderBuilder; fn main() -> Result<(), Box> { let data = "# This is a comment\nname,age\n# Another comment\nAlice,30\nBob,25\n"; let mut rdr = ReaderBuilder::new() .comment(Some(b'#')) .from_reader(data.as_bytes()); for result in rdr.records() { let record = result?; println!("{:?}", record); // Comments are skipped } Ok(()) } ``` ### Response #### Success Response (200) Represents a CSV record, typically a `StringRecord`. #### Response Example ``` ["name", "age"] ["Alice", "30"] ["Bob", "25"] ``` ``` -------------------------------- ### Get CSV Headers Source: https://context7.com/burntsushi/rust-csv/llms.txt Returns a reference to the first row (header row) of the CSV data. This method can be called before or after iterating through records, providing access to column names. Useful for dynamic processing of CSV files. ```rust use std::error::Error; use csv::Reader; fn main() -> Result<(), Box> { let data = "name,age,city\nAlice,30,Boston\nBob,25,Seattle"; let mut rdr = Reader::from_reader(data.as_bytes()); let headers = rdr.headers()?; println!("Columns: {:?}", headers); // Output: Columns: StringRecord(["name", "age", "city"]) for result in rdr.records() { let record = result?; for (header, value) in headers.iter().zip(record.iter()) { println!("{}: {}", header, value); } } Ok(()) } ``` -------------------------------- ### Handle Invalid CSV Field Values with csv::invalid_option in Rust Source: https://context7.com/burntsushi/rust-csv/llms.txt Explains and demonstrates the `csv::invalid_option` deserializer helper, which converts invalid field values to `None` during deserialization, preventing errors and allowing for graceful handling of dirty data. The example deserializes records with optional fields. ```rust use std::error::Error; use serde::Deserialize; #[derive(Debug, Deserialize)] struct Row { name: String, #[serde(deserialize_with = "csv::invalid_option")] age: Option, #[serde(deserialize_with = "csv::invalid_option")] score: Option, } fn main() -> Result<(), Box> { let data = "name,age,score\nAlice,30,95.5\nBob,invalid,\nCarol,,88.0"; let mut rdr = csv::Reader::from_reader(data.as_bytes()); for result in rdr.deserialize() { let row: Row = result?; println!("{:?}", row); } Ok(()) } ``` -------------------------------- ### Ignore Comment Lines with ReaderBuilder Source: https://context7.com/burntsushi/rust-csv/llms.txt Sets a character to identify comment lines in the CSV data. Lines starting with this specified character will be ignored during the parsing process. ```rust use std::error::Error; use csv::ReaderBuilder; fn main() -> Result<(), Box> { let data = "\ # This is a comment name,age # Another comment Alice,30 Bob,25 "; let mut rdr = ReaderBuilder::new() .comment(Some(b'#')) .from_reader(data.as_bytes()); for result in rdr.records() { let record = result?; println!("{:?}", record); // Comments are skipped } Ok(()) } ``` -------------------------------- ### Build and Use RandomAccessSimple CSV Index in Rust Source: https://github.com/burntsushi/rust-csv/blob/master/csv-index/README.md This Rust code demonstrates how to build a simple random access index for a CSV file using `RandomAccessSimple`. It covers creating the index, saving it to disk, opening the index, seeking to a specific record, and reading that record. It requires the `csv` and `csv-index` crates. ```rust use std::error::Error; use std::fs::File; use std::io::{self, Write}; use csv_index::RandomAccessSimple; fn main() { example().unwrap(); } fn example() -> Result<(), Box> { // Open a normal CSV reader. let mut rdr = csv::Reader::from_path("data.csv")?; // Create an index for the CSV data in `data.csv` and write it // to `data.csv.idx`. let mut wtr = io::BufWriter::new(File::create("data.csv.idx")?); RandomAccessSimple::create(&mut rdr, &mut wtr)?; wtr.flush()?; // Open the index we just created, get the position of the last // record and seek the CSV reader to the last record. let mut idx = RandomAccessSimple::open(File::open("data.csv.idx")?)?; if idx.is_empty() { return Err(From::from("expected a non-empty CSV index")); } let last = idx.len() - 1; let pos = idx.get(last)?; rdr.seek(pos)?; // Read the next record. if let Some(result) = rdr.records().next() { let record = result?; println!("{:?}", record); Ok(()) } else { Err(From::from("expected at least one record but got none")) } } ``` -------------------------------- ### WriterBuilder Source: https://context7.com/burntsushi/rust-csv/llms.txt Configures and builds a CSV writer with custom options. Allows setting delimiters, quote styles, terminators, and header behavior before creating the writer instance. ```APIDOC ## WriterBuilder ### Description Configures and builds a CSV writer with custom options like delimiters, quote styles, terminators, and header behavior. ### Method `WriterBuilder::new()` ### Endpoint N/A (This is a builder pattern) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use std::error::Error; use csv::{WriterBuilder, QuoteStyle, Terminator}; fn main() -> Result<(), Box> { let mut wtr = WriterBuilder::new() .delimiter(b';') .quote_style(QuoteStyle::NonNumeric) .terminator(Terminator::CRLF) .from_writer(vec![]); wtr.write_record(&["name", "age", "score"])?; wtr.write_record(&["Alice", "30", "95.5"])?; let data = String::from_utf8(wtr.into_inner()?)?; println!("{:?}", data); Ok(()) } ``` ### Response #### Success Response (200) None (This is a builder pattern) #### Response Example None ``` -------------------------------- ### Writer::from_path Source: https://context7.com/burntsushi/rust-csv/llms.txt Creates a CSV writer that directly writes to a specified file path. The file will be truncated if it already exists. ```APIDOC ## Writer::from_path ### Description Creates a CSV writer that writes to a file. The file is truncated if it already exists. ### Method `Writer::from_path>(path: P) -> Result>` ### Parameters #### Path Parameters * **path** (string) - Required - The path to the output CSV file. #### Query Parameters None #### Request Body None ### Request Example ```rust use std::error::Error; use csv::Writer; fn main() -> Result<(), Box> { let mut wtr = Writer::from_path("output.csv")?; wtr.write_record(&["id", "name", "score"])?; wtr.write_record(&["1", "Alice", "95"])?; wtr.write_record(&["2", "Bob", "87"])?; wtr.flush()?; Ok(()) } ``` ### Response #### Success Response (200) Indicates successful writing to the file. No specific data is returned, but the file `output.csv` will be created or overwritten. #### Response Example (File `output.csv` created with content) ```csv id,name,score 1,Alice,95 2,Bob,87 ``` ``` -------------------------------- ### Reader::from_path Source: https://context7.com/burntsushi/rust-csv/llms.txt Creates a CSV reader that reads from a file path. Returns an error if the file cannot be opened. ```APIDOC ## GET /reader/from_path ### Description Creates a CSV reader that reads from a file path. Returns an error if the file cannot be opened. ### Method GET ### Endpoint /reader/from_path ### Parameters #### Query Parameters - **path** (string) - Required - The path to the CSV file. ### Request Example ```rust use std::error::Error; use csv::Reader; fn main() -> Result<(), Box> { let mut rdr = Reader::from_path("cities.csv")?; for result in rdr.records() { let record = result?; println!("City: {}, Country: {}", &record[0], &record[1]); } Ok(()) } ``` ### Response #### Success Response (200) - **records** (array) - An array of CSV records. #### Response Example ```json { "records": [ ["Boston", "United States"], ["Concord", "United States"] ] } ``` ``` -------------------------------- ### ReaderBuilder Source: https://context7.com/burntsushi/rust-csv/llms.txt Configures and builds a CSV reader with custom parsing options like delimiters, quote characters, trimming, and flexible record lengths. ```APIDOC ## POST /reader/builder ### Description Configures and builds a CSV reader with custom parsing options like delimiters, quote characters, trimming, and flexible record lengths. ### Method POST ### Endpoint /reader/builder ### Parameters #### Request Body - **data** (string) - Required - The CSV data to read. - **delimiter** (char) - Optional - The delimiter character (e.g., ';'). Defaults to ','. - **trim** (string) - Optional - The type of trimming to apply (e.g., 'All', 'Whitespace'). Defaults to 'None'. - **flexible** (boolean) - Optional - Whether to allow flexible record lengths. Defaults to false. - **has_headers** (boolean) - Optional - Whether the CSV has a header row. Defaults to true. ### Request Example ```rust use std::error::Error; use csv::{ReaderBuilder, Trim}; fn main() -> Result<(), Box> { let data = "name ; age ; city\n Alice ; 30 ; Boston "; let mut rdr = ReaderBuilder::new() .delimiter(b';') .trim(Trim::All) .flexible(true) .has_headers(true) .from_reader(data.as_bytes()); for result in rdr.records() { let record = result?; println!("{:?}", record); } Ok(()) } ``` ### Response #### Success Response (200) - **records** (array) - An array of CSV records read with the configured builder. #### Response Example ```json { "records": [ ["Alice", "30", "Boston"] ] } ``` ``` -------------------------------- ### Add csv-index Dependency to Cargo.toml Source: https://github.com/burntsushi/rust-csv/blob/master/csv-index/README.md This snippet shows how to add the csv-index crate as a dependency to your Rust project by modifying the Cargo.toml file. This is a prerequisite for using the crate's functionalities. ```toml [dependencies] csv-index = "0.1.6" ``` -------------------------------- ### Configure and Build Custom CSV Reader Source: https://context7.com/burntsushi/rust-csv/llms.txt Configures and builds a CSV reader with custom parsing options, including delimiters, quote characters, trimming, and flexible record lengths. The `ReaderBuilder` allows fine-grained control over how CSV data is interpreted, making it suitable for non-standard CSV formats. ```rust use std::error::Error; use csv::{ReaderBuilder, Trim}; fn main() -> Result<(), Box> { // Semicolon-delimited data with whitespace let data = "name ; age ; city\n Alice ; 30 ; Boston "; let mut rdr = ReaderBuilder::new() .delimiter(b';') .trim(Trim::All) .flexible(true) .has_headers(true) .from_reader(data.as_bytes()); for result in rdr.records() { let record = result?; println!("{:?}", record); // Output: StringRecord(["Alice", "30", "Boston"]) } Ok(()) } ``` -------------------------------- ### Writer::from_writer Source: https://context7.com/burntsushi/rust-csv/llms.txt Creates a buffered CSV writer instance that writes to any type implementing the `io::Write` trait. ```APIDOC ## Writer::from_writer ### Description Creates a CSV writer from any type implementing `io::Write`. The writer is automatically buffered. ### Method `Writer::from_writer(writer: W) -> Writer` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use std::error::Error; use csv::Writer; fn main() -> Result<(), Box> { let mut wtr = Writer::from_writer(vec![]); wtr.write_record(&["name", "age", "city"])?; wtr.write_record(&["Alice", "30", "Boston"])?; wtr.write_record(&["Bob", "25", "Seattle"])?; let data = String::from_utf8(wtr.into_inner()?)?; println!("{}", data); // Output: // name,age,city // Alice,30,Boston // Bob,25,Seattle Ok(()) } ``` ### Response #### Success Response (200) Returns the underlying writer after all buffered data has been flushed. #### Response Example ``` name,age,city Alice,30,Boston Bob,25,Seattle ``` ``` -------------------------------- ### Write CSV Data to a File with Writer::from_path Source: https://context7.com/burntsushi/rust-csv/llms.txt Creates a CSV writer that directly writes to a specified file path. If the file already exists, it will be truncated before writing. ```rust use std::error::Error; use csv::Writer; fn main() -> Result<(), Box> { let mut wtr = Writer::from_path("output.csv")?; wtr.write_record(&["id", "name", "score"])?; wtr.write_record(&["1", "Alice", "95"])?; wtr.write_record(&["2", "Bob", "87"])?; wtr.flush()?; Ok(()) } ``` -------------------------------- ### Reader::from_reader Source: https://context7.com/burntsushi/rust-csv/llms.txt Creates a CSV reader from any type implementing `io::Read`. The reader is automatically buffered. ```APIDOC ## GET /reader/from_reader ### Description Creates a CSV reader from any type implementing `io::Read`. The reader is automatically buffered, so you should not wrap the input in a `BufReader`. ### Method GET ### Endpoint /reader/from_reader ### Parameters #### Query Parameters - **data** (string) - Required - The CSV data to read. ### Request Example ```rust use std::error::Error; use csv::Reader; fn main() -> Result<(), Box> { let data = "\" city,country,population Boston,United States,4628910 Concord,United States,42695 "; let mut rdr = Reader::from_reader(data.as_bytes()); for result in rdr.records() { let record = result?; println!("{:?}", record); } Ok(()) } ``` ### Response #### Success Response (200) - **records** (array) - An array of CSV records. #### Response Example ```json { "records": [ ["Boston", "United States", "4628910"], ["Concord", "United States", "42695"] ] } ``` ``` -------------------------------- ### Enable Flexible Record Parsing with ReaderBuilder Source: https://context7.com/burntsushi/rust-csv/llms.txt Allows CSV records to have a variable number of fields. By default, all records must match the field count of the first record. This is useful for malformed or inconsistent CSV data. ```rust use std::error::Error; use csv::ReaderBuilder; fn main() -> Result<(), Box> { let data = "a,b,c\n1,2\n4,5,6,7"; // Inconsistent field counts let mut rdr = ReaderBuilder::new() .flexible(true) .has_headers(false) .from_reader(data.as_bytes()); for result in rdr.records() { let record = result?; println!("Fields: {}, Data: {:?}", record.len(), record); } Ok(()) } ``` -------------------------------- ### Read CSV Data from Stdin in Rust Source: https://github.com/burntsushi/rust-csv/blob/master/README.md This Rust code snippet demonstrates how to read CSV data from standard input and print each record to standard output. It uses the `csv::Reader` to iterate over records and handles potential errors during reading. No external dependencies beyond the `csv` crate are required. ```rust use std::{error::Error, io, process}; fn example() -> Result<(), Box> { // Build the CSV reader and iterate over each record. let mut rdr = csv::Reader::from_reader(io::stdin()); for result in rdr.records() { // The iterator yields Result, so we check the // error here. let record = result?; println!("{:?}", record); } Ok(()) } fn main() { if let Err(err) = example() { println!("error running example: {}", err); process::exit(1); } } ``` -------------------------------- ### Write Individual Fields to CSV in Rust Source: https://context7.com/burntsushi/rust-csv/llms.txt Demonstrates how to write individual fields to a CSV writer one at a time using `write_field` and terminate rows with `write_record`. This method is useful for dynamically constructing records. The output is a CSV string. ```rust use std::error::Error; use csv::Writer; fn main() -> Result<(), Box> { let mut wtr = Writer::from_writer(vec![]); // Write fields individually wtr.write_field("name")?; wtr.write_field("value")?; wtr.write_record(None::<&[u8]>)?; wtr.write_field("pi")?; wtr.write_field("3.14159")?; wtr.write_record(None::<&[u8]>)?; let data = String::from_utf8(wtr.into_inner()?)?; println!("{}", data); Ok(()) } ``` -------------------------------- ### ReaderBuilder::flexible Source: https://context7.com/burntsushi/rust-csv/llms.txt Enables or disables flexible record parsing, allowing records to have a different number of fields than the first record. ```APIDOC ## ReaderBuilder::flexible ### Description Allows records to have varying numbers of fields. By default, all records must have the same number of fields as the first record. ### Method `ReaderBuilder::flexible(flexible: bool)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use std::error::Error; use csv::ReaderBuilder; fn main() -> Result<(), Box> { let data = "a,b,c\n1,2\n4,5,6,7"; // Inconsistent field counts let mut rdr = ReaderBuilder::new() .flexible(true) .has_headers(false) .from_reader(data.as_bytes()); for result in rdr.records() { let record = result?; println!("Fields: {}, Data: {:?}", record.len(), record); } Ok(()) } ``` ### Response #### Success Response (200) Represents a CSV record, typically a `StringRecord`. #### Response Example ``` Fields: 3, Data: ["a", "b", "c"] Fields: 2, Data: ["1", "2"] Fields: 4, Data: ["4", "5", "6", "7"] ``` ``` -------------------------------- ### Serialize Rust Structs to CSV with Writer::serialize Source: https://context7.com/burntsushi/rust-csv/llms.txt Serializes Rust structs or tuples into CSV records using the Serde library. For structs, header rows are automatically generated from the field names. ```rust use std::error::Error; use serde::Serialize; #[derive(Serialize)] struct City { name: String, country: String, population: u64, } fn main() -> Result<(), Box> { let mut wtr = csv::Writer::from_writer(vec![]); wtr.serialize(City { name: "Boston".to_string(), country: "United States".to_string(), population: 4628910, })?; wtr.serialize(City { name: "Tokyo".to_string(), country: "Japan".to_string(), population: 13960000, })?; let data = String::from_utf8(wtr.into_inner()?)?; println!("{}", data); // Output: // name,country,population // Boston,United States,4628910 // Tokyo,Japan,13960000 Ok(()) } ``` -------------------------------- ### Write CSV Data to a Buffer with Writer::from_writer Source: https://context7.com/burntsushi/rust-csv/llms.txt Creates a CSV writer that outputs to any type implementing `io::Write`, such as a `Vec`. The writer automatically buffers output for efficiency. ```rust use std::error::Error; use csv::Writer; fn main() -> Result<(), Box> { let mut wtr = Writer::from_writer(vec![]); wtr.write_record(&["name", "age", "city"])?; wtr.write_record(&["Alice", "30", "Boston"])?; wtr.write_record(&["Bob", "25", "Seattle"])?; let data = String::from_utf8(wtr.into_inner()?)?; println!("{}", data); // Output: // name,age,city // Alice,30,Boston // Bob,25,Seattle Ok(()) } ``` -------------------------------- ### StringRecord Source: https://context7.com/burntsushi/rust-csv/llms.txt Represents a CSV record stored as UTF-8 strings. This is the default and more ergonomic record type for text data, allowing easy access and iteration over fields. ```APIDOC ## StringRecord ### Description A CSV record stored as UTF-8 strings. This is the default record type and is more ergonomic than `ByteRecord` for text data. ### Method `StringRecord::from()` ### Endpoint N/A (This is a data structure) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use std::error::Error; use csv::StringRecord; fn main() -> Result<(), Box> { let record = StringRecord::from(vec!["Boston", "United States", "4628910"]); println!("City: {}", &record[0]); println!("Country: {}", &record[1]); for field in record.iter() { println!("Field: {}", field); } println!("Field count: {}", record.len()); Ok(()) } ``` ### Response #### Success Response (200) None (This is a data structure) #### Response Example None ``` -------------------------------- ### Deserialize CSV Data into a Struct with Serde in Rust Source: https://github.com/burntsushi/rust-csv/blob/master/README.md This Rust code snippet shows how to read CSV data from standard input and deserialize each record into a custom struct using Serde. The struct's member names are matched with the CSV header. It requires the `csv` and `serde` crates. The output is each deserialized record printed to standard output. ```rust use std::{error::Error, io, process}; #[derive(Debug, serde::Deserialize)] struct Record { city: String, region: String, country: String, population: Option, } fn example() -> Result<(), Box> { let mut rdr = csv::Reader::from_reader(io::stdin()); for result in rdr.deserialize() { // Notice that we need to provide a type hint for automatic // deserialization. let record: Record = result?; println!("{:?}", record); } Ok(()) } fn main() { if let Err(err) = example() { println!("error running example: {}", err); process::exit(1); } } ``` -------------------------------- ### Create CSV Reader from IO Read Source: https://context7.com/burntsushi/rust-csv/llms.txt Creates a CSV reader from any type implementing `io::Read`. The reader is automatically buffered, so you should not wrap the input in a `BufReader`. This function is useful for reading CSV data from various sources like strings or network streams. ```rust use std::error::Error; use csv::Reader; fn main() -> Result<(), Box> { let data = "city,country,population\nBoston,United States,4628910\nConcord,United States,42695\n"; let mut rdr = Reader::from_reader(data.as_bytes()); for result in rdr.records() { let record = result?; println!("{:?}", record); // Output: StringRecord(["Boston", "United States", "4628910"]) // Output: StringRecord(["Concord", "United States", "42695"]) } Ok(()) } ``` -------------------------------- ### Create CSV Reader from File Path Source: https://context7.com/burntsushi/rust-csv/llms.txt Creates a CSV reader that reads directly from a specified file path. This function simplifies file handling for CSV data, returning an error if the file cannot be opened. It's a convenient way to process CSV files stored on disk. ```rust use std::error::Error; use csv::Reader; fn main() -> Result<(), Box> { let mut rdr = Reader::from_path("cities.csv")?; for result in rdr.records() { let record = result?; println!("City: {}, Country: {}", &record[0], &record[1]); } Ok(()) } ``` -------------------------------- ### Handle CSV Parsing Errors with Rust Source: https://context7.com/burntsushi/rust-csv/llms.txt Demonstrates how to use the `csv::Error` type to catch and report detailed error information, including position data, when parsing CSV data. This is useful for identifying issues like unequal lengths or UTF-8 errors in the CSV file. ```rust use csv::{ErrorKind, ReaderBuilder}; fn main() { let data = "a,b,c\n1,2\n3,4,5"; // Second row has wrong field count let mut rdr = ReaderBuilder::new().from_reader(data.as_bytes()); for result in rdr.records() { match result { Ok(record) => println!("{:?}", record), Err(err) => { match err.kind() { ErrorKind::UnequalLengths { pos, expected_len, len } => { println!( "Row has {} fields, expected {}", len, expected_len ); if let Some(pos) = pos { println!("Error at line {}", pos.line()); } } ErrorKind::Utf8 { pos, err } => { println!("UTF-8 error: {}", err); } _ => println!("Other error: {}", err), } } } } } ``` -------------------------------- ### ByteRecord Source: https://context7.com/burntsushi/rust-csv/llms.txt Represents a CSV record stored as raw bytes. This is useful for handling non-UTF-8 data or when zero-copy deserialization is desired. ```APIDOC ## ByteRecord ### Description A CSV record stored as raw bytes, useful when dealing with non-UTF-8 data or when zero-copy deserialization is needed. ### Method `ByteRecord::new()` ### Endpoint N/A (This is a data structure) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use std::error::Error; use csv::{ByteRecord, ReaderBuilder}; use serde::Deserialize; #[derive(Debug, Deserialize)] struct Row<'a> { city: &'a str, country: &'a str, population: u64, } fn main() -> Result<(), Box> { let data = "city,country,population\nBoston,United States,4628910"; let mut rdr = ReaderBuilder::new().from_reader(data.as_bytes()); let headers = rdr.byte_headers()?.clone(); let mut record = ByteRecord::new(); while rdr.read_byte_record(&mut record)? { let row: Row = record.deserialize(Some(&headers))?; println!("{:?}", row); } Ok(()) } ``` ### Response #### Success Response (200) None (This is a data structure) #### Response Example None ``` -------------------------------- ### Deserialize CSV Records to Rust Structs Source: https://context7.com/burntsushi/rust-csv/llms.txt Returns an iterator that deserializes each CSV record into a Rust type using Serde. Field names from headers are automatically matched to struct field names, simplifying data mapping. Requires the `serde` crate and a struct with `#[derive(Deserialize)]`. ```rust use std::error::Error; use serde::Deserialize; #[derive(Debug, Deserialize)] struct City { city: String, country: String, population: Option, } fn main() -> Result<(), Box> { let data = "city,country,population\nBoston,United States,4628910\nConcord,United States,42695\n"; let mut rdr = csv::Reader::from_reader(data.as_bytes()); for result in rdr.deserialize() { let city: City = result?; println!("{:?}", city); // Output: City { city: "Boston", country: "United States", population: Some(4628910) } } Ok(()) } ``` -------------------------------- ### Writer::serialize Source: https://context7.com/burntsushi/rust-csv/llms.txt Serializes Rust data structures (structs or tuples) into CSV records, automatically generating headers from struct field names when applicable. ```APIDOC ## Writer::serialize ### Description Serializes a Rust struct or tuple into a CSV record using Serde. For structs, header rows are automatically written from field names. ### Method `Writer::serialize(&mut self, record: T) -> Result<()>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **record** (T) - Required - The Rust data structure (struct or tuple) to serialize. ### Request Example ```rust use std::error::Error; use serde::Serialize; #[derive(Serialize)] struct City { name: String, country: String, population: u64, } fn main() -> Result<(), Box> { let mut wtr = csv::Writer::from_writer(vec![]); wtr.serialize(City { name: "Boston".to_string(), country: "United States".to_string(), population: 4628910, })?; wtr.serialize(City { name: "Tokyo".to_string(), country: "Japan".to_string(), population: 13960000, })?; let data = String::from_utf8(wtr.into_inner()?)?; println!("{}", data); // Output: // name,country,population // Boston,United States,4628910 // Tokyo,Japan,13960000 Ok(()) } ``` ### Response #### Success Response (200) Indicates successful serialization and writing of the record(s) to the CSV writer. #### Response Example ```csv name,country,population Boston,United States,4628910 Tokyo,Japan,13960000 ``` ``` -------------------------------- ### Control Header Row Handling with ReaderBuilder Source: https://context7.com/burntsushi/rust-csv/llms.txt Determines whether the first row of the CSV data is treated as a header. If `has_headers(false)` is set, the first row is parsed as a regular data record instead of being skipped. ```rust use std::error::Error; use csv::ReaderBuilder; fn main() -> Result<(), Box> { let data = "Alice,30,Boston\nBob,25,Seattle"; let mut rdr = ReaderBuilder::new() .has_headers(false) .from_reader(data.as_bytes()); for result in rdr.records() { let record = result?; println!("{:?}", record); // First record is "Alice,30,Boston" instead of being skipped } Ok(()) } ``` -------------------------------- ### Reader::read_record Source: https://context7.com/burntsushi/rust-csv/llms.txt Reads a single record into a reusable `StringRecord` buffer. This is faster than using iterators when processing large files because it avoids allocations. ```APIDOC ## GET /reader/read_record ### Description Reads a single record into a reusable `StringRecord` buffer. This is faster than using iterators when processing large files because it avoids allocations. ### Method GET ### Endpoint /reader/read_record ### Parameters #### Query Parameters - **data** (string) - Required - The CSV data to read records from. ### Request Example ```rust use std::error::Error; use csv::{Reader, StringRecord}; fn main() -> Result<(), Box> { let data = "a,b,c\n1,2,3\n4,5,6"; let mut rdr = Reader::from_reader(data.as_bytes()); let mut record = StringRecord::new(); while rdr.read_record(&mut record)? { println!("Record: {:?}", record); } Ok(()) } ``` ### Response #### Success Response (200) - **records** (array) - An array of CSV records read. #### Response Example ```json { "records": [ ["1", "2", "3"], ["4", "5", "6"] ] } ``` ``` -------------------------------- ### Deserialize CSV Data with ByteRecord in Rust Source: https://context7.com/burntsushi/rust-csv/llms.txt Illustrates using `ByteRecord` for zero-copy deserialization of CSV data, particularly useful for non-UTF-8 data or performance-critical scenarios. It reads CSV data, deserializes rows into a struct using borrowed fields, and prints the results. ```rust use std::error::Error; use csv::{ByteRecord, ReaderBuilder}; use serde::Deserialize; #[derive(Debug, Deserialize)] struct Row<'a> { city: &'a str, country: &'a str, population: u64, } fn main() -> Result<(), Box> { let data = "city,country,population\nBoston,United States,4628910"; let mut rdr = ReaderBuilder::new().from_reader(data.as_bytes()); let headers = rdr.byte_headers()?.clone(); let mut record = ByteRecord::new(); while rdr.read_byte_record(&mut record)? { let row: Row = record.deserialize(Some(&headers))?; println!("{:?}", row); } Ok(()) } ``` -------------------------------- ### csv::invalid_option Source: https://context7.com/burntsushi/rust-csv/llms.txt A Serde deserializer helper that converts invalid field values to `None` during deserialization, preventing errors and allowing for more lenient data handling. ```APIDOC ## csv::invalid_option ### Description A Serde deserializer helper that converts invalid field values to `None` instead of returning an error. Useful for handling dirty data. ### Method `csv::invalid_option` ### Endpoint N/A (This is a deserializer function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use std::error::Error; use serde::Deserialize; #[derive(Debug, Deserialize)] struct Row { name: String, #[serde(deserialize_with = "csv::invalid_option")] age: Option, #[serde(deserialize_with = "csv::invalid_option")] score: Option, } fn main() -> Result<(), Box> { let data = "name,age,score\nAlice,30,95.5\nBob,invalid,\nCarol,,88.0"; let mut rdr = csv::Reader::from_reader(data.as_bytes()); for result in rdr.deserialize() { let row: Row = result?; println!("{:?}", row); } Ok(()) } ``` ### Response #### Success Response (200) None (This is a deserializer function) #### Response Example None ``` -------------------------------- ### Reader::headers Source: https://context7.com/burntsushi/rust-csv/llms.txt Returns a reference to the first row (header row) of the CSV data. Can be called before or after iterating through records. ```APIDOC ## GET /reader/headers ### Description Returns a reference to the first row (header row) of the CSV data. Can be called before or after iterating through records. ### Method GET ### Endpoint /reader/headers ### Parameters #### Query Parameters - **data** (string) - Required - The CSV data to read headers from. ### Request Example ```rust use std::error::Error; use csv::Reader; fn main() -> Result<(), Box> { let data = "name,age,city\nAlice,30,Boston\nBob,25,Seattle"; let mut rdr = Reader::from_reader(data.as_bytes()); let headers = rdr.headers()?; println!("Columns: {:?}", headers); for result in rdr.records() { let record = result?; for (header, value) in headers.iter().zip(record.iter()) { println!("{}: {}", header, value); } } Ok(()) } ``` ### Response #### Success Response (200) - **headers** (array) - An array of strings representing the header row. #### Response Example ```json { "headers": ["name", "age", "city"] } ``` ``` -------------------------------- ### Reader::seek and Position Source: https://context7.com/burntsushi/rust-csv/llms.txt Allows seeking to a specific position within a CSV file to re-read records. This functionality requires the underlying reader to implement the `io::Seek` trait. ```APIDOC ## Reader::seek and Position ### Description Allows seeking to a specific position in a CSV file to re-read records. Requires the underlying reader to implement `io::Seek`. ### Method `Reader::seek()` ### Endpoint N/A (This is a method on a Reader object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use std::error::Error; use std::io::Cursor; use csv::{Reader, Position}; fn main() -> Result<(), Box> { let data = "a,b,c\n1,2,3\n4,5,6\n7,8,9"; let mut rdr = Reader::from_reader(Cursor::new(data)); let mut last_pos = Position::new(); for result in rdr.records() { last_pos = result?.position().unwrap().clone(); } rdr.seek(last_pos)?; if let Some(result) = rdr.records().next() { println!("Last record again: {:?}", result?); } Ok(()) } ``` ### Response #### Success Response (200) None (This is a method) #### Response Example None ``` -------------------------------- ### Read Single CSV Record Efficiently Source: https://context7.com/burntsushi/rust-csv/llms.txt Reads a single CSV record into a reusable `StringRecord` buffer. This method is more performant than using iterators for large files as it minimizes memory allocations. It's ideal for scenarios where individual record processing is needed without creating new objects repeatedly. ```rust use std::error::Error; use csv::{Reader, StringRecord}; fn main() -> Result<(), Box> { let data = "a,b,c\n1,2,3\n4,5,6"; let mut rdr = Reader::from_reader(data.as_bytes()); let mut record = StringRecord::new(); while rdr.read_record(&mut record)? { println!("Record: {:?}", record); } Ok(()) } ```