1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#![deny(missing_docs)]

/*!
The `csv-async` crate provides a fast and flexible CSV reader and writer, 
which is intended to be run in asynchronous environment - i.e.
inside functions with `async` attribute called by tasks run by executor.
This library does not imply using any particular executor (is executor agnostic).
Unit tests and documentation snippets uses `async-std` crate.
Synchronous interface for reading and writing CSV files is not contained in this crate,
please use `csv` crate for this. This crate attempts to closely mimic `csv` crate API.

TODO: The [tutorial](tutorial/index.html) is a good place to start if you're new to
Rust.

TODO: The [cookbook](cookbook/index.html) will give you a variety of complete Rust
programs that do CSV reading and writing.

# Brief overview

The primary types in this crate are
[`AsyncReader`](struct.AsyncReader.html)
and
[`AsyncWriter`](struct.AsyncWriter.html),
for reading and writing CSV data respectively.
Correspondingly, to support CSV data with custom field or record delimiters
(among many other things), you should use either a
[`AsyncReaderBuilder`](struct.AsyncReaderBuilder.html)
or a
[`AsyncWriterBuilder`](struct.AsyncWriterBuilder.html),
depending on whether you're reading or writing CSV data.

The standard CSV record types are
[`StringRecord`](struct.StringRecord.html)
and
[`ByteRecord`](struct.ByteRecord.html).
`StringRecord` should be used when you know your data to be valid UTF-8.
For data that may be invalid UTF-8, `ByteRecord` is suitable.

Finally, the set of errors is described by the
[`Error`](struct.Error.html)
type.

The rest of the types in this crate mostly correspond to more detailed errors,
position information, configuration knobs or iterator types.

# Setup

Add this to your `Cargo.toml`:

```toml
[dependencies]
csv-async = "1.0.0"
# or
# csv-async = {version = "1.0.0", features = ["tokio"]}
```

# Example

This example shows how to read and write CSV file in asynchronous context and get into some record details.

Sample input file:
```csv
city,region,country,population
Southborough,MA,United States,9686
Northbridge,MA,United States,14061
Marlborough,MA,United States,38334
Springfield,MA,United States,152227
Springfield,MO,United States,150443
Springfield,NJ,United States,14976
Concord,NH,United States,42605
```

```no_run
use std::error::Error;
use std::process;
#[cfg(not(feature = "tokio"))]
use futures::stream::StreamExt;
#[cfg(not(feature = "tokio"))]
use async_std::fs::File;
#[cfg(feature = "tokio")]
use tokio::stream::StreamExt;
#[cfg(feature = "tokio")]
use tokio::fs::File;

async fn filter_by_region(region:&str, file_in:&str, file_out:&str) -> Result<(), Box<dyn Error>> {
    // Function reads CSV file that has column named "region"
    // at second position (index = 1).
    // It writes to new file only rows with region equal to passed argument
    // and remove region column.
    let mut rdr = csv_async::AsyncReader::from_reader(
        File::open(file_in).await?
    );
    let mut wri = csv_async::AsyncWriter::from_writer(
        File::create(file_out).await?
    );
    wri.write_record(rdr
        .headers()
        .await?.into_iter()
        .filter(|h| *h != "region")
    ).await?;
    let mut records = rdr.records();
    while let Some(record) = records.next().await {
        let record = record?;
        match record.get(1) {
            Some(reg) if reg == region => 
                wri.write_record(record
                    .iter()
                    .enumerate()
                    .filter(|(i, _)| *i != 1)
                    .map(|(_, s)| s)
                ).await?,
            _ => {},
        }
    }
    Ok(())
}

#[cfg(not(feature = "tokio"))]
fn main() {
    async_std::task::block_on(async {
        if let Err(err) = filter_by_region(
            "MA",
            "/tmp/all_regions.csv",
            "/tmp/MA_only.csv"
        ).await {
            println!("error running filter_by_region: {}", err);
            process::exit(1);
        }
    });
}

#[cfg(feature = "tokio")]
fn main() {
    tokio::runtime::Runtime::new().unwrap().block_on(async {
        if let Err(err) = filter_by_region(
            "MA",
            "/tmp/all_regions.csv",
            "/tmp/MA_only.csv"
        ).await {
            println!("error running filter_by_region: {}", err);
            process::exit(1);
        }
    });
}
```

TODO: There are more examples in the [cookbook](cookbook/index.html).
*/

