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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use std::result;

use futures::io::{self, AsyncWrite};

use crate::AsyncWriterBuilder;
use crate::byte_record::ByteRecord;
use crate::error::Result;
use super::AsyncWriterImpl;

impl AsyncWriterBuilder {
    /// 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;
    ///
    /// # fn main() { async_std::task::block_on(async {example().await.unwrap()}); }
    /// 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(())
    /// }
    /// ```
    pub fn create_writer<W: AsyncWrite + Unpin>(&self, wtr: W) -> AsyncWriter<W> {
        AsyncWriter::new(self, wtr)
    }
}

/// An already configured CSV writer.
///
/// 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`](struct.AsyncWriterBuilder.html).
/// 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.
#[derive(Debug)]
pub struct AsyncWriter<W: AsyncWrite + Unpin>(AsyncWriterImpl<W>);

impl<W: AsyncWrite + Unpin> AsyncWriter<W> {
    fn new(builder: &AsyncWriterBuilder, wtr: W) -> AsyncWriter<W> {
        AsyncWriter(AsyncWriterImpl::new(builder, wtr))
    }

    /// 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;
    ///
    /// # fn main() { async_std::task::block_on(async {example().await.unwrap()}); }
    /// 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(())
    /// }
    /// ```
    pub fn from_writer(wtr: W) -> AsyncWriter<W> {
        AsyncWriterBuilder::new().create_writer(wtr)
    }

    /// 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;
    ///
    /// # fn main() { async_std::task::block_on(async {example().await.unwrap()}); }
    /// 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(())
    /// }
    /// ```
    #[inline]
    pub async fn write_record<I, T>(&mut self, record: I) -> Result<()>
    where
        I: IntoIterator<Item = T>,
        T: AsRef<[u8]>,
    {
        self.0.write_record(record).await
    }

    /// 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};
    ///
    /// # fn main() { async_std::task::block_on(async {example().await.unwrap()}); }
    /// 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(())
    /// }
    /// ```
    #[inline]
    pub async fn write_byte_record(&mut self, record: &ByteRecord) -> Result<()> {
        self.0.write_byte_record(record).await
    }

    /// 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;
    ///
    /// # fn main() { async_std::task::block_on(async {example().await.unwrap()}); }
    /// 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(())
    /// }
    /// ```
    #[inline]
    pub async fn write_field<T: AsRef<[u8]>>(&mut self, field: T) -> Result<()> {
        self.0.write_field(field).await
    }

    /// 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.
    #[inline]
    pub async fn flush(&mut self) -> io::Result<()> {
        self.0.flush().await
    }

