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
418
419
420
421
422
423
424
425
426
use std::vec;

use crate::{
    add_with, error,

    add::Add, add::ColSpec, flush::Flush, headers::Headers, inspect::Inspect,
    reduce::Reduce, Row, RowResult, add_with::AddWith, del::Del,
    adjacent_group::AdjacentGroup, MockStream, rename::Rename, select::Select,
    reduce::aggregate::Aggregate,

    map::{MapRow, MapCol},

    group::{Group, GroupCriteria},

    filter::{FilterCol, FilterRow},
};

/// This trait describes de behaviour of every component in the CSV transformation
/// chain. Functions provided by this trait help construct the chain and can be
/// _chained_.
///
/// Implement this trait to extend `csvsc` with your own processors.
pub trait RowStream: IntoIterator<Item = RowResult> {

    /// Must return headers as they are in this point of the chain. For example
    /// if implementor adds a column, its `headers()` function must return the
    /// new headers including the one just added.
    fn headers(&self) -> &Headers;

    /// Add a column to each row of the stream.
    ///
    /// New columns can be build arbitrarily from previous columns or from a
    /// specific column using a regular expression.
    ///
    /// ```
    /// use csvsc::prelude::*;
    /// use encoding::all::UTF_8;
    ///
    /// let mut chain = InputStreamBuilder::from_paths(&["test/assets/1.csv"])
    ///     .unwrap().build().unwrap()
    ///     .add(
    ///         Column::with_name("new column")
    ///             .from_all_previous()
    ///             .definition("{old col1} - {old col2}")
    ///     ).unwrap();
    /// ```
    ///
    /// See [`Column`](struct.Column.html) for options.
    ///
    /// If you want to add a constant value or have some other requirement take
    /// a look at `.add_with()`.
    #[inline]
    fn add(self, column: ColSpec) -> error::Result<Add<Self>>
    where
        Self: Sized,
    {
        Add::new(self, column)
    }

    /// Deletes the specified columns from each row of the stream. If you have
    /// too many columns to delete perhaps instead use [`RowStream::select`].
    #[inline]
    fn del(self, columns: Vec<&str>) -> Del<Self>
    where
        Self: Sized,
    {
        Del::new(self, columns)
    }

    /// Outputs only the selected columns, ignoring the rest.
    ///
    /// The returned rows contain its values in the order corresponding to the
    /// order in which the headers were given to this function. That means that
    /// this function can be used to reorder the headers.
    ///
    /// If you only want do delete specific columns take a look at
    /// [`RowStream::del`].
    #[inline]
    fn select(self, columns: Vec<&str>) -> Select<Self>
    where
        Self: Sized,
    {
        Select::new(self, columns)
    }

    /// Adds a column to each row of the stream using a closure to compute its
    /// value.
    ///
    /// This you can use to add a constant value also.
    ///
    /// ## Example
    ///
    /// ```
    /// use csvsc::prelude::*;
    /// use encoding::all::UTF_8;
    ///
    /// let mut chain = InputStreamBuilder::from_paths(&["test/assets/1.csv"])
    ///     .unwrap().build().unwrap()
    ///     .add_with("new col", |headers, row| {
    ///         Ok("value".into())
    ///     }).unwrap();
    /// ```
    #[inline]
    fn add_with<F>(self, colname: &str, f: F) -> Result<AddWith<Self, F>, add_with::BuildError>
    where
        Self: Sized,
        F: FnMut(&Headers, &Row) -> error::Result<String>,
    {
        AddWith::new(self, colname, f)
    }

    /// Reduce all the incoming stream into one row, computing some aggregates
    /// in the way. All the stream collapses into one row.
    ///
    /// The final row contains only the result of reducers and no other column
    /// but you might preserve a column using the `.last()` aggregate.
    ///
    /// You'll likely be using this inside a `.group()` or `.adjacent_group()`.
    ///
    /// ## Example
    ///
    /// ```
    /// use csvsc::prelude::*;
    /// use encoding::all::UTF_8;
    ///
    /// let mut chain = InputStreamBuilder::from_paths(&["test/assets/chicken_north.csv"])
    ///     .unwrap().build().unwrap()
    ///     .group(["month"], |row_stream| {
    ///         row_stream
    ///             .reduce(vec![
    ///                 Reducer::with_name("avg").of_column("eggs per week").average().unwrap(),
    ///             ]).unwrap()
    ///     });
    /// ```
    ///
    /// See [`Reducer`](./struct.Reducer.html) for built-in aggregates.
    #[inline]
    fn reduce(
        self,
        columns: Vec<Box<dyn Aggregate>>,
    ) -> error::Result<Reduce<Self>>
    where
        Self: Sized,
    {
        Reduce::new(self, columns)
    }