#[cfg(test)]
mod tests {
    use std::error::Error;
    
    #[cfg(not(feature = "tokio"))]
    use futures::stream::StreamExt;
    #[cfg(not(feature = "tokio"))]
    use async_std::fs::File;
    
    #[cfg(feature = "tokio")]
    use tokio::stream::StreamExt;
    #[cfg(feature = "tokio")]
    use tokio::fs::File;
   
    async fn crete_async(file:&str) -> Result<(), Box<dyn Error>> {
        // Build the CSV reader and iterate over each record.
        let mut wri = crate::AsyncWriter::from_writer(
            File::create(file).await?
        );
        wri.write_record(&["city","region","country","population"]).await?;
        wri.write_record(&["Northbridge","MA","United States","14061"]).await?;
        wri.write_record(&["Westborough","MA","United States","29313"]).await?;
        wri.write_record(&["Springfield","NJ","United States","14976"]).await?;
        wri.flush().await?;
        Ok(())
    }
   
    async fn copy_async(file_in:&str, file_out:&str) -> Result<(), Box<dyn Error>> {
        let mut rdr = crate::AsyncReader::from_reader(
            File::open(file_in).await?
        );
        let mut wri = crate::AsyncWriter::from_writer(
            File::create(file_out).await?
        );
        wri.write_record(rdr.headers().await?.into_iter()).await?;
        let mut records = rdr.records();
        while let Some(record) = records.next().await {
            wri.write_record(&record?).await?;
        }
        Ok(())
    }
   
    #[test]
    fn test_on_files() {
        use std::io::Read;
        use std::hash::Hasher;
        std::fs::create_dir_all("examples/data").unwrap();
        let file_in  = "examples/data/smallpop.csv";
        let file_out = "examples/data/smallpop_out.csv";

        #[cfg(not(feature = "tokio"))]
        async_std::task::block_on(async {
            if let Err(err) = crete_async(file_in).await {
                assert!(false, "error running crete_async: {}", err);
            }
            if let Err(err) = copy_async(file_in, file_out).await {
                assert!(false, "error running copy_async: {}", err);
            }
        });
        #[cfg(feature = "tokio")]
        tokio::runtime::Runtime::new().unwrap().block_on(async {
            if let Err(err) = crete_async(file_in).await {
                assert!(false, "error running crete_async: {}", err);
            }
            if let Err(err) = copy_async(file_in, file_out).await {
                assert!(false, "error running copy_async: {}", err);
            }
        });
        
        let mut bytes_in  = vec![];
        std::fs::File::open(file_in).unwrap().read_to_end(&mut bytes_in).unwrap();
        let mut hasher_in = std::collections::hash_map::DefaultHasher::new();
        hasher_in.write(&bytes_in);

        let mut bytes_out = vec![];
        std::fs::File::open(file_out).unwrap().read_to_end(&mut bytes_out).unwrap();
        let mut hasher_out = std::collections::hash_map::DefaultHasher::new();
        hasher_out.write(&bytes_out);

        assert_eq!(hasher_in.finish(), hasher_out.finish(), "Cloned file {} is different than source {}", file_out, file_in);
        
        std::fs::remove_file(file_in).unwrap();
        std::fs::remove_file(file_out).unwrap();
    }
}

mod byte_record;
mod error;
mod string_record;

mod async_reader_builder;
#[cfg(not(feature = "tokio"))]
mod async_reader_futures;
#[cfg(feature = "tokio")]
mod async_reader_tokio;

mod async_writer_builder;
#[cfg(not(feature = "tokio"))]
mod async_writer_futures;
#[cfg(feature = "tokio")]
mod async_writer_tokio;

// pub mod cookbook;
// pub mod tutorial;


pub use crate::byte_record::{ByteRecord, ByteRecordIter, Position};
pub use crate::error::{
    Error, ErrorKind, FromUtf8Error, IntoInnerError, Result, Utf8Error,
};
pub use crate::string_record::{StringRecord, StringRecordIter};

