string_dataframe 0.1.0

Reading in data from in parquet-file in a textual format to be printed out in the console or serialized as csv.
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use crate::data_frame_list::DataFrameList;
use crate::utils::{csv_header, is_hashmap_dataframe, remove_trailing_comma};
use std::collections::HashMap;
use std::convert::From;
use std::convert::TryFrom;
use std::fmt;
use term_table::row::Row;
use term_table::table_cell::{Alignment, TableCell};
use term_table::{Table, TableStyle};

#[derive(Debug)]
pub enum DataFrameErrors {
    DifferrentNumberRows,
    EmptyDataFrame,
    ColumnDoesNotExist,
    RowDoesNotExist,
    CouldNotOpenFile,
}

pub struct CSVDataFrame {
    data: HashMap<String, Vec<String>>,
}
impl Default for CSVDataFrame {
    fn default() -> Self {
        Self::new()
    }
}
impl<const N: usize> From<[(String, Vec<String>); N]> for CSVDataFrame {
    fn from(array: [(String, Vec<String>); N]) -> Self {
        CSVDataFrame {
            data: HashMap::from(array),
        }
    }
}

impl From<DataFrameList> for CSVDataFrame {
    fn from(data_frames: DataFrameList) -> Self {
        CSVDataFrame {
            data: data_frames
                .iter()
                .fold(HashMap::new(), |all_dataframes, next_dataframe| {
                    all_dataframes
                        .into_iter()
                        .chain(next_dataframe.data.clone())
                        .collect()
                }),
        }
    }
}
impl TryFrom<HashMap<String, Vec<String>>> for CSVDataFrame {
    type Error = DataFrameErrors;
    fn try_from(mut data_frame: HashMap<String, Vec<String>>) -> Result<Self, DataFrameErrors> {
        match is_hashmap_dataframe(&mut data_frame) {
            true => Ok(CSVDataFrame { data: data_frame }),
            false => Err(DataFrameErrors::DifferrentNumberRows),
        }
    }
}

impl CSVDataFrame {
    pub fn new() -> Self {
        CSVDataFrame {
            data: HashMap::new(),
        }
    }
    pub fn n_cols(&self) -> usize {
        self.data.len()
    }
    pub fn n_rows(&self) -> usize {
        if self.n_cols() == 0 {
            0
        } else {
            // `unwrap` is safe here because we checked earlier
            // that the dataframe has at least one column.
            self.data.iter().next().unwrap().1.len()
        }
    }
    fn get_column_names(&self) -> Vec<String> {
        self.data
            .iter()
            .map(|(column_name, _)| column_name.to_string())
            .collect()
    }
    fn get_sorted_columns_names(&self) -> Vec<String> {
        let mut columns = self.get_column_names();
        columns.sort();
        columns
    }
    #[allow(dead_code)]
    fn get_column(&self, column_name: &str) -> Result<&Vec<String>, DataFrameErrors> {
        if self.data.contains_key(column_name) {
            Ok(self.data.get_key_value(column_name).unwrap().1)
        } else {
            Err(DataFrameErrors::ColumnDoesNotExist)
        }
    }
    fn get_row(&self, row_idx: usize) -> Result<HashMap<String, String>, DataFrameErrors> {
        if self.n_rows() <= row_idx {
            Err(DataFrameErrors::RowDoesNotExist)
        } else {
            Ok(self
                .data
                .iter()
                .map(|(column_name, column_values)| {
                    (column_name.clone(), column_values[row_idx].clone())
                })
                .collect())
        }
    }
    pub fn to_csv(&self) -> String {
        csv_header(self.get_sorted_columns_names())
            + &self.csv_body(self.get_sorted_columns_names())
    }
    fn csv_body(&self, columns: Vec<String>) -> String {
        (0..self.n_rows())
            .map(|row_idx| self.csv_row(&columns, row_idx))
            .collect::<String>()
    }
    fn csv_row(&self, columns: &Vec<String>, row_idx: usize) -> String {
        remove_trailing_comma(
            columns
                .iter()
                .map(|column_name| {
                    self.get_row(row_idx)
                        .unwrap()
                        .get(column_name)
                        .unwrap()
                        .to_owned()
                        + ","
                })
                .collect::<String>()
                + "\n",
        )
    }
}

impl fmt::Display for CSVDataFrame {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Init table
        let mut table = Table::new();
        table.style = TableStyle::simple();

        // Columns as first row
        let mut columns = self.get_column_names();
        columns.sort();
        table.add_row(Row::new(columns.iter().map(|column| {
            TableCell::new_with_alignment(column, 2, Alignment::Center)
        })));

