dcsv 0.3.3

Dyanmic csv reader,writer,editor
Documentation
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
414
415
416
417
//! Reader reads and parses given string into a csv struct
//!
//! You can also configure reader with multiple builder methods

use crate::error::{DcsvError, DcsvResult};
use crate::parser::Parser;
use crate::utils::ALPHABET;
use crate::value::Value;
use crate::virtual_data::VirtualData;
use crate::{Column, VCont, VirtualArray};
use std::io::BufRead;

/// Csv Reader
///
/// User can set various reader option to configure a reading behaviour.
/// Reader's options are not dropped after a read but persists for reader's lifetime.
///
/// # Usage
///
/// ```rust
/// use dcsv::Reader;
///
/// let csv_value = "a,b,c
/// 1,2,3";
///
/// let data = Reader::new()
///    .trim(true)
///    .ignore_empty_row(true)
///    .has_header(true)
///    .data_from_stream(csv_value.as_bytes());
/// ```
pub struct Reader {
    option: ReaderOption,
    parser: Parser,
}

impl Default for Reader {
    fn default() -> Self {
        Self::new()
    }
}

impl Reader {
    pub fn new() -> Self {
        Self {
            option: ReaderOption::new(),
            parser: Parser::new(),
        }
    }

    /// Build with reader option
    pub fn with_option(mut self, option: ReaderOption) -> Self {
        self.option = option;
        self
    }

    /// Consumes double quote in csv file
    pub fn consume_dquote(mut self, tv: bool) -> Self {
        self.option.consume_dquote = tv;
        self
    }

    /// Ignore empty rows
    ///
    /// This prevents reader from panicking on empty row.
    pub fn ignore_empty_row(mut self, tv: bool) -> Self {
        self.option.ignore_empty_row = tv;
        self
    }

    /// Trim all read values
    pub fn trim(mut self, tv: bool) -> Self {
        self.option.trim = tv;
        self
    }

    /// Allow invalid string while parsing csv values
    pub fn allow_invalid_string(mut self, allow: bool) -> Self {
        self.option.allow_invalid_string = allow;
        self
    }

    /// Whether csv data has header or not
    pub fn has_header(mut self, has_header: bool) -> Self {
        self.option.read_header = has_header;
        self
    }

    /// Set custom header
    ///
    /// This will override "has_header" option and create header from given values.
    pub fn custom_header<T: AsRef<str>>(mut self, headers: &[T]) -> Self {
        self.option.custom_header = headers.iter().map(|s| s.as_ref().to_owned()).collect();
        self
    }

    /// Clear reader option and set to default
    pub fn clear_reader_option(&mut self) {
        self.option = ReaderOption::new();
    }

    /// Use given delimiter instead of default one : ",".
    pub fn use_delimiter(mut self, delimiter: char) -> Self {
        self.option.delimiter.replace(delimiter);
        self
    }

    /// Use given line delimiter instead of default one : "\n, \r\n".
    ///
    /// Only default state will detect both "\n" and "\r\n". If you set "\n" manually, "\r\n" will
    /// be ignored.
    pub fn use_line_delimiter(mut self, delimiter: char) -> Self {
        self.parser.line_delimiter.replace(delimiter);
        self.option.line_delimiter.replace(delimiter);
        self
    }