pub use crate::async_reader_builder::AsyncReaderBuilder;
#[cfg(not(feature = "tokio"))]
pub use crate::async_reader_futures::{
    AsyncReader, ByteRecordsIntoStream, ByteRecordsStream,
    StringRecordsIntoStream, StringRecordsStream,
};
#[cfg(feature = "tokio")]
pub use crate::async_reader_tokio::{
    AsyncReader, ByteRecordsIntoStream, ByteRecordsStream,
    StringRecordsIntoStream, StringRecordsStream,
};

pub use crate::async_writer_builder::AsyncWriterBuilder;
#[cfg(not(feature = "tokio"))]
pub use crate::async_writer_futures::AsyncWriter;
#[cfg(feature = "tokio")]
pub use crate::async_writer_tokio::AsyncWriter;


/// The quoting style to use when writing CSV data.
#[derive(Clone, Copy, Debug)]
pub enum QuoteStyle {
    /// This puts quotes around every field. Always.
    Always,
    /// This puts quotes around fields only when necessary.
    ///
    /// They are necessary when fields contain a quote, delimiter or record
    /// terminator. Quotes are also necessary when writing an empty record
    /// (which is indistinguishable from a record with one empty field).
    ///
    /// This is the default.
    Necessary,
    /// This puts quotes around all fields that are non-numeric. Namely, when
    /// writing a field that does not parse as a valid float or integer, then
    /// quotes will be used even if they aren't strictly necessary.
    NonNumeric,
    /// This *never* writes quotes, even if it would produce invalid CSV data.
    Never,
    /// Hints that destructuring should not be exhaustive.
    ///
    /// This enum may grow additional variants, so this makes sure clients
    /// don't count on exhaustive matching. (Otherwise, adding a new variant
    /// could break existing code.)
    #[doc(hidden)]
    __Nonexhaustive,
}

impl QuoteStyle {
    #[allow(dead_code)]
    fn to_core(self) -> csv_core::QuoteStyle {
        match self {
            QuoteStyle::Always => csv_core::QuoteStyle::Always,
            QuoteStyle::Necessary => csv_core::QuoteStyle::Necessary,
            QuoteStyle::NonNumeric => csv_core::QuoteStyle::NonNumeric,
            QuoteStyle::Never => csv_core::QuoteStyle::Never,
            _ => unreachable!(),
        }
    }
}

impl Default for QuoteStyle {
    fn default() -> QuoteStyle {
        QuoteStyle::Necessary
    }
}

/// A record terminator.
///
/// Use this to specify the record terminator while parsing CSV. The default is
/// CRLF, which treats `\r`, `\n` or `\r\n` as a single record terminator.
#[derive(Clone, Copy, Debug)]
pub enum Terminator {
    /// Parses `\r`, `\n` or `\r\n` as a single record terminator.
    CRLF,
    /// Parses the byte given as a record terminator.
    Any(u8),
    /// Hints that destructuring should not be exhaustive.
    ///
    /// This enum may grow additional variants, so this makes sure clients
    /// don't count on exhaustive matching. (Otherwise, adding a new variant
    /// could break existing code.)
    #[doc(hidden)]
    __Nonexhaustive,
}

impl Terminator {
    /// Convert this to the csv_core type of the same name.
    fn to_core(self) -> csv_core::Terminator {
        match self {
            Terminator::CRLF => csv_core::Terminator::CRLF,
            Terminator::Any(b) => csv_core::Terminator::Any(b),
            _ => unreachable!(),
        }
    }
}

impl Default for Terminator {
    fn default() -> Terminator {
        Terminator::CRLF
    }
}

/// The whitespace preservation behavior when reading CSV data.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Trim {
    /// Preserves fields and headers. This is the default.
    None,
    /// Trim whitespace from headers.
    Headers,
    /// Trim whitespace from fields, but not headers.
    Fields,
    /// Trim whitespace from fields and headers.
    All,
    /// Hints that destructuring should not be exhaustive.
    ///
    /// This enum may grow additional variants, so this makes sure clients
    /// don't count on exhaustive matching. (Otherwise, adding a new variant
    /// could break existing code.)
    #[doc(hidden)]
    __Nonexhaustive,
}

impl Trim {
    fn should_trim_fields(&self) -> bool {
        self == &Trim::Fields || self == &Trim::All
    }

    fn should_trim_headers(&self) -> bool {
        self == &Trim::Headers || self == &Trim::All
    }
}

impl Default for Trim {
    fn default() -> Trim {
        Trim::None
    }
}