    /// Groups rows by the given criteria, but assuming a "group" is a set of
    /// adjacent rows.
    ///
    /// This means that sets of rows that meet the same criteria but are not
    /// adjacent will not be grouped together. Only use it if you are sure that
    /// your data follows this pattern and you want to take advantage of it.
    ///
    /// An interesting advantage of using this is that only one group is kept in
    /// memory at a time.
    ///
    /// See [`RowStream::group`] for more details.
    ///
    /// ## Example
    ///
    /// Consider a file `test/assets/groups.csv` with this contents. Notice that
    /// there are four adjacent groups that have the same value for column
    /// `name`: two with value `a` and two with `b`.
    ///
    /// ```text
    /// name,value
    /// a,1
    /// a,1
    /// b,2
    /// b,2
    /// a,3
    /// a,3
    /// b,4
    /// b,4
    /// ```
    ///
    /// Then the following code works as expected, generating an average for all
    /// of the four adjacent groups that have the same value for column `name`.
    ///
    /// ```
    /// use csvsc::prelude::*;
    ///
    /// let mut rows = InputStreamBuilder::from_paths(&["test/assets/groups.csv"]).unwrap().build().unwrap()
    ///     .adjacent_group(["name"], |row_stream| {
    ///         row_stream
    ///             .reduce(vec![
    ///                 Reducer::with_name("name").of_column("name").last("").unwrap(),
    ///                 Reducer::with_name("avg").of_column("value").average().unwrap(),
    ///             ]).unwrap()
    ///     })
    ///     .into_iter();
    ///
    /// assert_eq!(rows.next().unwrap().unwrap(), Row::from(vec!["a", "1"]));
    /// assert_eq!(rows.next().unwrap().unwrap(), Row::from(vec!["b", "2"]));
    /// assert_eq!(rows.next().unwrap().unwrap(), Row::from(vec!["a", "3"]));
    /// assert_eq!(rows.next().unwrap().unwrap(), Row::from(vec!["b", "4"]));
    /// ```
    #[inline]
    fn adjacent_group<F, R, G>(
        self,
        grouping: G,
        f: F,
    ) -> AdjacentGroup<Self, F, G>
    where
        F: Fn(MockStream<vec::IntoIter<RowResult>>) -> R,
        R: RowStream,
        G: GroupCriteria,
        Self: Sized,
    {
        AdjacentGroup::new(self, f, grouping)
    }

    /// Groups rows by the given criteria. You'll be given a RowStream instance
    /// as the first argument of a closure that you can use to further process
    /// the grouped rows.
    ///
    /// The first argument is the group criteria and it can be any of:
    ///
    /// * A slice of `&str`: `&["foo", "bar"]`,
    /// * an array of `&str`: `["foo", "bar"]`,
    /// * a closure `Fn(&Headers, &Row) -> Hash`,
    /// * any type that implements
    /// [`GroupCriteria`](crate::group::GroupCriteria)
    ///
    /// In the first two cases the `&str`s are treated as column names. Rows
    /// having the same values for the specified columns will belong to the same
    /// group. Strings that don't match any column name will be ignored.
    ///
    /// In the closure case you'll be given the headers and every row and you
    /// must return a hashable type that identifies the group where that row
    /// belongs.
    ///
    /// [`GroupCriteria`](crate::group::GroupCriteria) is a trait you can
    /// implement for your own types if you want to use them as grouping
    /// criteria.
    ///
    /// ## Example
    ///
    /// Consider the following file:
    ///
    /// ```text
    /// name,value
    /// a,1
    /// a,1
    /// b,2
    /// b,2
    /// a,3
    /// a,3
    /// b,4
    /// b,4
    /// ```
    ///
    /// Then we can group for example using the column `name` and get the
    /// following results:
    ///
    /// ```
    /// use csvsc::prelude::*;
    ///
    /// let mut rows: Vec<_> = InputStreamBuilder::from_paths(&["test/assets/groups.csv"]).unwrap().build().unwrap()
    ///     .group(["name"], |row_stream| {
    ///         row_stream
    ///             .reduce(vec![
    ///                 Reducer::with_name("name").of_column("name").last("").unwrap(),
    ///                 Reducer::with_name("avg").of_column("value").average().unwrap(),
    ///             ]).unwrap()
    ///     })
    ///     .into_iter()
    ///     .filter_map(|r| r.ok())
    ///     .collect();
    ///
    /// rows.sort_by_key(|row| row.get(0).unwrap().to_string());
    ///
    /// assert_eq!(rows[0], Row::from(vec!["a", "2"]));
    /// assert_eq!(rows[1], Row::from(vec!["b", "3"]));
    /// ```
    ///
    /// ## Grouping by closure
    ///
    /// If you decide that you need an arbitrary grouping criteria you can use a
    /// closure that returns a hashable type like this:
    ///
    /// ```
    /// use csvsc::prelude::*;
    ///
    /// let mut rows: Vec<_> = InputStreamBuilder::from_paths(&["test/assets/groups.csv"]).unwrap().build().unwrap()
    ///     .group(|headers: &Headers, row: &Row| {
    ///         headers.get_field(row, "name").unwrap().to_string()
    ///     }, |row_stream| {
    ///         row_stream
    ///             .reduce(vec![
    ///                 Reducer::with_name("name").of_column("name").last("").unwrap(),
    ///                 Reducer::with_name("avg").of_column("value").average().unwrap(),
    ///             ]).unwrap()
    ///     })
    ///     .into_iter()
    ///     .filter_map(|r| r.ok())
    ///     .collect();
    ///
    /// rows.sort_by_key(|row| row.get(0).unwrap().to_string());
    ///
    /// assert_eq!(rows[0], Row::from(vec!["a", "2"]));
    /// assert_eq!(rows[1], Row::from(vec!["b", "3"]));
    /// ```
    #[inline]
    fn group<F, R, G>(
        self,
        grouping: G,
        f: F,
    ) -> Group<Self, F, G>
    where
        F: Fn(MockStream<vec::IntoIter<RowResult>>) -> R,
        R: RowStream,
        G: GroupCriteria,
        Self: Sized,
    {
        Group::new(self, f, grouping)
    }

