Struct csv::Writer [] [src]

pub struct Writer<W: Write> {
    // some fields omitted
}

A CSV writer.

This writer provides a convenient interface for encoding CSV data. While creating CSV data is much easier than parsing it, having a writer can be convenient because it can handle quoting for you automatically. Moreover, this particular writer supports Encodable types, which makes it easy to write your custom types as CSV records.

All CSV data produced by this writer, with default options, conforms with RFC 4180. (If certain options like flexible record lengths are enabled, then compliance with RFC 4180 cannot be guaranteed.)

One slight deviation is that records with a single empty field are always encoded as "". This ensures that the record is not skipped since some CSV parsers will ignore consecutive record terminators (like the one in this crate).

Example

Here's an example that encodes word pairs and their edit distances:

let records = vec![
    ("sticker", "mortals", 7),
    ("bribed", "personae", 7),
    ("wobbling", "poncing", 4),
    ("interposed", "emmett", 9),
    ("chocolate", "refile", 7),
];

let mut wtr = csv::Writer::from_memory();
for record in records.into_iter() {
    let result = wtr.encode(record);
    assert!(result.is_ok());
}

Methods

impl Writer<File>
[src]

fn from_file<P: AsRef<Path>>(path: P) -> Result<Writer<File>>

Creates a new Writer that writes CSV data to the file path given.

The file is created if it does not already exist and is truncated otherwise.

impl<W: Write> Writer<W>
[src]

fn from_writer(w: W) -> Writer<W>

Creates a new CSV writer that writes to the io::Write given.

Note that the writer is buffered for you automatically.

fn from_buffer(buf: BufWriter<W>) -> Writer<W>

Creates a new CSV writer that writes to the buffer given.

This lets you specify your own buffered writer (e.g., use a different capacity). All other constructors wrap the writer given in a buffer with default capacity.

impl Writer<Vec<u8>>
[src]

fn from_memory() -> Writer<Vec<u8>>

Creates a new CSV writer that writes to an in memory buffer. At any time, as_string or as_bytes can be called to retrieve the cumulative CSV data.

fn as_string<'r>(&'r mut self) -> &'r str

Returns the written CSV data as a string.

fn as_bytes<'r>(&'r mut self) -> &'r [u8]

Returns the encoded CSV data as raw bytes.

fn into_string(self) -> String

Convert the Writer into a string of written CSV data

fn into_bytes(self) -> Vec<u8>

Convert the Writer into a vector of encoded CSV bytes.

impl<W: Write> Writer<W>
[src]

fn encode<E>(&mut self, e: E) -> Result<()> where E: Encodable

Writes a record by encoding any Encodable value.

This is the most convenient way to write CSV data. Most Rust types map to CSV data in a straight forward way. A vector is just a sequence of fields. Similarly for a struct. Enumerations of zero or one arguments are supported too. (Enums with zero arguments encode to their name, while enums of one argument encode to their constituent value.) Option types are also supported (None encodes to an empty field).

Example

This example encodes word pairs that may or may not have their edit distances computed.

extern crate rustc_serialize;

#[derive(RustcEncodable)]
struct Distance {
    name1: &'static str,
    name2: &'static str,
    dist: Option<usize>,
}

let records = vec![
    Distance { name1: "sticker", name2: "mortals", dist: None },
    Distance { name1: "bribed", name2: "personae", dist: Some(7) },
];

let mut wtr = csv::Writer::from_memory();
for record in records.into_iter() {
    let result = wtr.encode(record);
    assert!(result.is_ok());
}
assert_eq!(wtr.as_string(),
           "sticker,mortals,\nbribed,personae,7\n");

fn write<'a, I>(&mut self, r: I) -> Result<()> where I: Iterator, I::Item: BorrowBytes

Writes a record of strings (Unicode or raw bytes).

This is meant to be the standard method provided by most CSV writers. That is, it writes a record of strings---no more and no less.

This method accepts an iterator of fields for a single record. Each field must satisfy BorrowBytes, which allows the caller to control allocation.

Example

This shows how to write string records.

let records = vec![
    vec!["sticker", "mortals", "7"],
    vec!["bribed", "personae", "7"],
    vec!["wobbling", "poncing", "4"],
    vec!["interposed", "emmett", "9"],
    vec!["chocolate", "refile", "7"],
];

let mut wtr = csv::Writer::from_memory();
for record in records.into_iter() {
    let result = wtr.write(record.into_iter());
    assert!(result.is_ok());
}

This shows how to write records that do not correspond to a valid UTF-8 encoding. (Note the use of Rust's byte string syntax!)

let mut wtr = csv::Writer::from_memory();
let result = wtr.write(vec![&b"\xff"[..], &b"\x00"[..]].into_iter());
assert!(result.is_ok());

assert_eq!(wtr.as_bytes(), b"\xff,\x00\n");

fn flush(&mut self) -> Result<()>

Flushes the underlying buffer.

impl<W: Write> Writer<W>
[src]

fn delimiter(self, delimiter: u8) -> Writer<W>

The delimiter to use when writing CSV data.

Since the CSV writer is meant to be mostly encoding agnostic, you must specify the delimiter as a single ASCII byte. For example, to write tab-delimited data, you would use b'\t'.

The default value is b','.

fn flexible(self, yes: bool) -> Writer<W>

Whether to allow flexible length records when writing CSV data.

When this is set to true, records in the CSV data can have different lengths. By default, this is disabled, which will cause the CSV writer to return an error if it tries to write a record that has a different length than other records it has already written.

fn record_terminator(self, term: RecordTerminator) -> Writer<W>

Sets the record terminator to use when writing CSV data.

By default, this is RecordTerminator::Any(b'\n'). If you want to use CRLF (\r\n) line endings, then use RecordTerminator:CRLF.

fn quote_style(self, style: QuoteStyle) -> Writer<W>

Set the quoting style to use when writing CSV data.

By default, this is set to QuoteStyle::Necessary, which will only use quotes when they are necessary to preserve the integrity of data.

fn quote(self, quote: u8) -> Writer<W>

Set the quote character to use when writing CSV data.

Since the CSV parser is meant to be mostly encoding agnostic, you must specify the quote as a single ASCII byte. For example, to write single quoted data, you would use b'\''.

The default value is b'"'.

fn escape(self, escape: u8) -> Writer<W>

Set the escape character to use when writing CSV data.

This is only used when double_quote is set to false.

Since the CSV parser is meant to be mostly encoding agnostic, you must specify the escape as a single ASCII byte.

The default value is b'\\'.

fn double_quote(self, yes: bool) -> Writer<W>

Set the quoting escape mechanism.

When enabled (which is the default), quotes are escaped by doubling them. e.g., " escapes to "".

When disabled, quotes are escaped with the escape character (which is \\ by default).