Struct csv_async::AsyncWriter

source ·
pub struct AsyncWriter<W: AsyncWrite + Unpin>(/* private fields */);
Expand description

A already configured CSV writer for tokio runtime.

A CSV writer takes as input Rust values and writes those values in a valid CSV format as output.

While CSV writing is considerably easier than parsing CSV, a proper writer will do a number of things for you:

  1. Quote fields when necessary.
  2. Check that all records have the same number of fields.
  3. Write records with a single empty field correctly.
  4. Use buffering intelligently and otherwise avoid allocation. (This means that callers should not do their own buffering.)

All of the above can be configured using a AsyncWriterBuilder. However, a AsyncWriter has convenient constructor (from_writer`) that use the default configuration.

Note that the default configuration of a AsyncWriter uses \n for record terminators instead of \r\n as specified by RFC 4180. Use the terminator method on AsyncWriterBuilder to set the terminator to \r\n if it’s desired.

Implementations§

source§

impl<W: AsyncWrite + Unpin> AsyncWriter<W>

source

pub fn from_writer(wtr: W) -> AsyncWriter<W>

Build a CSV writer with a default configuration that writes data to wtr.

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

Example
use std::error::Error;
use csv_async::AsyncWriter;

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriter::from_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 async fn write_record<I, T>(&mut self, record: I) -> Result<()>where I: IntoIterator<Item = T>, T: AsRef<[u8]>,

Write a single record.

This method accepts something that can be turned into an iterator that yields elements that can be represented by a &[u8].

This may be called with an empty iterator, which will cause a record terminator to be written. If no fields had been written, then a single empty field is written before the terminator.

Example
use std::error::Error;
use csv_async::AsyncWriter;

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriter::from_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 async fn write_byte_record(&mut self, record: &ByteRecord) -> Result<()>

Write a single ByteRecord.

This method accepts a borrowed ByteRecord and writes its contents to the underlying writer.

This is similar to write_record except that it specifically requires a ByteRecord. This permits the writer to possibly write the record more quickly than the more generic write_record.

This may be called with an empty record, which will cause a record terminator to be written. If no fields had been written, then a single empty field is written before the terminator.

Example
use std::error::Error;
use csv_async::{ByteRecord, AsyncWriter};

async fn example() -> Result<(), Box<dyn Error>> {
    let mut wtr = AsyncWriter::from_writer(vec![]);
    wtr.write_byte_record(&ByteRecord::from(&["a", "b", "c"][..])).await?;
    wtr.write_byte_record(&ByteRecord::from(&["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 async fn write_field<T: AsRef<[u8]>>(&mut self, field: T) -> Result<()>

Write a single field.

One should prefer using write_record over this method. It is provided for cases where writing a field at a time is more convenient than writing a record at a time.

Note that if this API is used, write_record should be called with an empty iterator to write a record terminator.

Example
use std::error::Error;
use csv_async::AsyncWriter;

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

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

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

Flush the contents of the internal buffer to the underlying writer.

If there was a problem writing to the underlying writer, then an error is returned.

This finction is also called by writer destructor.

source

pub async fn into_inner(self) -> Result<W, Error>

Flush the contents of the internal buffer and return the underlying writer.

Trait Implementations§

source§

impl<W: Debug + AsyncWrite + Unpin> Debug for AsyncWriter<W>

source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<W> RefUnwindSafe for AsyncWriter<W>where W: RefUnwindSafe,

§

impl<W> Send for AsyncWriter<W>where W: Send,

§

impl<W> Sync for AsyncWriter<W>where W: Sync,

§

impl<W> Unpin for AsyncWriter<W>

§

impl<W> UnwindSafe for AsyncWriter<W>where W: UnwindSafe,

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere 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> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere 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 Twhere 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 Twhere 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.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more