        // Add data as the other rows.
        for row_idx in 0..self.n_rows() {
            table.add_row(Row::new(columns.iter().map(|column_name| {
                TableCell::new_with_alignment(
                    self.get_row(row_idx).unwrap().get(column_name).unwrap(),
                    2,
                    Alignment::Center,
                )
            })));
        }
        write!(f, "{}", table.render())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    mod test_from_dataframe_list {
        use super::*;
        #[test]
        fn from_simple_dataframe_list() {
            let mut my_test_dataframe_list = DataFrameList::new();
            let _ = my_test_dataframe_list.push(
                CSVDataFrame::try_from(HashMap::from([(
                    String::from("column-0-list-0"),
                    vec![String::from("value-0-0"), String::from("value-0-1")],
                )]))
                .unwrap(),
            );
            let _ = my_test_dataframe_list.push(
                CSVDataFrame::try_from(HashMap::from([(
                    String::from("column-0-list-1"),
                    vec![String::from("value-0-0"), String::from("value-0-1")],
                )]))
                .unwrap(),
            );

            let my_test_dataframe = CSVDataFrame::from(my_test_dataframe_list);

            assert_eq!(
                my_test_dataframe.data,
                HashMap::from([
                    (
                        String::from("column-0-list-0"),
                        vec![String::from("value-0-0"), String::from("value-0-1")],
                    ),
                    (
                        String::from("column-0-list-1"),
                        vec![String::from("value-0-0"), String::from("value-0-1")],
                    ),
                ])
            );
        }
    }
    mod test_from_tuple_list {
        use super::*;
        #[test]
        fn sucess_from_list() {
            let my_test_dataframe = CSVDataFrame::try_from(HashMap::from([
                (
                    String::from("column-0-list-0"),
                    vec![String::from("value-0-0"), String::from("value-0-1")],
                ),
                (
                    String::from("column-0-list-1"),
                    vec![String::from("value-0-0"), String::from("value-0-1")],
                ),
            ]))
            .unwrap();

            assert_eq!(
                my_test_dataframe.data,
                HashMap::from([
                    (
                        String::from("column-0-list-0"),
                        vec![String::from("value-0-0"), String::from("value-0-1")],
                    ),
                    (
                        String::from("column-0-list-1"),
                        vec![String::from("value-0-0"), String::from("value-0-1")],
                    ),
                ])
            );
        }
        #[test]
        fn failure_from_list() {
            let error = CSVDataFrame::try_from(HashMap::from([
                (
                    String::from("column-0-list-0"),
                    vec![
                        String::from("value-0-0"),
                        String::from("value-0-1"),
                        String::from("value-0-1"),
                    ],
                ),
                (
                    String::from("column-0-list-1"),
                    vec![String::from("value-0-0"), String::from("value-0-1")],
                ),
            ]));

            assert!(matches!(
                error.err().unwrap(),
                DataFrameErrors::DifferrentNumberRows
            ));
        }
    }
    mod test_column_names {
        use super::*;
        #[test]
        fn get_three_column_names() {
            assert_eq!(
                test_utils::get_simple_dataframe().get_column_names().sort(),
                vec![
                    String::from("column-1"),
                    String::from("column-2"),
                    String::from("column-3"),
                ]
                .sort()
            )
        }
        #[test]
        fn get_no_column_names() {
            assert_eq!(CSVDataFrame::new().get_column_names(), Vec::<String>::new());
        }
    }
    mod test_get_column {
        use super::*;
        #[test]
        fn get_three_columns() {
            let my_data = test_utils::get_simple_dataframe();
            assert_eq!(
                my_data.get_column("column-0").unwrap(),
                &vec![String::from("value-0-0"), String::from("value-0-1")]
            );
            assert_eq!(
                my_data.get_column("column-1").unwrap(),
                &vec![String::from("value-1-0"), String::from("value-1-1")]
            );
            assert_eq!(
                my_data.get_column("column-2").unwrap(),
                &vec![String::from("value-2-0"), String::from("value-2-1")]
            );
        }
        #[test]
        fn get_nonexisting_column() {
            assert!(matches!(
                CSVDataFrame::new().get_column("column_name").err().unwrap(),
                DataFrameErrors::ColumnDoesNotExist
            ));
        }
    }
    mod test_get_row {
        use super::*;
        #[test]
        fn get_existing_rows() {
            let my_data = test_utils::get_simple_dataframe();

            assert_eq!(
                my_data.get_row(0).unwrap(),
                test_utils::get_hash_map(vec![
                    (String::from("column-0"), String::from("value-0-0")),
                    (String::from("column-1"), String::from("value-1-0")),
                    (String::from("column-2"), String::from("value-2-0"))
                ])
            );
            assert_eq!(
                my_data.get_row(1).unwrap(),
                test_utils::get_hash_map(vec![
                    (String::from("column-0"), String::from("value-0-1")),
                    (String::from("column-1"), String::from("value-1-1")),
                    (String::from("column-2"), String::from("value-2-1"))
                ])
            );
        }
        #[test]
        fn get_non_existing_row() {
            assert!(matches!(
                test_utils::get_simple_dataframe().get_row(2).err().unwrap(),
                DataFrameErrors::RowDoesNotExist
            ));
        }
        #[test]
        fn get_row_empty_dataframe() {
            assert!(matches!(
                CSVDataFrame::new().get_row(0).err().unwrap(),
                DataFrameErrors::RowDoesNotExist
            ));
        }
    }
    mod test_nrows {
        use super::*;
        #[test]
        fn two_rows() {
            assert_eq!(test_utils::get_simple_dataframe().n_rows(), 2);
        }
        #[test]
        fn empty_dataframe() {
            assert_eq!(CSVDataFrame::new().n_rows(), 0);
        }
    }
    mod test_ncols {
        use super::*;
        #[test]
        fn three_columns() {
            assert_eq!(test_utils::get_simple_dataframe().n_cols(), 3);
        }
        #[test]
        fn empty_dataframe() {
            assert_eq!(CSVDataFrame::new().n_cols(), 0);
        }
    }
    mod test_format {
        use super::*;
        #[test]
        fn test_simple_dataframe() {
            assert_eq!(
                "+------------+------------+------------+\n\
                |  column-0  |  column-1  |  column-2  |\n\
                +------------+------------+------------+\n\
                |  value-0-0 |  value-1-0 |  value-2-0 |\n\
                +------------+------------+------------+\n\
                |  value-0-1 |  value-1-1 |  value-2-1 |\n\
                +------------+------------+------------+\n",
                format!("{}", test_utils::get_simple_dataframe())
            )
        }
    }
    mod test_to_csv {
        use super::*;
        #[test]
        fn test_simple_dataframe() {
            assert_eq!(
                "column-0,column-1,column-2\n\
            value-0-0,value-1-0,value-2-0\n\
            value-0-1,value-1-1,value-2-1\n",
                test_utils::get_simple_dataframe().to_csv()
            )
        }
    }
    mod test_csv_row {
        use super::*;
        #[test]
        fn simple_data_test_row_1_all_cols() {
            assert_eq!(
                String::from("value-0-0,value-1-0,value-2-0\n"),
                test_utils::get_simple_dataframe().csv_row(
                    &vec![
                        String::from("column-0"),
                        String::from("column-1"),
                        String::from("column-2")
                    ],
                    0
                )
            )
        }
        #[test]
        fn simple_data_test_row_1_two_cols() {
            assert_eq!(
                String::from("value-0-0,value-1-0\n"),
                test_utils::get_simple_dataframe().csv_row(
                    &vec![String::from("column-0"), String::from("column-1"),],
                    0
                )
            )
        }
        #[test]
        fn simple_data_test_row_2_all_cols() {
            assert_eq!(
                String::from("value-0-1,value-1-1,value-2-1\n"),
                test_utils::get_simple_dataframe().csv_row(
                    &vec![
                        String::from("column-0"),
                        String::from("column-1"),
                        String::from("column-2")
                    ],
                    1
                )
            )
        }
    }
    mod test_csv_body {
        use super::*;
        #[test]
        fn simple_data_test() {
            assert_eq!(
                String::from("value-0-0,value-1-0,value-2-0\nvalue-0-1,value-1-1,value-2-1\n"),
                test_utils::get_simple_dataframe().csv_body(vec![
                    String::from("column-0"),
                    String::from("column-1"),
                    String::from("column-2")
                ],)
            )
        }
    }
    mod test_utils {
        use super::*;
        pub fn get_simple_dataframe() -> CSVDataFrame {
            CSVDataFrame::try_from(HashMap::from([
                (
                    String::from("column-0"),
                    vec![String::from("value-0-0"), String::from("value-0-1")],
                ),
                (
                    String::from("column-1"),
                    vec![String::from("value-1-0"), String::from("value-1-1")],
                ),
                (
                    String::from("column-2"),
                    vec![String::from("value-2-0"), String::from("value-2-1")],
                ),
            ]))
            .unwrap()
        }
        pub fn get_hash_map<T>(elems: Vec<(T, T)>) -> HashMap<T, T>
        where
            T: std::cmp::Eq + std::hash::Hash,
        {
            let mut hashmap = HashMap::new();
            for (key, value) in elems {
                hashmap.insert(key, value);
            }
            hashmap
        }
    }
}