    /// Flush the contents of the internal buffer and return the underlying writer.
    /// 
    pub async fn into_inner(
        self,
    ) -> result::Result<W, io::Error> {
        match self.0.into_inner().await {
            Ok(w) => Ok(w),
            Err(err) => Err(err.into_error()),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::pin::Pin;
    use std::task::{Context, Poll};
    
    use futures::io;

    use crate::byte_record::ByteRecord;
    use crate::error::ErrorKind;
    use crate::string_record::StringRecord;

    use super::{AsyncWriter, AsyncWriterBuilder};

    async fn wtr_as_string<'w>(wtr: AsyncWriter<Vec<u8>>) -> String {
        String::from_utf8(wtr.into_inner().await.unwrap()).unwrap()
    }

    #[async_std::test]
    async fn one_record() {
        let mut wtr = AsyncWriter::from_writer(vec![]);
        wtr.write_record(&["a", "b", "c"]).await.unwrap();

        assert_eq!(wtr_as_string(wtr).await, "a,b,c\n");
    }

    #[async_std::test]
    async fn one_string_record() {
        let mut wtr = AsyncWriter::from_writer(vec![]);
        wtr.write_record(&StringRecord::from(vec!["a", "b", "c"])).await.unwrap();

        assert_eq!(wtr_as_string(wtr).await, "a,b,c\n");
    }

    #[async_std::test]
    async fn one_byte_record() {
        let mut wtr = AsyncWriter::from_writer(vec![]);
        wtr.write_record(&ByteRecord::from(vec!["a", "b", "c"])).await.unwrap();

        assert_eq!(wtr_as_string(wtr).await, "a,b,c\n");
    }

    #[async_std::test]
    async fn raw_one_byte_record() {
        let mut wtr = AsyncWriter::from_writer(vec![]);
        wtr.write_byte_record(&ByteRecord::from(vec!["a", "b", "c"])).await.unwrap();

        assert_eq!(wtr_as_string(wtr).await, "a,b,c\n");
    }

    #[async_std::test]
    async fn one_empty_record() {
        let mut wtr = AsyncWriter::from_writer(vec![]);
        wtr.write_record(&[""]).await.unwrap();

        assert_eq!(wtr_as_string(wtr).await, "\"\"\n");
    }

    #[async_std::test]
    async fn raw_one_empty_record() {
        let mut wtr = AsyncWriter::from_writer(vec![]);
        wtr.write_byte_record(&ByteRecord::from(vec![""])).await.unwrap();

        assert_eq!(wtr_as_string(wtr).await, "\"\"\n");
    }

    #[async_std::test]
    async fn two_empty_records() {
        let mut wtr = AsyncWriter::from_writer(vec![]);
        wtr.write_record(&[""]).await.unwrap();
        wtr.write_record(&[""]).await.unwrap();

        assert_eq!(wtr_as_string(wtr).await, "\"\"\n\"\"\n");
    }

    #[async_std::test]
    async fn raw_two_empty_records() {
        let mut wtr = AsyncWriter::from_writer(vec![]);
        wtr.write_byte_record(&ByteRecord::from(vec![""])).await.unwrap();
        wtr.write_byte_record(&ByteRecord::from(vec![""])).await.unwrap();

        assert_eq!(wtr_as_string(wtr).await, "\"\"\n\"\"\n");
    }

    #[async_std::test]
    async fn unequal_records_bad() {
        let mut wtr = AsyncWriter::from_writer(vec![]);
        wtr.write_record(&ByteRecord::from(vec!["a", "b", "c"])).await.unwrap();
        let err = wtr.write_record(&ByteRecord::from(vec!["a"])).await.unwrap_err();
        match *err.kind() {
            ErrorKind::UnequalLengths { ref pos, expected_len, len } => {
                assert!(pos.is_none());
                assert_eq!(expected_len, 3);
                assert_eq!(len, 1);
            }
            ref x => {
                panic!("expected UnequalLengths error, but got '{:?}'", x);
            }
        }
    }

    #[async_std::test]
    async fn raw_unequal_records_bad() {
        let mut wtr = AsyncWriter::from_writer(vec![]);
        wtr.write_byte_record(&ByteRecord::from(vec!["a", "b", "c"])).await.unwrap();
        let err =
            wtr.write_byte_record(&ByteRecord::from(vec!["a"])).await.unwrap_err();
        match *err.kind() {
            ErrorKind::UnequalLengths { ref pos, expected_len, len } => {
                assert!(pos.is_none());
                assert_eq!(expected_len, 3);
                assert_eq!(len, 1);
            }
            ref x => {
                panic!("expected UnequalLengths error, but got '{:?}'", x);
            }
        }
    }

    #[async_std::test]
    async fn unequal_records_ok() {
        let mut wtr = AsyncWriterBuilder::new().flexible(true).create_writer(vec![]);
        wtr.write_record(&ByteRecord::from(vec!["a", "b", "c"])).await.unwrap();
        wtr.write_record(&ByteRecord::from(vec!["a"])).await.unwrap();
        assert_eq!(wtr_as_string(wtr).await, "a,b,c\na\n");
    }

    #[async_std::test]
    async fn raw_unequal_records_ok() {
        let mut wtr = AsyncWriterBuilder::new().flexible(true).create_writer(vec![]);
        wtr.write_byte_record(&ByteRecord::from(vec!["a", "b", "c"])).await.unwrap();
        wtr.write_byte_record(&ByteRecord::from(vec!["a"])).await.unwrap();
        assert_eq!(wtr_as_string(wtr).await, "a,b,c\na\n");
    }

    #[async_std::test]
    async fn full_buffer_should_not_flush_underlying() {
        #[derive(Debug)]
        struct MarkWriteAndFlush(Vec<u8>);

        impl MarkWriteAndFlush {
            fn to_str(self) -> String {
                String::from_utf8(self.0).unwrap()
            }
        }

        impl io::AsyncWrite for MarkWriteAndFlush {
            fn poll_write(
                mut self: Pin<&mut Self>,
                _: &mut Context,
                buf: &[u8]
            ) -> Poll<Result<usize, io::Error>> {
                use std::io::Write;
                self.0.write(b">").unwrap();
                let written = self.0.write(buf).unwrap();
                assert_eq!(written, buf.len());
                self.0.write(b"<").unwrap();
                // AsyncWriteExt::write_all panics if write returns more than buf.len()
                // Poll::Ready(Ok(written + 2))
                Poll::Ready(Ok(written))
            }

            fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context) -> Poll<Result<(), io::Error>> {
                use std::io::Write;
                self.0.write(b"!").unwrap();
                Poll::Ready(Ok(()))
            }

            fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> {
                self.poll_flush(cx)
            }
        }

        let underlying = MarkWriteAndFlush(vec![]);
        let mut wtr =
            AsyncWriterBuilder::new().buffer_capacity(4).create_writer(underlying);

        wtr.write_byte_record(&ByteRecord::from(vec!["a", "b"])).await.unwrap();
        wtr.write_byte_record(&ByteRecord::from(vec!["c", "d"])).await.unwrap();
        wtr.flush().await.unwrap();
        wtr.write_byte_record(&ByteRecord::from(vec!["e", "f"])).await.unwrap();

        let got = wtr.into_inner().await.unwrap().to_str();

        // As the buffer size is 4 we should write each record separately, and
        // flush when explicitly called and implictly in into_inner.
        assert_eq!(got, ">a,b\n<>c,d\n<!>e,f\n<!");
    }
}