pub struct AsyncWriterBuilder { /* private fields */ }
Expand description

Builds a CSV writer with various configuration knobs.

This builder can be used to tweak the field delimiter, record terminator and more. Once a CSV AsyncWriter is built, its configuration cannot be changed.

Implementations§

source§

impl AsyncWriterBuilder

source

pub fn create_writer<W: AsyncWrite + Unpin>(&self, wtr: W) -> AsyncWriter<W>

Build a CSV writer from this configuration that writes data to wtr.

Note that the CSV writer is buffered automatically, so you should not wrap wtr in a buffered writer like.

§Example
use std::error::Error;
use csv_async::AsyncWriterBuilder;

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriterBuilder::new().create_writer(vec![]);
    wtr.write_record(&["a", "b", "c"]).await?;
    wtr.write_record(&["x", "y", "z"]).await?;

    let data = String::from_utf8(wtr.into_inner().await?)?;
    assert_eq!(data, "a,b,c\nx,y,z\n");
    Ok(())
}
source§

impl AsyncWriterBuilder

source

pub fn create_serializer<W: AsyncWrite + Unpin>( &self, wtr: W ) -> AsyncSerializer<W>

Build a CSV serde serializer from this configuration that writes data to ser.

Note that the CSV serializer is buffered automatically, so you should not wrap ser in a buffered writer.

§Example
use std::error::Error;
use csv_async::AsyncWriterBuilder;
use serde::Serialize;

#[derive(Serialize)]
struct Row<'a> {
    name: &'a str,
    x: u64,
    y: u64,
}

async fn example() -> Result<(), Box<dyn Error>> {
    let mut ser = AsyncWriterBuilder::new().has_headers(false).create_serializer(vec![]);
    ser.serialize(Row {name: "p1", x: 1, y: 2}).await?;
    ser.serialize(Row {name: "p2", x: 3, y: 4}).await?;

    let data = String::from_utf8(ser.into_inner().await?)?;
    assert_eq!(data, "p1,1,2\np2,3,4\n");
    Ok(())
}
source§

impl AsyncWriterBuilder

source

pub fn new() -> AsyncWriterBuilder

Create a new builder for configuring CSV writing.

To convert a builder into a writer, call one of the methods starting with from_.

§Example
use std::error::Error;
use csv_async::AsyncWriterBuilder;

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriterBuilder::new().create_writer(vec![]);
    wtr.write_record(&["a", "b", "c"]).await?;
    wtr.write_record(&["x", "y", "z"]).await?;

    let data = String::from_utf8(wtr.into_inner().await?)?;
    assert_eq!(data, "a,b,c\nx,y,z\n");
    Ok(())
}
source

pub fn delimiter(&mut self, delimiter: u8) -> &mut AsyncWriterBuilder

The field delimiter to use when writing CSV.

The default is b','.

§Example
use std::error::Error;
use csv_async::AsyncWriterBuilder;

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriterBuilder::new()
        .delimiter(b';')
        .create_writer(vec![]);
    wtr.write_record(&["a", "b", "c"]).await?;
    wtr.write_record(&["x", "y", "z"]).await?;

    let data = String::from_utf8(wtr.into_inner().await?)?;
    assert_eq!(data, "a;b;c\nx;y;z\n");
    Ok(())
}
source

pub fn has_headers(&mut self, yes: bool) -> &mut AsyncWriterBuilder

Whether to write a header row before writing any other row.

When this is enabled and the serialize method is used to write data with something that contains field names (i.e., a struct), then a header row is written containing the field names before any other row is written.

This option has no effect when using other methods to write rows. That is, if you don’t use serialize, then you must write your header row explicitly if you want a header row.

This is enabled by default.

source

pub fn flexible(&mut self, yes: bool) -> &mut AsyncWriterBuilder

Whether the number of fields in records is allowed to change or not.

When disabled (which is the default), writing CSV data will return an error if a record is written with a number of fields different from the number of fields written in a previous record.

When enabled, this error checking is turned off.

§Example: writing flexible records
use std::error::Error;
use csv_async::AsyncWriterBuilder;

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriterBuilder::new()
        .flexible(true)
        .create_writer(vec![]);
    wtr.write_record(&["a", "b"]).await?;
    wtr.write_record(&["x", "y", "z"]).await?;

    let data = String::from_utf8(wtr.into_inner().await?)?;
    assert_eq!(data, "a,b\nx,y,z\n");
    Ok(())
}
§Example: error when flexible is disabled
use std::error::Error;
use csv_async::AsyncWriterBuilder;

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriterBuilder::new()
        .flexible(false)
        .create_writer(vec![]);
    wtr.write_record(&["a", "b"]).await?;
    let err = wtr.write_record(&["x", "y", "z"]).await.unwrap_err();
    match *err.kind() {
        csv_async::ErrorKind::UnequalLengths { expected_len, len, .. } => {
            assert_eq!(expected_len, 2);
            assert_eq!(len, 3);
        }
        ref wrong => {
            panic!("expected UnequalLengths but got {:?}", wrong);
        }
    }
    Ok(())
}
source

pub fn terminator(&mut self, term: Terminator) -> &mut AsyncWriterBuilder

The record terminator to use when writing CSV.

A record terminator can be any single byte. The default is \n.

Note that RFC 4180 specifies that record terminators should be \r\n. To use \r\n, use the special Terminator::CRLF value.

