### Run basic CSV read example Source: https://docs.rs/csv/1.4.0/csv/cookbook/index.html Command-line instructions to clone the repository and execute the basic reading example. ```bash $ git clone git://github.com/BurntSushi/rust-csv $ cd rust-csv $ cargo run --example cookbook-read-basic < examples/data/smallpop.csv ``` -------------------------------- ### Run Serde CSV read example Source: https://docs.rs/csv/1.4.0/csv/cookbook/index.html Command-line instructions to clone the repository and execute the Serde-based reading example. ```bash $ git clone git://github.com/BurntSushi/rust-csv $ cd rust-csv $ cargo run --example cookbook-read-serde < examples/data/smallpop.csv ``` -------------------------------- ### Position::new Source: https://docs.rs/csv/1.4.0/csv/struct.Position.html Creates a new Position instance initialized to the start value. ```APIDOC ## pub fn new() -> Position ### Description Returns a new position initialized to the start value. ``` -------------------------------- ### Create and initialize ByteRecord Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Examples for creating an empty ByteRecord or initializing one from a vector of strings. ```rust use csv::ByteRecord; let record = ByteRecord::new(); assert_eq!(record.len(), 0); ``` ```rust use csv::ByteRecord; let record = ByteRecord::from(vec!["a", "b", "c"]); assert_eq!(record.len(), 3); ``` -------------------------------- ### Iterate over ByteRecord fields Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Example showing how to iterate over the fields contained within a ByteRecord. ```rust use csv::ByteRecord; let record = ByteRecord::from(vec!["a", "b", "c"]); for field in record.iter() { assert!(field == b"a" || field == b"b" || field == b"c"); } ``` -------------------------------- ### pub fn get(&self, i: usize) -> Option<&[u8]> Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Returns the field at the specified index, or None if the index is out of bounds. ```APIDOC ## pub fn get(&self, i: usize) -> Option<&[u8]> ### Description Returns the field at index `i`. If no field at index `i` exists, then this returns `None`. ``` -------------------------------- ### Deserialize ByteRecord into structs Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Examples demonstrating how to deserialize ByteRecord data into Rust structs, either by field order or by header mapping. ```rust use std::error::Error; use csv::ByteRecord; use serde::Deserialize; #[derive(Deserialize)] struct Row<'a> { city: &'a str, country: &'a str, population: u64, } fn example() -> Result<(), Box> { let record = ByteRecord::from(vec![ "Boston", "United States", "4628910", ]); let row: Row = record.deserialize(None)?; assert_eq!(row.city, "Boston"); assert_eq!(row.country, "United States"); assert_eq!(row.population, 4628910); Ok(()) } ``` ```rust use std::error::Error; use csv::ByteRecord; use serde::Deserialize; #[derive(Deserialize)] struct Row { city: String, country: String, population: u64, } fn example() -> Result<(), Box> { // Notice that the fields are not in the same order // as the fields in the struct! let header = ByteRecord::from(vec![ "country", "city", "population", ]); let record = ByteRecord::from(vec![ "United States", "Boston", "4628910", ]); let row: Row = record.deserialize(Some(&header))?; assert_eq!(row.city, "Boston"); assert_eq!(row.country, "United States"); assert_eq!(row.population, 4628910); Ok(()) } ``` -------------------------------- ### Deserialize StringRecord into a struct Source: https://docs.rs/csv/1.4.0/csv/struct.StringRecord.html Examples demonstrating deserialization into structs using field order or header-based mapping. ```rust use std::error::Error; use csv::StringRecord; #[derive(serde::Deserialize)] struct Row<'a> { city: &'a str, country: &'a str, population: u64, } fn example() -> Result<(), Box> { let record = StringRecord::from(vec![ "Boston", "United States", "4628910", ]); let row: Row = record.deserialize(None)?; assert_eq!(row.city, "Boston"); assert_eq!(row.country, "United States"); assert_eq!(row.population, 4628910); Ok(()) } ``` ```rust use std::error::Error; use csv::StringRecord; #[derive(serde::Deserialize)] struct Row { city: String, country: String, population: u64, } fn example() -> Result<(), Box> { // Notice that the fields are not in the same order // as the fields in the struct! let header = StringRecord::from(vec![ "country", "city", "population", ]); let record = StringRecord::from(vec![ "United States", "Boston", "4628910", ]); let row: Row = record.deserialize(Some(&header))?; assert_eq!(row.city, "Boston"); assert_eq!(row.country, "United States"); assert_eq!(row.population, 4628910); Ok(()) } ``` -------------------------------- ### get Source: https://docs.rs/csv/1.4.0/csv/struct.StringRecord.html Retrieves a field at a specific index. ```APIDOC ## pub fn get(&self, i: usize) -> Option<&str> ### Description Return the field at index i. Returns None if the index is out of bounds. ### Parameters - **i** (usize) - Required - The index of the field to retrieve. ``` -------------------------------- ### Get record as slice Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Returns the entire record content as a single contiguous byte slice. ```rust use csv::ByteRecord; let record = ByteRecord::from(vec!["foo", "quux", "z"]); assert_eq!(record.as_slice(), &b"fooquuxz"[..]); ``` -------------------------------- ### Get field range Source: https://docs.rs/csv/1.4.0/csv/struct.StringRecord.html Retrieve the start and end indices of a specific field within the record. ```rust use csv::StringRecord; let record = StringRecord::from(vec!["foo", "quux", "z"]); let range = record.range(1).expect("a record range"); assert_eq!(&record.as_slice()[range], "quux"); ``` -------------------------------- ### pub fn range(&self, i: usize) -> Option> Source: https://docs.rs/csv/1.4.0/csv/struct.StringRecord.html Returns the start and end position of a field in this record. ```APIDOC ## pub fn range(&self, i: usize) -> Option> ### Description Return the start and end position of a field in this record. If no such field exists at the given index, then return None. ``` -------------------------------- ### Get record length Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Returns the total number of fields currently in the record. ```rust use csv::ByteRecord; let record = ByteRecord::from(vec!["a", "b", "c"]); assert_eq!(record.len(), 3); ``` -------------------------------- ### Get record position Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Retrieves the position metadata associated with the record, if available. ```rust use std::error::Error; use csv::{ByteRecord, ReaderBuilder}; fn example() -> Result<(), Box> { let mut record = ByteRecord::new(); let mut rdr = ReaderBuilder::new() .has_headers(false) .from_reader("a,b,c\nx,y,z".as_bytes()); assert!(rdr.read_byte_record(&mut record)?); { let pos = record.position().expect("a record position"); assert_eq!(pos.byte(), 0); assert_eq!(pos.line(), 1); assert_eq!(pos.record(), 0); } assert!(rdr.read_byte_record(&mut record)?); { let pos = record.position().expect("a record position"); assert_eq!(pos.byte(), 6); assert_eq!(pos.line(), 2); assert_eq!(pos.record(), 1); } // Finish the CSV reader for good measure. assert!(!rdr.read_byte_record(&mut record)?); Ok(()) } ``` -------------------------------- ### Create a CSV Reader with ReaderBuilder Source: https://docs.rs/csv/1.4.0/csv/struct.ReaderBuilder.html Demonstrates initializing a reader from a byte slice and collecting records. ```rust use std::error::Error; use csv::{ReaderBuilder, StringRecord}; fn example() -> Result<(), Box> { let data = "\ city,country,pop Boston,United States,4628910 Concord,United States,42695 "; let mut rdr = ReaderBuilder::new().from_reader(data.as_bytes()); let records = rdr .records() .collect::, csv::Error>>()?; assert_eq!(records, vec![ vec!["Boston", "United States", "4628910"], vec!["Concord", "United States", "42695"], ]); Ok(()) } ``` -------------------------------- ### Create a new CSV writer Source: https://docs.rs/csv/1.4.0/csv/struct.WriterBuilder.html Initialize a new WriterBuilder and convert it into a writer using from_writer. ```rust use std::error::Error; use csv::WriterBuilder; fn example() -> Result<(), Box> { let mut wtr = WriterBuilder::new().from_writer(vec![]); wtr.write_record(&["a", "b", "c"])?; wtr.write_record(&["x", "y", "z"])?; let data = String::from_utf8(wtr.into_inner()?)?; assert_eq!(data, "a,b,c\nx,y,z\n"); Ok(()) } ``` -------------------------------- ### ByteRecord::new Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Creates a new, empty ByteRecord. ```APIDOC ## pub fn new() -> ByteRecord ### Description Creates a new empty `ByteRecord`. ### Signature `pub fn new() -> ByteRecord` ``` -------------------------------- ### Create an empty StringRecord Source: https://docs.rs/csv/1.4.0/csv/struct.StringRecord.html Initialize a new, empty StringRecord instance. ```rust use csv::StringRecord; let record = StringRecord::new(); assert_eq!(record.len(), 0); ``` -------------------------------- ### Create a CSV writer from a file path Source: https://docs.rs/csv/1.4.0/csv/struct.Writer.html Initializes a writer that outputs to a specified file path using default configuration. ```rust use std::error::Error; use csv::Writer; fn example() -> Result<(), Box> { let mut wtr = Writer::from_path("foo.csv")?; wtr.write_record(&["a", "b", "c"])?; wtr.write_record(&["x", "y", "z"])?; wtr.flush()?; Ok(()) } ``` -------------------------------- ### Build a Reader from a file path Source: https://docs.rs/csv/1.4.0/csv/struct.ReaderBuilder.html Initializes a CSV reader directly from a file path. ```rust use std::error::Error; use csv::ReaderBuilder; fn example() -> Result<(), Box> { let mut rdr = ReaderBuilder::new().from_path("foo.csv")?; for result in rdr.records() { let record = result?; println!("{:?}", record); } Ok(()) } ``` -------------------------------- ### Get a field by index Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Retrieves the field at the specified index as a byte slice. Returns None if the index is out of bounds. ```rust use csv::ByteRecord; let record = ByteRecord::from(vec!["a", "b", "c"]); assert_eq!(record.get(1), Some(&b"b"[..])); assert_eq!(record.get(3), None); ``` -------------------------------- ### comment(comment: Option) Source: https://docs.rs/csv/1.4.0/csv/struct.ReaderBuilder.html Sets the comment character. Lines starting with this character are ignored. Disabled by default. ```APIDOC ## pub fn comment(&mut self, comment: Option) -> &mut ReaderBuilder ### Description Sets the comment character to use when parsing CSV. If the start of a record begins with the byte given here, then that line is ignored by the CSV parser. ``` -------------------------------- ### Configure comment character Source: https://docs.rs/csv/1.4.0/csv/struct.ReaderBuilder.html Sets a character that, when appearing at the start of a record, causes the line to be ignored. This is disabled by default. ```rust use std::error::Error; use csv::ReaderBuilder; fn example() -> Result<(), Box> { let data = "\ city,country,pop #Concord,United States,42695 Boston,United States,4628910 "; let mut rdr = ReaderBuilder::new() .comment(Some(b'#')) .from_reader(data.as_bytes()); if let Some(result) = rdr.records().next() { let record = result?; assert_eq!(record, vec!["Boston", "United States", "4628910"]); Ok(()) } else { Err(From::from("expected at least one record but got none")) } } ``` -------------------------------- ### Initialize a StringRecord from a Vec Source: https://docs.rs/csv/1.4.0/csv/struct.StringRecord.html Create a StringRecord from a vector of strings using the From trait. ```rust use csv::StringRecord; let record = StringRecord::from(vec!["a", "b", "c"]); assert_eq!(record.len(), 3); ``` -------------------------------- ### pub fn as_byte_record(&self) -> &ByteRecord Source: https://docs.rs/csv/1.4.0/csv/struct.StringRecord.html Returns a reference to the record's raw ByteRecord. ```APIDOC ## pub fn as_byte_record(&self) -> &ByteRecord ### Description Return a reference to this record’s raw ByteRecord. ``` -------------------------------- ### expect Source: https://docs.rs/csv/1.4.0/csv/type.Result.html Returns the contained Ok value, consuming the self value, or panics if Err. ```APIDOC ## pub fn expect(self, msg: &str) -> T ### Description Returns the contained `Ok` value, consuming the `self` value. Panics if the value is an `Err`, with a panic message including the passed message, and the content of the `Err`. ``` -------------------------------- ### Get field range Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Returns the byte range of a specific field, which can be used to slice the record's underlying buffer. ```rust use csv::ByteRecord; let record = ByteRecord::from(vec!["foo", "quux", "z"]); let range = record.range(1).expect("a record range"); assert_eq!(&record.as_slice()[range], &b"quux"[..]); ``` -------------------------------- ### pub fn into_byte_record(self) -> ByteRecord Source: https://docs.rs/csv/1.4.0/csv/struct.StringRecord.html Converts the StringRecord into a ByteRecord. ```APIDOC ## pub fn into_byte_record(self) -> ByteRecord ### Description Convert this StringRecord into a ByteRecord. ``` -------------------------------- ### Build a Reader from a generic reader Source: https://docs.rs/csv/1.4.0/csv/struct.ReaderBuilder.html Initializes a CSV reader from any type implementing Read. Note that automatic buffering is applied. ```rust use std::error::Error; use csv::ReaderBuilder; fn example() -> Result<(), Box> { let data = "\ city,country,pop Boston,United States,4628910 Concord,United States,42695 "; let mut rdr = ReaderBuilder::new().from_reader(data.as_bytes()); for result in rdr.records() { let record = result?; println!("{:?}", record); } Ok(()) } ``` -------------------------------- ### pub fn is_empty(&self) -> bool Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Checks if the record contains zero fields. ```APIDOC ## pub fn is_empty(&self) -> bool ### Description Returns true if and only if this record is empty. ``` -------------------------------- ### pub fn trim(&mut self) Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Removes leading and trailing ASCII whitespace from all fields. ```APIDOC ## pub fn trim(&mut self) ### Description Trim the fields of this record so that leading and trailing whitespace is removed. This method uses the ASCII definition of whitespace. ``` -------------------------------- ### WriterBuilder::new Source: https://docs.rs/csv/1.4.0/csv/struct.WriterBuilder.html Creates a new instance of WriterBuilder to configure CSV writing settings. ```APIDOC ## pub fn new() -> WriterBuilder ### Description Creates a new builder for configuring CSV writing. To convert a builder into a writer, call one of the methods starting with `from_`. ``` -------------------------------- ### pub fn unwrap_or_default(self) -> T Source: https://docs.rs/csv/1.4.0/csv/type.Result.html Returns the contained Ok value or a default value if the result is Err. ```APIDOC ## pub fn unwrap_or_default(self) -> T ### Description Consumes the `self` argument then, if `Ok`, returns the contained value, otherwise if `Err`, returns the default value for that type. ``` -------------------------------- ### Convert to ByteRecord Source: https://docs.rs/csv/1.4.0/csv/struct.StringRecord.html Access or convert a StringRecord into its raw ByteRecord representation. ```rust use csv::StringRecord; let str_record = StringRecord::from(vec!["a", "b", "c"]); let byte_record = str_record.as_byte_record(); assert_eq!(&byte_record[2], b"c"); ``` ```rust use csv::StringRecord; let str_record = StringRecord::from(vec!["a", "b", "c"]); let byte_record = str_record.into_byte_record(); assert_eq!(&byte_record[2], b"c"); ``` ```rust use csv::{ByteRecord, StringRecord}; // Using ByteRecord::from... let str_record = StringRecord::from(vec!["a", "b", "c"]); assert_eq!(ByteRecord::from(str_record).len(), 3); // Using StringRecord::into... let str_record = StringRecord::from(vec!["a", "b", "c"]); let byte_record: ByteRecord = str_record.into(); assert_eq!(byte_record.len(), 3); ``` -------------------------------- ### Configure record terminator with WriterBuilder Source: https://docs.rs/csv/1.4.0/csv/struct.WriterBuilder.html Demonstrates setting a custom record terminator, such as CRLF for RFC 4180 compliance. ```rust use std::error::Error; use csv::{Terminator, WriterBuilder}; fn example() -> Result<(), Box> { let mut wtr = WriterBuilder::new() .terminator(Terminator::CRLF) .from_writer(vec![]); wtr.write_record(&["a", "b", "c"])?; wtr.write_record(&["x", "y", "z"])?; let data = String::from_utf8(wtr.into_inner()?)?; assert_eq!(data, "a,b,c x,y,z "); Ok(()) } ``` -------------------------------- ### ByteRecord::with_capacity Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Creates a new empty ByteRecord with pre-allocated capacity for buffer and fields. ```APIDOC ## pub fn with_capacity(buffer: usize, fields: usize) -> ByteRecord ### Description Create a new empty `ByteRecord` with the given capacity settings. `buffer` refers to the capacity of the buffer used to store the actual row contents, and `fields` refers to the number of fields expected. ### Parameters - **buffer** (usize) - Capacity of the internal buffer. - **fields** (usize) - Expected number of fields. ``` -------------------------------- ### Write a ByteRecord with write_byte_record Source: https://docs.rs/csv/1.4.0/csv/struct.Writer.html Writes a pre-constructed ByteRecord, which can be more efficient than generic record writing. ```rust use std::error::Error; use csv::{ByteRecord, Writer}; fn example() -> Result<(), Box> { let mut wtr = Writer::from_writer(vec![]); wtr.write_byte_record(&ByteRecord::from(&["a", "b", "c"][..]))?; wtr.write_byte_record(&ByteRecord::from(&["x", "y", "z"][..]))?; let data = String::from_utf8(wtr.into_inner()?)?; assert_eq!(data, "a,b,c\nx,y,z\n"); Ok(()) } ``` -------------------------------- ### Provide default values with unwrap_or Source: https://docs.rs/csv/1.4.0/csv/type.Result.html Returns the contained Ok value or a provided default value. Arguments are eagerly evaluated. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Create a CSV writer from an arbitrary writer Source: https://docs.rs/csv/1.4.0/csv/struct.Writer.html Initializes a writer that outputs to any type implementing the Write trait. Note that automatic buffering is performed, so wrapping in a BufWriter is unnecessary. ```rust use std::error::Error; use csv::Writer; fn example() -> Result<(), Box> { let mut wtr = Writer::from_writer(vec![]); wtr.write_record(&["a", "b", "c"])?; wtr.write_record(&["x", "y", "z"])?; let data = String::from_utf8(wtr.into_inner()?)?; assert_eq!(data, "a,b,c\nx,y,z\n"); Ok(()) } ``` -------------------------------- ### Configure header writing with WriterBuilder Source: https://docs.rs/csv/1.4.0/csv/struct.WriterBuilder.html Demonstrates automatic header generation from struct field names and the default behavior when serializing non-struct types. ```rust use std::error::Error; use csv::WriterBuilder; #[derive(serde::Serialize)] struct Row<'a> { city: &'a str, country: &'a str, // Serde allows us to name our headers exactly, // even if they don't match our struct field names. #[serde(rename = "popcount")] population: u64, } fn example() -> Result<(), Box> { let mut wtr = WriterBuilder::new().from_writer(vec![]); wtr.serialize(Row { city: "Boston", country: "United States", population: 4628910, })?; wtr.serialize(Row { city: "Concord", country: "United States", population: 42695, })?; let data = String::from_utf8(wtr.into_inner()?)?; assert_eq!(data, "\ city,country,popcount Boston,United States,4628910 Concord,United States,42695 "); Ok(()) } ``` ```rust use std::error::Error; use csv::WriterBuilder; fn example() -> Result<(), Box> { let mut wtr = WriterBuilder::new().from_writer(vec![]); wtr.serialize(("Boston", "United States", 4628910))?; wtr.serialize(("Concord", "United States", 42695))?; let data = String::from_utf8(wtr.into_inner()?)?; assert_eq!(data, "\ Boston,United States,4628910 Concord,United States,42695 "); Ok(()) } ``` -------------------------------- ### Manually set headers with set_headers Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Overrides automatic header detection by providing a StringRecord manually. ```rust use std::error::Error; use csv::{Reader, StringRecord}; fn example() -> Result<(), Box> { let data = "\ city,country,pop Boston,United States,4628910 "; let mut rdr = Reader::from_reader(data.as_bytes()); assert_eq!(rdr.headers()?, vec!["city", "country", "pop"]); rdr.set_headers(StringRecord::from(vec!["a", "b", "c"])); assert_eq!(rdr.headers()?, vec!["a", "b", "c"]); Ok(()) } ``` -------------------------------- ### Configure record flexibility with WriterBuilder Source: https://docs.rs/csv/1.4.0/csv/struct.WriterBuilder.html Shows how to enable or disable strict field count validation when writing records. ```rust use std::error::Error; use csv::WriterBuilder; fn example() -> Result<(), Box> { let mut wtr = WriterBuilder::new() .flexible(true) .from_writer(vec![]); wtr.write_record(&["a", "b"])?; wtr.write_record(&["x", "y", "z"])?; let data = String::from_utf8(wtr.into_inner()?)?; assert_eq!(data, "a,b x,y,z "); Ok(()) } ``` ```rust use std::error::Error; use csv::WriterBuilder; fn example() -> Result<(), Box> { let mut wtr = WriterBuilder::new() .flexible(false) .from_writer(vec![]); wtr.write_record(&["a", "b"])?; let err = wtr.write_record(&["x", "y", "z"]).unwrap_err(); match *err.kind() { csv::ErrorKind::UnequalLengths { expected_len, len, .. } => { assert_eq!(expected_len, 2); assert_eq!(len, 3); } ref wrong => { panic!("expected UnequalLengths but got {:?}", wrong); } } Ok(()) } ``` -------------------------------- ### ReaderBuilder::new Source: https://docs.rs/csv/1.4.0/csv/struct.ReaderBuilder.html Creates a new instance of ReaderBuilder to begin configuring a CSV reader. ```APIDOC ## pub fn new() -> ReaderBuilder ### Description Creates a new builder for configuring CSV parsing. To convert a builder into a reader, call one of the methods starting with `from_`. ``` -------------------------------- ### Into Ok value Source: https://docs.rs/csv/1.4.0/csv/type.Result.html Extracts the Ok value without panicking, useful for infallible results. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### pub fn len(&self) -> usize Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Returns the total number of fields in the record. ```APIDOC ## pub fn len(&self) -> usize ### Description Returns the number of fields in this record. ``` -------------------------------- ### into_records(self) -> StringRecordsIntoIter Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Returns an owned iterator over all records as strings. ```APIDOC ## pub fn into_records(self) -> StringRecordsIntoIter ### Description Returns an owned iterator over all records as strings. Each item yielded is a Result. ``` -------------------------------- ### from_path Source: https://docs.rs/csv/1.4.0/csv/struct.Writer.html Creates a new CSV writer that writes data to the specified file path using default configuration. ```APIDOC ## pub fn from_path>(path: P) -> Result> ### Description Builds a CSV writer with a default configuration that writes data to the given file path. The file is truncated if it already exists. ### Parameters - **path** (P: AsRef) - Required - The file path to write the CSV data to. ``` -------------------------------- ### pub fn as_slice(&self) -> &str Source: https://docs.rs/csv/1.4.0/csv/struct.StringRecord.html Returns the entire row as a single string slice. ```APIDOC ## pub fn as_slice(&self) -> &str ### Description Return the entire row as a single string slice. The slice returned stores all fields contiguously. ``` -------------------------------- ### Unwrap Result or default Source: https://docs.rs/csv/1.4.0/csv/type.Result.html Returns the Ok value or the default value of the type if the result is an Err. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### Chain Result with and Source: https://docs.rs/csv/1.4.0/csv/type.Result.html Returns the provided result if the current result is Ok, otherwise returns the Err. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### pub fn has_headers(&self) -> bool Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Checks if the reader is configured to interpret the first record as a header. ```APIDOC ## pub fn has_headers(&self) -> bool ### Description Returns true if and only if this reader has been configured to interpret the first record as a header record. ``` -------------------------------- ### pub fn get_ref(&self) -> &R Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Returns a reference to the underlying reader. ```APIDOC ## pub fn get_ref(&self) -> &R ### Description Returns a reference to the underlying reader. ``` -------------------------------- ### pub fn unwrap(self) -> T Source: https://docs.rs/csv/1.4.0/csv/type.Result.html Returns the contained Ok value, consuming the self value. Panics if the value is an Err. ```APIDOC ## pub fn unwrap(self) -> T ### Description Returns the contained `Ok` value, consuming the `self` value. Because this function may panic, its use is generally discouraged. ### Panics Panics if the value is an `Err`, with a panic message provided by the `Err`’s value. ``` -------------------------------- ### byte_records(&mut self) -> ByteRecordsIter<'_, R> Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Returns a borrowed iterator over all records as raw bytes. ```APIDOC ## pub fn byte_records(&mut self) -> ByteRecordsIter<'_, R> ### Description Returns a borrowed iterator over all records as raw bytes. Each item yielded is a Result. ``` -------------------------------- ### pub fn and_then(self, op: F) -> Result Source: https://docs.rs/csv/1.4.0/csv/type.Result.html Calls op if the result is Ok, otherwise returns the Err value of self. ```APIDOC ## pub fn and_then(self, op: F) -> Result ### Description Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`. This function can be used for control flow based on `Result` values. ``` -------------------------------- ### Manually set byte headers with set_byte_headers Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Overrides automatic header detection by providing a ByteRecord manually. ```rust use std::error::Error; use csv::{Reader, ByteRecord}; fn example() -> Result<(), Box> { let data = "\ city,country,pop Boston,United States,4628910 "; let mut rdr = Reader::from_reader(data.as_bytes()); assert_eq!(rdr.byte_headers()?, vec!["city", "country", "pop"]); rdr.set_byte_headers(ByteRecord::from(vec!["a", "b", "c"])); assert_eq!(rdr.byte_headers()?, vec!["a", "b", "c"]); Ok(()) } ``` -------------------------------- ### pub fn as_slice(&self) -> &[u8] Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Returns the entire record as a single contiguous byte slice. ```APIDOC ## pub fn as_slice(&self) -> &[u8] ### Description Return the entire row as a single byte slice. The slice returned stores all fields contiguously. ``` -------------------------------- ### serialize Source: https://docs.rs/csv/1.4.0/csv/struct.Writer.html Serializes a single record into the CSV output using Serde. ```APIDOC ## pub fn serialize(&mut self, record: S) -> Result<()> ### Description Serializes a single record using Serde. If the record is a struct, a header row is automatically written based on the struct fields. ### Parameters - **record** (S: Serialize) - Required - The data structure to serialize as a CSV record. ``` -------------------------------- ### records(&mut self) -> StringRecordsIter<'_, R> Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Returns a borrowed iterator over all records as strings. ```APIDOC ## pub fn records(&mut self) -> StringRecordsIter<'_, R> ### Description Returns a borrowed iterator over all records as strings. Each item yielded is a Result. ``` -------------------------------- ### ReaderBuilder::from_path Source: https://docs.rs/csv/1.4.0/csv/struct.ReaderBuilder.html Builds a CSV parser from the current configuration that reads data from a specified file path. ```APIDOC ## pub fn from_path>(&self, path: P) -> Result> ### Description Builds a CSV parser from this configuration that reads data from the given file path. If there was a problem opening the file at the given path, then this returns the corresponding error. ``` -------------------------------- ### pub fn range(&self, i: usize) -> Option> Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Returns the byte range of a specific field. ```APIDOC ## pub fn range(&self, i: usize) -> Option> ### Description Return the start and end position of a field in this record. If no such field exists at the given index, then return `None`. ``` -------------------------------- ### Reader::from_path Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Creates a new CSV parser with default configuration for a given file path. ```APIDOC ## pub fn from_path>(path: P) -> Result> ### Description Create a new CSV parser with a default configuration for the given file path. To customize CSV parsing, use a `ReaderBuilder`. ### Parameters - **path** (P: AsRef) - Required - The path to the CSV file to be read. ``` -------------------------------- ### Push a new field Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Appends a new field to the end of the record. ```rust use csv::ByteRecord; let mut record = ByteRecord::new(); record.push_field(b"foo"); assert_eq!(&record[0], b"foo"); ``` -------------------------------- ### headers Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Returns a reference to the first row read by this parser as a StringRecord. ```APIDOC ## pub fn headers(&mut self) -> Result<&StringRecord> ### Description Returns a reference to the first row read by this parser. If no row has been read yet, it forces parsing of the first row. Returns an error if parsing fails or if the data is not valid UTF-8. ``` -------------------------------- ### ascii() Source: https://docs.rs/csv/1.4.0/csv/struct.ReaderBuilder.html Configures the reader for ASCII delimited text. ```APIDOC ## pub fn ascii(&mut self) -> &mut ReaderBuilder ### Description A convenience method for specifying a configuration to read ASCII delimited text. This sets the delimiter and record terminator to the ASCII unit separator (`\x1F`) and record separator (`\x1E`), respectively. ``` -------------------------------- ### Copying Result Contents Source: https://docs.rs/csv/1.4.0/csv/type.Result.html Copies the contents of an Ok variant from a Result containing a reference. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` -------------------------------- ### pub fn position(&self) -> Option<&Position> Source: https://docs.rs/csv/1.4.0/csv/struct.ByteRecord.html Retrieves the position metadata for the record if available. ```APIDOC ## pub fn position(&self) -> Option<&Position> ### Description Return the position of this record, if available. ``` -------------------------------- ### Lossily convert ByteRecord to StringRecord Source: https://docs.rs/csv/1.4.0/csv/struct.StringRecord.html Convert a ByteRecord to a StringRecord, replacing invalid UTF-8 sequences with the replacement character. ```rust use csv::{ByteRecord, StringRecord}; let byte_record = ByteRecord::from(vec!["a", "b", "c"]); let str_record = StringRecord::from_byte_record_lossy(byte_record); assert_eq!(str_record.len(), 3); ``` ```rust use csv::{ByteRecord, StringRecord}; let byte_record = ByteRecord::from(vec![ &b"quux"[..], &b"foo\xFFbar"[..], &b"c"[..], ]); let str_record = StringRecord::from_byte_record_lossy(byte_record); assert_eq!(&str_record[0], "quux"); assert_eq!(&str_record[1], "foobar"); assert_eq!(&str_record[2], "c"); ``` -------------------------------- ### Seek to a specific record position Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Shows how to capture a position and seek back to it to re-read a specific record. ```rust use std::{error::Error, io}; use csv::{Reader, Position}; fn example() -> Result<(), Box> { let data = "\ city,country,popcount Boston,United States,4628910 Concord,United States,42695 "; let rdr = Reader::from_reader(io::Cursor::new(data)); let mut iter = rdr.into_records(); let mut pos = Position::new(); loop { // Read the position immediately before each record. let next_pos = iter.reader().position().clone(); if iter.next().is_none() { break; } pos = next_pos; } // Now seek the reader back to `pos`. This will let us read the // last record again. iter.reader_mut().seek(pos)?; let mut iter = iter.into_reader().into_records(); if let Some(result) = iter.next() { let record = result?; assert_eq!(record, vec!["Concord", "United States", "42695"]); Ok(()) } else { Err(From::from("expected at least one record but got none")) } } ``` -------------------------------- ### Initialize CSV Reader from a generic reader Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Creates a new CSV parser using default configuration for a type implementing the Read trait. ```rust use std::error::Error; use csv::Reader; fn example() -> Result<(), Box> { let data = "\ city,country,pop 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(()) } ``` -------------------------------- ### pub fn seek(&mut self, pos: Position) -> Result<()> Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Seeks the underlying reader to the specified position. ```APIDOC ## pub fn seek(&mut self, pos: Position) -> Result<()> ### Description Seeks the underlying reader to the position given. Note that any internal buffer is cleared and header logic is disabled. ``` -------------------------------- ### byte_headers Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Returns a reference to the first row read by this parser as raw bytes. ```APIDOC ## pub fn byte_headers(&mut self) -> Result<&ByteRecord> ### Description Returns a reference to the first row read by this parser as raw bytes. If no row has been read yet, it forces parsing of the first row. Returns an error if parsing fails. ``` -------------------------------- ### pub fn seek_raw(&mut self, seek_from: SeekFrom, pos: Position) -> Result<()> Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Performs a seek operation with explicit control via io::SeekFrom. ```APIDOC ## pub fn seek_raw(&mut self, seek_from: SeekFrom, pos: Position) -> Result<()> ### Description This is like `seek`, but provides direct control over how the seeking operation is performed via `io::SeekFrom`. Unlike `seek`, this will always cause an actual seek to be performed. ``` -------------------------------- ### pub fn into_inner(self) -> R Source: https://docs.rs/csv/1.4.0/csv/struct.Reader.html Consumes the reader and returns the underlying reader. ```APIDOC ## pub fn into_inner(self) -> R ### Description Unwraps this CSV reader, returning the underlying reader. Note that any leftover data inside this reader’s internal buffer is lost. ``` -------------------------------- ### Iterate over StringRecord fields Source: https://docs.rs/csv/1.4.0/csv/struct.StringRecord.html Iterate over each field in a StringRecord. ```rust use csv::StringRecord; let record = StringRecord::from(vec!["a", "b", "c"]); for field in record.iter() { assert!(field == "a" || field == "b" || field == "c"); } ``` -------------------------------- ### pub fn and(self, res: Result) -> Result Source: https://docs.rs/csv/1.4.0/csv/type.Result.html Returns res if the result is Ok, otherwise returns the Err value of self. ```APIDOC ## pub fn and(self, res: Result) -> Result ### Description Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`. ``` -------------------------------- ### from_writer Source: https://docs.rs/csv/1.4.0/csv/struct.Writer.html Creates a new CSV writer that writes data to the provided writer instance. ```APIDOC ## pub fn from_writer(wtr: W) -> Writer ### Description Builds a CSV writer with a default configuration that writes data to the provided writer `wtr`. Note that the CSV writer is buffered automatically. ### Parameters - **wtr** (W: Write) - Required - The underlying writer to output CSV data to. ``` -------------------------------- ### Write CSV data to stdout Source: https://docs.rs/csv/1.4.0/csv/cookbook/index.html Writes CSV records manually to standard output without using Serde. ```rust use std::{error::Error, io, process}; fn example() -> Result<(), Box> { let mut wtr = csv::Writer::from_writer(io::stdout()); // When writing records without Serde, the header record is written just // like any other record. wtr.write_record(["city", "region", "country", "population"])?; wtr.write_record(["Southborough", "MA", "United States", "9686"])?; wtr.write_record(["Northbridge", "MA", "United States", "14061"])?; wtr.flush()?; Ok(()) } fn main() { if let Err(err) = example() { println!("error running example: {}", err); process::exit(1); } } ``` ```bash $ git clone git://github.com/BurntSushi/rust-csv $ cd rust-csv $ cargo run --example cookbook-write-basic > /tmp/simplepop.csv ``` -------------------------------- ### trim(&mut self, trim: Trim) -> &mut ReaderBuilder Source: https://docs.rs/csv/1.4.0/csv/struct.ReaderBuilder.html Configures whether fields are trimmed of leading and trailing whitespace. Supports trimming headers, fields, or both. ```APIDOC ## trim(trim: Trim) ### Description Sets the whitespace trimming behavior for the CSV reader. Trimming can be applied to headers, fields, or both. ### Parameters - **trim** (Trim) - Required - The trimming strategy to apply: Trim::Headers, Trim::Fields, or Trim::All. ``` -------------------------------- ### Map Result with defaults Source: https://docs.rs/csv/1.4.0/csv/type.Result.html Methods to map a Result to a value, providing a default for the Err case. ```rust let x: Result<_, &str> = Ok("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Result<&str, _> = Err("bar"); assert_eq!(x.map_or(42, |v| v.len()), 42); ``` ```rust let k = 21; let x : Result<_, &str> = Ok("foo"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); let x : Result<&str, _> = Err("bar"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); ``` ```rust #![feature(result_option_map_or_default)] let x: Result<_, &str> = Ok("foo"); let y: Result<&str, _> = Err("bar"); assert_eq!(x.map_or_default(|x| x.len()), 3); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### into_inner(self) Source: https://docs.rs/csv/1.4.0/csv/struct.Writer.html Flushes the buffer and returns the underlying writer. ```APIDOC ## into_inner(self) ### Description Flushes the internal buffer and consumes the `Writer`, returning the underlying writer instance. ### Returns - **Result>>** - The underlying writer, or an error if flushing fails. ``` -------------------------------- ### Configure a custom delimiter Source: https://docs.rs/csv/1.4.0/csv/struct.ReaderBuilder.html Sets a custom field delimiter for parsing CSV data. ```rust use std::error::Error; use csv::ReaderBuilder; fn example() -> Result<(), Box> { let data = "\ city;country;pop Boston;United States;4628910 "; let mut rdr = ReaderBuilder::new() .delimiter(b';') .from_reader(data.as_bytes()); if let Some(result) = rdr.records().next() { let record = result?; assert_eq!(record, vec!["Boston", "United States", "4628910"]); Ok(()) } else { Err(From::from("expected at least one record but got none")) } } ``` -------------------------------- ### Handle errors with or Source: https://docs.rs/csv/1.4.0/csv/type.Result.html Returns the current result if it is Ok, otherwise returns the provided alternative result. Note that arguments are eagerly evaluated. ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### Serialize Rust structs to CSV Source: https://docs.rs/csv/1.4.0/csv/struct.Writer.html Uses Serde to serialize structs into CSV records, automatically generating a header row based on struct fields. ```rust use std::error::Error; use csv::Writer; #[derive(serde::Serialize)] struct Row<'a> { city: &'a str, country: &'a str, // Serde allows us to name our headers exactly, // even if they don't match our struct field names. #[serde(rename = "popcount")] population: u64, } fn example() -> Result<(), Box> { let mut wtr = Writer::from_writer(vec![]); wtr.serialize(Row { city: "Boston", country: "United States", population: 4628910, })?; wtr.serialize(Row { city: "Concord", country: "United States", population: 42695, })?; let data = String::from_utf8(wtr.into_inner()?)?; assert_eq!(data, "\ city,country,popcount Boston,United States,4628910 Concord,United States,42695 "); Ok(()) } ``` -------------------------------- ### Convert ByteRecord to StringRecord Source: https://docs.rs/csv/1.4.0/csv/struct.StringRecord.html Convert a ByteRecord to a StringRecord, performing UTF-8 validation. ```rust use std::error::Error; use csv::{ByteRecord, StringRecord}; fn example() -> Result<(), Box> { let byte_record = ByteRecord::from(vec!["a", "b", "c"]); let str_record = StringRecord::from_byte_record(byte_record)?; assert_eq!(str_record.len(), 3); Ok(()) } ``` ```rust use csv::{ByteRecord, StringRecord}; let byte_record = ByteRecord::from(vec![ &b"quux"[..], &b"foo\xFFbar"[..], &b"c"[..], ]); let err = StringRecord::from_byte_record(byte_record).unwrap_err(); assert_eq!(err.utf8_error().field(), 1); assert_eq!(err.utf8_error().valid_up_to(), 3); ``` -------------------------------- ### flexible(&mut self, yes: bool) -> &mut WriterBuilder Source: https://docs.rs/csv/1.4.0/csv/struct.WriterBuilder.html Configures whether the CSV writer allows records with varying numbers of fields. ```APIDOC ## flexible(yes: bool) ### Description Determines if the number of fields in records is allowed to change. When disabled (default), writing a record with a different number of fields than previous records will return an error. ```