    /// When consumed, writes to destination specified by the column given in
    /// the first argument. Other than that this behaves like an `id(x)`
    /// function so you can specify more links in the chain and even more
    /// flushers.
    #[inline]
    fn flush<T>(self, target: T) -> error::Result<Flush<Self, T>>
    where
        Self: Sized,
    {
        Flush::new(self, target)
    }

    /// Mostly for debugging, calls a closure on each element. Behaves like the
    /// identity function on the stream returning each row untouched.
    #[inline]
    fn review<F>(self, f: F) -> Inspect<Self, F>
    where
        Self: Sized,
        F: FnMut(&Headers, &RowResult),
    {
        Inspect::new(self, f)
    }

    /// Renames some columns
    #[inline]
    fn rename(self, old_name: &str, new_name: &str) -> Rename<Self>
    where
        Self: Sized,
    {
        Rename::new(self, old_name, new_name)
    }

    /// Apply a function to every row and use the return values to build the
    /// row stream.
    ///
    /// This method accepts a closure that must return an iterator over
    /// RowResult values, this means that you can create more rows out of a
    /// single one.
    ///
    /// You're responsible of providing the new headers and for that you need to
    /// use the second closure, that maps the old headers to the new ones.
    ///
    /// # Example
    ///
    /// ```
    /// use csvsc::prelude::*;
    /// use encoding::all::UTF_8;
    ///
    /// InputStreamBuilder::from_paths(&["test/assets/1.csv"])
    ///     .unwrap().build().unwrap()
    ///     .map_row(|_headers, row| {
    ///         // Go creative here in the creation of your new row(s)
    ///         Ok(vec![
    ///             Ok(row.clone())
    ///         ].into_iter())
    ///     }, |old_headers| {
    ///         // be responsible and provide proper headers from the old ones
    ///         old_headers.clone()
    ///     })
    ///     .into_iter();
    /// ```
    #[inline]
    fn map_row<F, H, R>(self, f: F, header_map: H) -> MapRow<Self, F>
    where
        Self: Sized,
        F: Fn(&Headers, &Row) -> error::Result<R>,
        H: Fn(&Headers) -> Headers,
        R: Iterator<Item = RowResult>,
    {
        let new_headers = (header_map)(self.headers());

        MapRow::new(self, f, new_headers)
    }

    /// Apply a function to a single column of the stream, this function dones't fail
    /// if the column dones't exist.
    #[inline]
    fn map_col<F>(self, col: &str, f: F) -> MapCol<Self, F>
    where
        Self: Sized,
        F: Fn(&str) -> error::Result<String>,
    {
        MapCol::new(self, col.into(), f)
    }

    /// filter entire rows out depending on one column's value and a
    /// condition, leaving errored rows untouched.
    #[inline]
    fn filter_col<F>(self, col: &str, f: F) -> error::Result<FilterCol<Self, F>>
    where
        Self: Sized,
        F: Fn(&str) -> bool,
    {
        FilterCol::new(self, col.into(), f)
    }

    /// filter entire rows out depending on one column's value and a
    /// condition, leaving errored rows untouched.
    #[inline]
    fn filter_row<F>(self, f: F) -> FilterRow<Self, F>
    where
        Self: Sized,
        F: Fn(&Headers, &Row) -> bool,
    {
        FilterRow::new(self, f)
    }
}