§Example: CRLF

This shows how to use RFC 4180 compliant record terminators.

use std::error::Error;
use csv_async::{Terminator, AsyncWriterBuilder};

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriterBuilder::new()
        .terminator(Terminator::CRLF)
        .create_writer(vec![]);
    wtr.write_record(&["a", "b", "c"]).await?;
    wtr.write_record(&["x", "y", "z"]).await?;

    let data = String::from_utf8(wtr.into_inner().await?)?;
    assert_eq!(data, "a,b,c\r\nx,y,z\r\n");
    Ok(())
}
source

pub fn quote_style(&mut self, style: QuoteStyle) -> &mut AsyncWriterBuilder

The quoting style to use when writing CSV.

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

Note that unless the quote style is set to Never, an empty field is quoted if it is the only field in a record.

§Example: non-numeric quoting

This shows how to quote non-numeric fields only.

use std::error::Error;
use csv_async::{QuoteStyle, AsyncWriterBuilder};

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriterBuilder::new()
        .quote_style(QuoteStyle::NonNumeric)
        .create_writer(vec![]);
    wtr.write_record(&["a", "5", "c"]).await?;
    wtr.write_record(&["3.14", "y", "z"]).await?;

    let data = String::from_utf8(wtr.into_inner().await?)?;
    assert_eq!(data, "\"a\",5,\"c\"\n3.14,\"y\",\"z\"\n");
    Ok(())
}
§Example: never quote

This shows how the CSV writer can be made to never write quotes, even if it sacrifices the integrity of the data.

use std::error::Error;
use csv_async::{QuoteStyle, AsyncWriterBuilder};

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriterBuilder::new()
        .quote_style(QuoteStyle::Never)
        .create_writer(vec![]);
    wtr.write_record(&["a", "foo\nbar", "c"]).await?;
    wtr.write_record(&["g\"h\"i", "y", "z"]).await?;

    let data = String::from_utf8(wtr.into_inner().await?)?;
    assert_eq!(data, "a,foo\nbar,c\ng\"h\"i,y,z\n");
    Ok(())
}
source

pub fn quote(&mut self, quote: u8) -> &mut AsyncWriterBuilder

The quote character to use when writing CSV.

The default is b'"'.

§Example
use std::error::Error;
use csv_async::AsyncWriterBuilder;

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriterBuilder::new()
        .quote(b'\'')
        .create_writer(vec![]);
    wtr.write_record(&["a", "foo\nbar", "c"]).await?;
    wtr.write_record(&["g'h'i", "y\"y\"y", "z"]).await?;

    let data = String::from_utf8(wtr.into_inner().await?)?;
    assert_eq!(data, "a,'foo\nbar',c\n'g''h''i',y\"y\"y,z\n");
    Ok(())
}
source

pub fn double_quote(&mut self, yes: bool) -> &mut AsyncWriterBuilder

Enable double quote escapes.

This is enabled by default, but it may be disabled. When disabled, quotes in field data are escaped instead of doubled.

§Example
use std::error::Error;
use csv_async::AsyncWriterBuilder;

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriterBuilder::new()
        .double_quote(false)
        .create_writer(vec![]);
    wtr.write_record(&["a", "foo\"bar", "c"]).await?;
    wtr.write_record(&["x", "y", "z"]).await?;

    let data = String::from_utf8(wtr.into_inner().await?)?;
    assert_eq!(data, "a,\"foo\\\"bar\",c\nx,y,z\n");
    Ok(())
}
source

pub fn escape(&mut self, escape: u8) -> &mut AsyncWriterBuilder

The escape character to use when writing CSV.

In some variants of CSV, quotes are escaped using a special escape character like \ (instead of escaping quotes by doubling them).

By default, writing these idiosyncratic escapes is disabled, and is only used when double_quote is disabled.

§Example
use std::error::Error;
use csv_async::AsyncWriterBuilder;

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriterBuilder::new()
        .double_quote(false)
        .escape(b'$')
        .create_writer(vec![]);
    wtr.write_record(&["a", "foo\"bar", "c"]).await?;
    wtr.write_record(&["x", "y", "z"]).await?;

    let data = String::from_utf8(wtr.into_inner().await?)?;
    assert_eq!(data, "a,\"foo$\"bar\",c\nx,y,z\n");
    Ok(())
}
source

pub fn comment(&mut self, comment: Option<u8>) -> &mut AsyncWriterBuilder

Use this when you are going to set comment for reader used to read saved file.

If quote_style is set to QuoteStyle::Necessary, a field will be quoted if the comment character is detected anywhere in the field.

The default value is None.

§Example
use std::error::Error;
use csv_async::AsyncWriterBuilder;

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr =
        AsyncWriterBuilder::new().comment(Some(b'#')).create_writer(Vec::new());
    wtr.write_record(&["# comment", "another"]).await?;
    let buf = wtr.into_inner().await?;
    assert_eq!(String::from_utf8(buf).unwrap(), "\"# comment\",another\n");
    Ok(())
}
source

pub fn buffer_capacity(&mut self, capacity: usize) -> &mut AsyncWriterBuilder

Set the capacity (in bytes) of the internal buffer used in the CSV writer. This defaults to a reasonable setting.

Trait Implementations§

source§

impl Debug for AsyncWriterBuilder

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for AsyncWriterBuilder

source§

fn default() -> AsyncWriterBuilder

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.