    /// Read csv value from buf read stream
    ///
    /// This returns read value as virtual data struct
    pub fn data_from_stream(&mut self, mut csv_stream: impl BufRead) -> DcsvResult<VirtualData> {
        let mut row_buffer: Vec<u8> = vec![];
        let line_delimiter = self.option.line_delimiter.unwrap_or('\n') as u8;
        self.parser.reset();

        let mut num_bytes = csv_stream
            .read_until(line_delimiter, &mut row_buffer)
            .expect("Failed to read until");
        let mut data = VirtualData::new();
        let mut row_count = 1;
        while num_bytes != 0 {
            // Create column
            // Create row or continue to next line.
            let row = self.parser.feed_chunk(
                std::mem::take(&mut row_buffer),
                self.option.delimiter,
                self.option.consume_dquote,
                self.option.allow_invalid_string,
            )?;

            // Row has been detected
            if let Some(row) = row {
                // This is a trailing value after new line
                // Simply break
                if row.len() == 1 && row[0].trim().is_empty() {
                    // go to next line
                    if self.option.ignore_empty_row {
                        num_bytes = csv_stream
                            .read_until(line_delimiter, &mut row_buffer)
                            .expect("Failed to read until");
                        row_count += 1;
                        continue;
                    } else {
                        return Err(DcsvError::InvalidRowData(format!(
                                    "Row of line \"{}\" has empty row. Which is unallowed by reader option.",
                                    row_count + 1
                        )));
                    }
                }

                // Add column header if column is empty
                if data.get_column_count() == 0 {
                    if !self.option.custom_header.is_empty() {
                        if self.option.custom_header.len() != row.len() {
                            return Err(DcsvError::InvalidColumn(format!(
                                "Custom value has different length. Given {} but needs {}",
                                self.option.custom_header.len(),
                                row.len()
                            )));
                        }
                        let header = std::mem::take(&mut self.option.custom_header);
                        add_multiple_columns(&mut data, &header)?;
                    } else if self.option.read_header {
                        if self.option.trim {
                            // Trim row
                            add_multiple_columns(
                                &mut data,
                                &row.iter().map(|s| s.trim().to_owned()).collect::<Vec<_>>(),
                            )?;
                        } else {
                            // Don't trim
                            add_multiple_columns(&mut data, &row)?;
                        }
                        row_count += 1;
                        num_bytes = csv_stream
                            .read_until(line_delimiter, &mut row_buffer)
                            .expect("Failed to read until");
                        continue;
                    } else {
                        // Create a header
                        add_multiple_columns(&mut data, &make_arbitrary_column(row.len()))?;
                    }
                }

                // Given row data has different length with column
                if row.len() != data.get_column_count() {
                    data.drop_data();
                    return Err(DcsvError::InvalidRowData(format!(
                        "Row of line \"{}\" has different length.",
                        row_count
                    )));
                }

                if self.option.trim {
                    add_data_row(
                        &mut data,
                        row.iter().map(|s| s.trim().to_string()).collect::<Vec<_>>(),
                    )?;
                } else {
                    // Add as new row and proceed
                    add_data_row(&mut data, row)?;
                }
            }

            // advance row
            row_count += 1;
            num_bytes = csv_stream
                .read_until(line_delimiter, &mut row_buffer)
                .expect("Failed to read until");
        }

        Ok(data)
    }

    /// Read csv value from buf read stream
    ///
    /// This returns read value as virtual array struct
    pub fn array_from_stream(&mut self, mut csv_stream: impl BufRead) -> DcsvResult<VirtualArray> {
        let mut row_buffer: Vec<u8> = vec![];
        let line_delimiter = self.option.line_delimiter.unwrap_or('\n') as u8;
        self.parser.reset();

        let mut num_bytes = csv_stream
            .read_until(line_delimiter, &mut row_buffer)
            .expect("Failed to read until");
        let mut data = VirtualArray::new();
        let mut row_count = 1;
        while num_bytes != 0 {
            // Create column
            // Create row or continue to next line.
            let row = self.parser.feed_chunk(
                std::mem::take(&mut row_buffer),
                self.option.delimiter,
                self.option.consume_dquote,
                self.option.allow_invalid_string,
            )?;

            // Row has been detected
            if let Some(row) = row {
                // This is a trailing value after new line
                // Simply break
                if row.len() == 1 && row[0].trim().is_empty() {
                    // go to next line
                    if self.option.ignore_empty_row {
                        num_bytes = csv_stream
                            .read_until(line_delimiter, &mut row_buffer)
                            .expect("Failed to read until");
                        row_count += 1;
                        continue;
                    } else {
                        return Err(DcsvError::InvalidRowData(format!(
                                    "Row of line \"{}\" has empty row. Which is unallowed by reader option.",
                                    row_count + 1
                        )));
                    }
                }

                // Add column header if column is empty
                if data.get_column_count() == 0 {
                    if !self.option.custom_header.is_empty() {
                        if self.option.custom_header.len() != row.len() {
                            return Err(DcsvError::InvalidColumn(format!(
                                "Custom value has different length. Given {} but needs {}",
                                self.option.custom_header.len(),
                                row.len()
                            )));
                        }
                        let header = std::mem::take(&mut self.option.custom_header);
                        data.columns = header.iter().map(|h| Column::empty(h)).collect::<Vec<_>>();
                    } else if self.option.read_header {
                        if self.option.trim {
                            data.columns = row
                                .iter()
                                .map(|s| Column::empty(s.trim()))
                                .collect::<Vec<_>>();
                        } else {
                            data.columns = row.iter().map(|h| Column::empty(h)).collect::<Vec<_>>();
                        }
                        row_count += 1;
                        num_bytes = csv_stream
                            .read_until(line_delimiter, &mut row_buffer)
                            .expect("Failed to read until");
                        continue;
                    } else {
                        // Create a header
                        data.columns = make_arbitrary_column(row.len())
                            .iter()
                            .map(|h| Column::empty(h))
                            .collect::<Vec<_>>();
                    }
                }

                // Given row data has different length with column
                if row.len() != data.get_column_count() {
                    data.drop_data();
                    return Err(DcsvError::InvalidRowData(format!(
                        "Row of line \"{}\" has different length.",
                        row_count
                    )));
                }

                if self.option.trim {
                    add_array_row(
                        &mut data,
                        row.iter().map(|s| s.trim().to_owned()).collect::<Vec<_>>(),
                    )?;
                } else {
                    // Add as new row and proceed
                    add_array_row(&mut data, row)?;
                }
            }

            // advance row
            row_count += 1;
            num_bytes = csv_stream
                .read_until(line_delimiter, &mut row_buffer)
                .expect("Failed to read until");
        }

        Ok(data)
    }
}

// -----
// <DRY>
// DRY Codes
/// add new data row into a virtual data
fn add_data_row(data: &mut VirtualData, mut row: Vec<String>) -> DcsvResult<()> {
    data.insert_row(
        data.get_row_count(),
        Some(
            &row.iter_mut()
                .map(|val| Value::Text(std::mem::take(val)))
                .collect::<Vec<_>>(),
        ),
    )?;
    Ok(())
}

/// add new data row into a virtual array
fn add_array_row(data: &mut VirtualArray, mut row: Vec<String>) -> DcsvResult<()> {
    data.insert_row(
        data.get_row_count(),
        Some(
            &row.iter_mut()
                .map(|val| Value::Text(std::mem::take(val)))
                .collect::<Vec<_>>(),
        ),
    )?;
    Ok(())
}

/// Add multiple columns with given names
fn add_multiple_columns(data: &mut VirtualData, column_names: &[String]) -> DcsvResult<()> {
    for (idx, col) in column_names.iter().enumerate() {
        data.insert_column(idx, col.as_ref())?;
    }
    Ok(())
}

/// Create arbitrary column names
fn make_arbitrary_column(size: usize) -> Vec<String> {
    let mut column_names: Vec<String> = vec![];
    for index in 0..size {
        let index = index + 1;
        let target = ALPHABET[index % ALPHABET.len() - 1];
        let name = target.repeat(index / ALPHABET.len() + 1);
        column_names.push(name);
    }
    column_names
}
// </DRY>
// -----

/// Reader behaviour related options
pub struct ReaderOption {
    pub trim: bool,
    pub read_header: bool,
    pub consume_dquote: bool,
    pub custom_header: Vec<String>,
    pub delimiter: Option<char>,
    pub line_delimiter: Option<char>,
    pub ignore_empty_row: bool,
    pub allow_invalid_string: bool,
}

impl Default for ReaderOption {
    fn default() -> Self {
        Self::new()
    }
}

impl ReaderOption {
    /// Constructor
    pub fn new() -> Self {
        Self {
            trim: false,
            read_header: true,
            custom_header: vec![],
            consume_dquote: false,
            delimiter: None,
            line_delimiter: None,
            ignore_empty_row: false,
            allow_invalid_string: false,
        }
    }
}