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
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
//! Virtual data module

use crate::error::{DcsvError, DcsvResult};
use crate::value::{Value, ValueLimiter, ValueType};
use crate::vcont::VCont;
use std::cmp::Ordering;
use std::collections::HashMap;

/// Header for csv schema
pub const SCHEMA_HEADER: &str = "column,type,default,variant,pattern";

/// Virtual data struct which contains csv information
///
/// - VirtualData holds row information as hashmap. Therefore modifying data( cell, row or column ) is generally faster than virtual array struct.
/// - VirtualData cannot have duplicate column name due to previous hashmap implementaiton
/// - VirtualData allows limiters to confine csv value's possible states.
#[derive(Clone)]
pub struct VirtualData {
    pub columns: Vec<Column>,
    pub rows: Vec<Row>,
}

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

impl VCont for VirtualData {
    /// Create empty virtual data
    fn new() -> Self {
        Self {
            columns: vec![],
            rows: vec![],
        }
    }

    /// Move given row to a target row index
    fn move_row(&mut self, src_index: usize, target_index: usize) -> DcsvResult<()> {
        let row_count = self.get_row_count();
        if src_index >= row_count || target_index >= row_count {
            return Err(DcsvError::OutOfRangeError);
        }

        let move_direction = src_index.cmp(&target_index);
        match move_direction {
            // Go left
            Ordering::Greater => {
                let mut index = src_index;
                let mut next = index - 1;
                while next >= target_index {
                    self.rows.swap(index, next);

                    // Usize specific check code
                    if next == 0 {
                        break;
                    }

                    // Update index values
                    index -= 1;
                    next -= 1;
                }
            }
            Ordering::Less => {
                // Go right
                let mut index = src_index;
                let mut next = index + 1;
                while next <= target_index {
                    self.rows.swap(index, next);

                    // Update index values
                    index += 1;
                    next += 1;
                }
            }
            Ordering::Equal => (),
        }
        Ok(())
    }

    /// Move a given column to target column index
    fn move_column(&mut self, src_index: usize, target_index: usize) -> DcsvResult<()> {
        let column_count = self.get_column_count();
        if src_index >= column_count || target_index >= column_count {
            return Err(DcsvError::OutOfRangeError);
        }

        let move_direction = src_index.cmp(&target_index);
        match move_direction {
            // Go left
            Ordering::Greater => {
                let mut index = src_index;
                let mut next = index - 1;
                while next >= target_index {
                    self.columns.swap(index, next);

                    // Usize specific check code
                    if next == 0 {
                        break;
                    }

                    // Update index values
                    index -= 1;
                    next -= 1;
                }
            }
            Ordering::Less => {
                // Go right
                let mut index = src_index;
                let mut next = index + 1;
                while next <= target_index {
                    self.columns.swap(index, next);

                    // Update index values
                    index += 1;
                    next += 1;
                }
            }
            Ordering::Equal => (),
        }
        Ok(())
    }

    /// Rename a column
    ///
    /// Column's name cannot be an exsiting name
    ///
    /// * column   : column_index
    /// * new_name : New column name
    fn rename_column(&mut self, column_index: usize, new_name: &str) -> DcsvResult<()> {
        let next_column_index = self.try_get_column_index(new_name);

        if !self.is_valid_cell_coordinate(0, column_index) {
            return Err(DcsvError::OutOfRangeError);
        }

        if next_column_index.is_some() {
            return Err(DcsvError::InvalidColumn(format!(
                "Cannot rename to \"{}\" which already exists",
                &new_name
            )));
        }

        let previous = self.columns[column_index].rename(new_name);
        for row in &mut self.rows {
            row.rename_column(&previous, new_name);
        }
        Ok(())
    }

    /// Set values to a column
    ///
    /// Given value will override every row's value
    fn set_column(&mut self, column_index: usize, value: Value) -> DcsvResult<()> {
        if !self.is_valid_cell_coordinate(0, column_index) {
            return Err(DcsvError::OutOfRangeError);
        }

        let column = &self.columns[column_index].name;

        for row in &mut self.rows {
            row.update_cell_value(column, value.clone());
        }
        Ok(())
    }

    /// Edit a row
    ///
    /// Only edit row's cell when value is not none
    fn edit_row(&mut self, row_index: usize, values: &[Option<Value>]) -> DcsvResult<()> {
        // Row's value doesn't match length of columns
        if values.len() != self.get_column_count() {
            return Err(DcsvError::InsufficientRowData);
        }
        // Invalid cooridnate
        if !self.is_valid_cell_coordinate(row_index, 0) {
            return Err(DcsvError::OutOfRangeError);
        }

        let col_value_iter = self.columns.iter().zip(values.iter());

        for (col, value) in col_value_iter {
            if let Some(value) = value {
                // Early return if doesn't qualify a single element
                if !col.limiter.qualify(value) {
                    return Err(DcsvError::InvalidRowData(format!(
                        "\"{}\" doesn't qualify \"{}\"'s limiter",
                        value, col.name
                    )));
                }
            }
        }

        let col_value_iter = self.columns.iter().zip(values.iter());

        // It is safe to unwrap because row_number
        // was validated by is_valid_cell_coordinate method.
        let row = self.rows.get_mut(row_index).unwrap();
        for (col, value) in col_value_iter {
            if let Some(value) = value {
                row.update_cell_value(&col.name, value.clone())
            }
        }

        Ok(())
    }

    // TODO
    // 1. Check limiter
    // 2. Check if value exists
    /// Set values to a row
    ///
    /// This assumes that given values accord to column's order.
    /// This method will fail when given value fails to qualify column's limiter.
    fn set_row(&mut self, row_index: usize, values: &[Value]) -> DcsvResult<()> {
        // Row's value doesn't match length of columns
        if values.len() != self.get_column_count() {
            return Err(DcsvError::InsufficientRowData);
        }
        // Invalid cooridnate
        if !self.is_valid_cell_coordinate(row_index, 0) {
            return Err(DcsvError::OutOfRangeError);
        }

        let col_value_iter = self.columns.iter().zip(values.iter());

        for (col, value) in col_value_iter.clone() {
            // Early return if doesn't qualify a single element
            if !col.limiter.qualify(value) {
                return Err(DcsvError::InvalidRowData(format!(
                    "\"{}\" doesn't qualify \"{}\"'s limiter",
                    value, col.name
                )));
            }
        }

        // It is safe to unwrap because row_number
        // was validated by is_valid_cell_coordinate method.
        let row = self.rows.get_mut(row_index).unwrap();
        for (col, value) in col_value_iter {
            row.update_cell_value(&col.name, value.clone())
        }

        Ok(())
    }

    /// get cell data by coordinate
    fn get_cell(&self, x: usize, y: usize) -> Option<&Value> {
        if let Ok(column) = self.get_column_if_valid(x, y) {
            self.rows[x].get_cell_value(&column.name)
        } else {
            None
        }
    }

    /// Set cell value by coordinate
    fn set_cell(&mut self, x: usize, y: usize, value: Value) -> DcsvResult<()> {
        let name = self.get_column_if_valid(x, y)?.name.to_owned();

        self.is_valid_column_data(y, &value)?;
        self.rows[x].update_cell_value(&name, value);

        Ok(())
    }

    // THis should insert row with given column limiters
    /// Insert a row to given index
    ///
    /// This can yield out of rnage error
    fn insert_row(&mut self, row_index: usize, source: Option<&[Value]>) -> DcsvResult<()> {
        if row_index > self.get_row_count() {
            return Err(DcsvError::InvalidColumn(format!(
                "Cannot add row to out of range position : {}",
                row_index
            )));
        }
        let mut new_row = Row::new();
        if let Some(source) = source {
            self.check_row_length(source)?;
            let iter = self.columns.iter().zip(source.iter());

            for (col, value) in iter.clone() {
                if !col.limiter.qualify(value) {
                    return Err(DcsvError::InvalidRowData(format!(
                        "\"{}\" doesn't qualify \"{}\"'s limiter",
                        value, col.name
                    )));
                }
            }

            iter.for_each(|(col, v)| new_row.insert_cell(&col.name, v.clone()));
        } else {
            for col in &self.columns {
                new_row.insert_cell(&col.name, col.get_default_value());
            }
        }
        self.rows.insert(row_index, new_row);
        Ok(())
    }

    fn insert_column(&mut self, column_index: usize, column_name: &str) -> DcsvResult<()> {
        if column_index > self.get_column_count() {
            return Err(DcsvError::InvalidColumn(format!(
                "Cannot add column to out of range position : {}",
                column_index
            )));
        }
        if self.try_get_column_index(column_name).is_some() {
            return Err(DcsvError::InvalidColumn(format!(
                "Cannot add existing column = \"{}\"",
                column_name
            )));
        }
        let new_column = Column::new(column_name, ValueType::Text, None);
        let default_value = new_column.get_default_value();
        for row in &mut self.rows {
            row.insert_cell(&new_column.name, default_value.clone());
        }
        self.columns.insert(column_index, new_column);
        Ok(())
    }

    /// Delete a row with given row_index
    ///
    /// This doesn't fail but silently do nothing if index is out of range
    fn delete_row(&mut self, row_index: usize) -> bool {
        let row_count = self.get_row_count();
        if row_count == 0 || row_count < row_index {
            return false;
        }
        self.rows.remove(row_index);
        true
    }

    /// Delete a column with given column index
    fn delete_column(&mut self, column_index: usize) -> DcsvResult<()> {
        let name = self.get_column_if_valid(0, column_index)?.name.to_owned();

        for row in &mut self.rows {
            row.remove_cell(&name);
        }

        self.columns.remove(column_index);

        // If column is empty, drop all rows
        if self.get_column_count() == 0 {
            self.rows = vec![];
        }

        Ok(())
    }

    /// Get total rows count
    fn get_row_count(&self) -> usize {
        self.rows.len()
    }

    /// Get total columns count
    fn get_column_count(&self) -> usize {
        self.columns.len()
    }

    /// Drop all data from virtual data
    fn drop_data(&mut self) {
        self.columns.clear();
        self.rows.clear();
    }

    /// Apply closure to all values
    fn apply_all<F: FnMut(&mut Value)>(&mut self, mut f: F) {
        for row in &mut self.rows {
            for value in row.values.values_mut() {
                f(value)
            }
        }
    }
}

impl VirtualData {
    /// Get read only data from virtual data
    ///
    /// This clones every value into a ReadOnlyData.
    /// If the purpose is to simply iterate over values, prefer read_only_ref method.
    pub fn read_only(&self) -> ReadOnlyData {
        ReadOnlyData::from(self)
    }

    /// Get read only data from virtual data, but as reference
    pub fn read_only_ref(&self) -> ReadOnlyDataRef {
        ReadOnlyDataRef::from(self)
    }

    /// Set cell's value with given string value
    ///
    /// This will fail if the value cannot be converted to column's type
    pub fn set_cell_from_string(&mut self, x: usize, y: usize, value: &str) -> DcsvResult<()> {
        let key_column = self.get_column_if_valid(x, y)?;
        match key_column.column_type {
            ValueType::Text => self.set_cell(x, y, Value::Text(value.to_string())),
            ValueType::Number => self.set_cell(
                x,
                y,
                Value::Number(value.parse().map_err(|_| {
                    DcsvError::InvalidCellData(format!(
                        "Given value is \"{}\" which is not a number",
                        value
                    ))
                })?),
            ),
        }
    }

    /// Insert a column with given column informations
    ///
    /// # Args
    ///
    /// * column_index  : Position to put column
    /// * column_name   : New column name
    /// * column_type   : Column's type
    /// * limiter       : Set limiter with
    /// * placeholder   : Placeholder will be applied to every row
    pub fn insert_column_with_type(
        &mut self,
        column_index: usize,
        column_name: &str,
        column_type: ValueType,
        limiter: Option<ValueLimiter>,
        placeholder: Option<Value>,
    ) -> DcsvResult<()> {
        if column_index > self.get_column_count() {
            return Err(DcsvError::InvalidColumn(format!(
                "Cannot add column to out of range position : {}",
                column_index
            )));
        }
        if self.try_get_column_index(column_name).is_some() {
            return Err(DcsvError::InvalidColumn(format!(
                "Cannot add existing column = \"{}\"",
                column_name
            )));
        }
        let new_column = Column::new(column_name, column_type, limiter);
        let default_value = new_column.get_default_value();
        for row in &mut self.rows {
            row.insert_cell(
                &new_column.name,
                placeholder.clone().unwrap_or_else(|| default_value.clone()),
            );
        }
        self.columns.insert(column_index, new_column);
        Ok(())
    }

    /// Set a limiter to a column
    ///
    /// # Args
    ///
    /// * column  : column's index
    /// * limiter : Target limiter
    /// * panic   : If true, failed set will occur panic
    pub fn set_limiter(
        &mut self,
        column: usize,
        limiter: &ValueLimiter,
        panic: bool,
    ) -> DcsvResult<()> {
        let column = &mut self.columns[column];
        for (index, row) in self.rows.iter_mut().enumerate() {
            let mut qualified = true;
            let mut converted = None;
            let mut convert_to = None;
            if let Some(value) = row.get_cell_value(&column.name) {
                // Check if value can be converted at most
                if let Some(ttype) = limiter.is_convertible(value) {
                    converted.replace(Value::from_str(&value.to_string(), ttype)?);
                    convert_to = Some(ttype);
                }

                // Check if value qualify limiter condition
                if !limiter.qualify(converted.as_ref().unwrap_or(value)) {
                    qualified = false;
                    convert_to = None;
                    if panic {
                        return Err(DcsvError::InvalidCellData(format!(
                            "Cell {},{} doesn't match limiter's qualification",
                            index, column.name
                        )));
                    }
                }
            } else {
                return Err(DcsvError::InvalidRowData(
                    "Failed to get row data while setting limiter".to_string(),
                ));
            }

            if let Some(ttype) = convert_to {
                row.change_cell_type(&column.name, ttype)?;
            } else if !qualified && !panic {
                // Force update to defualt value
                // It is mostly safe to unwrap because default is required for pattern or variant
                // but, limiter might only have a single "type" value
                row.update_cell_value(
                    &column.name,
                    limiter
                        .get_default()
                        .unwrap_or(&Value::empty(limiter.get_type()))
                        .clone(),
                );
            }
        }
        column.set_limiter(limiter.clone());
        Ok(())
    }

    /// Qualify data and get reference of qualifed rows.
    pub fn qualify(&self, column: usize, limiter: &ValueLimiter) -> DcsvResult<Vec<&Row>> {
        let mut rows = vec![];
        let column = &self.columns[column];
        for row in &self.rows {
            if let Some(value) = row.get_cell_value(&column.name) {
                // Check if value qualify limiter condition
                if limiter.qualify(value) {
                    rows.push(row)
                }
            } else {
                return Err(DcsvError::InvalidRowData(
                    "Failed to get row data while qualifying".to_string(),
                ));
            }
        }
        Ok(rows)
    }

    /// Qualify data with multiple limiters and get reference of qualifed rows.
    pub fn qualify_multiple(
        &self,
        qualifiers: Vec<(usize, &ValueLimiter)>,
    ) -> DcsvResult<Vec<&Row>> {
        let mut rows = vec![];
        // Rows loop
        'outer: for row in &self.rows {
            // Values loop in
            for (column, limiter) in &qualifiers {
                let column = &self.columns[*column];
                if let Some(value) = row.get_cell_value(&column.name) {
                    // Check if value qualify limiter condition
                    if !limiter.qualify(value) {
                        continue 'outer;
                    }
                } else {
                    return Err(DcsvError::InvalidRowData(
                        "Failed to get row data while qualifying".to_string(),
                    ));
                }
            }

            // Only push if all qualifiers suceeded.
            rows.push(row);
        }
        Ok(rows)
    }

    /// Export virtual data's schema(limiter) as string form
    ///
    /// Schema is expressed as csv value. Each line is structured with following order.
    ///
    /// - column
    /// - type
    /// - default
    /// - variant
    /// - pattern
    pub fn export_schema(&self) -> String {
        let mut schema = format!("{}\n", SCHEMA_HEADER);
        for col in &self.columns {
            let mut line = col.name.clone() + ",";
            let limiter = &col.limiter;
            line.push_str(&limiter.get_type().to_string());
            line.push(',');
            line.push_str(
                &limiter
                    .get_default()
                    .map(|s| s.to_string())
                    .unwrap_or_default(),
            );
            line.push(',');
            line.push_str(
                &limiter
                    .get_variant()
                    .map(|s| s.iter().map(|s| s.to_string()).collect::<Vec<String>>())
                    .unwrap_or_default()
                    .join(" "),
            );
            line.push(',');
            line.push_str(
                &limiter
                    .get_pattern()
                    .map(|s| s.to_string())
                    .unwrap_or_default(),
            );

            schema.push_str(&(line + "\n"));
        }
        schema
    }

    // <DRY>
    /// Get a column index from src
    ///
    /// Src can be either colum name or column index
    /// If colum index is out of range, it returns none
    pub fn try_get_column_index(&self, src: &str) -> Option<usize> {
        let column_index = match src.parse::<usize>() {
            Err(_) => self.columns.iter().position(|c| c.name == src),
            Ok(index) => {
                if index < self.get_column_count() {
                    Some(index)
                } else {
                    None
                }
            }
        };
        column_index
    }

    /// Check if cell coordinate is not out of range
    ///
    /// # Return
    ///
    /// True if given coordinate is within data's boundary, false if not.
    fn is_valid_cell_coordinate(&self, x: usize, y: usize) -> bool {
        if x < self.get_row_count() && y < self.get_column_count() {
            return true;
        }

        false
    }

    /// Check if given coordinate exits and return target column
    fn get_column_if_valid(&self, x: usize, y: usize) -> DcsvResult<&Column> {
        if !self.is_valid_cell_coordinate(x, y) {
            return Err(DcsvError::OutOfRangeError);
        }
        // It is sfe to uwnrap because
        // it was validated by prior is_valid_cell_coordinate method
        let key_column = self.columns.get(y).unwrap();
        Ok(key_column)
    }

    /// Check if given value corresponds to column limiter
    fn is_valid_column_data(&self, column: usize, value: &Value) -> DcsvResult<()> {
        if let Some(col) = self.columns.get(column) {
            if col.limiter.qualify(value) {
                Ok(())
            } else {
                Err(DcsvError::InvalidCellData(
                    "Given cell data failed to match limiter's restriction".to_string(),
                ))
            }
        } else {
            Err(DcsvError::InvalidRowData(format!(
                "Given column index \"{}\" doesn't exist",
                column
            )))
        }
    }

    /// Check if given values' length matches column's legnth
    fn check_row_length(&self, values: &[Value]) -> DcsvResult<()> {
        match self.get_column_count().cmp(&values.len()) {
            Ordering::Equal => (),
            Ordering::Less | Ordering::Greater => {
                return Err(DcsvError::InvalidRowData(format!(
                    r#"Given row length is "{}" while columns length is "{}""#,
                    values.len(),
                    self.get_column_count()
                )))
            }
        }
        Ok(())
    }

    /// Get iterator.
    ///
    /// This methods returns iterator which respects column orders
    pub fn get_iterator(&self) -> std::vec::IntoIter<&Value> {
        let columns = &self.columns;
        let mut iterate = vec![];
        for row in &self.rows {
            iterate.extend(row.get_iterator(columns));
        }
        iterate.into_iter()
    }

    /// Get iterator of a row with given index
    ///
    /// This respects  columns orders
    pub fn get_row_iterator(&self, row_index: usize) -> DcsvResult<std::vec::IntoIter<&Value>> {
        let columns = &self.columns;
        Ok(self
            .rows
            .get(row_index)
            .ok_or(DcsvError::OutOfRangeError)?
            .get_iterator(columns))
    }

    // </DRY>
}

/// to_string implementation for virtual data
///
/// This returns csv value string
impl std::fmt::Display for VirtualData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut csv_src = String::new();
        let column_row = self
            .columns
            .iter()
            .map(|c| c.name.as_str())
            .collect::<Vec<&str>>()
            .join(",")
            + "\n";
        csv_src.push_str(&column_row);

        let columns = self
            .columns
            .iter()
            .map(|col| col.name.as_str())
            .collect::<Vec<&str>>();
        for row in &self.rows {
            let row_value = columns
                .iter()
                .map(|name| {
                    row.get_cell_value(name)
                        .unwrap_or(&Value::Text(String::new()))
                        .to_string()
                })
                .collect::<Vec<String>>()
                .join(",")
                + "\n";

            csv_src.push_str(&row_value);
        }
        // Remove trailing newline
        csv_src.pop();
        write!(f, "{}", csv_src)
    }
}

/// Column of virtual data
///
/// Column is "text" type by default but can be further configured with value limiter.
#[derive(Clone, Debug)]
pub struct Column {
    pub name: String,
    pub column_type: ValueType,
    pub limiter: ValueLimiter,
}

impl Column {
    /// Create empty column with name
    pub fn empty(name: &str) -> Self {
        Self {
            name: name.to_string(),
            column_type: ValueType::Text,
            limiter: ValueLimiter::default(),
        }
    }

    /// Create new column with properties
    pub fn new(name: &str, column_type: ValueType, limiter: Option<ValueLimiter>) -> Self {
        Self {
            name: name.to_string(),
            column_type,
            limiter: limiter.unwrap_or_default(),
        }
    }

    /// Get column name
    pub fn get_name(&self) -> &str {
        &self.name
    }

    /// Get column type
    pub fn get_column_type(&self) -> &ValueType {
        &self.column_type
    }

    /// Rename a column and return an original name
    pub fn rename(&mut self, new_name: &str) -> String {
        std::mem::replace(&mut self.name, new_name.to_string())
    }

    /// Apply limiter to a column
    pub fn set_limiter(&mut self, limiter: ValueLimiter) {
        self.column_type = limiter.get_type();
        self.limiter = limiter;
    }

    /// Get default value by column
    ///
    /// Every value type has it's own default value.
    /// The default value can differ by limiter's variant of patterns and should comply to a
    /// limter's predicate.
    pub fn get_default_value(&self) -> Value {
        // has default
        if let Some(def) = self.limiter.get_default() {
            return def.clone();
        }

        // has variant
        let variant = self.limiter.get_variant();
        if let Some(vec) = variant {
            if !vec.is_empty() {
                return vec[0].clone();
            }
        }

        // Construct new default value
        match self.column_type {
            ValueType::Number => Value::Number(0),
            ValueType::Text => Value::Text(String::new()),
        }
    }
}

/// Row
///
/// Row is implementated as a hashmap. You cannot iterate row without column information.
#[derive(Clone, Debug)]
pub struct Row {
    pub values: HashMap<String, Value>,
}

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

impl Row {
    /// Create a new row
    pub fn new() -> Self {
        Self {
            values: HashMap::new(),
        }
    }

    /// Convert row to vector with given columns
    ///
    /// It is totally valid to give partial columns into a row.
    pub fn to_vector(&self, columns: &[Column]) -> DcsvResult<Vec<&Value>> {
        let mut acc = Vec::default();
        for col in columns {
            acc.push(self.values.get(&col.name).ok_or_else(|| {
                DcsvError::InvalidColumn(
                    "Given column was not present thus cannot construct row vector".to_string(),
                )
            })?);
        }
        Ok(acc)
    }

    /// Get comma separated row string
    ///
    /// This requires columns because a row is not a linear container. Partial column is not an
    /// error but valid behaviour.
    pub fn to_string(&self, columns: &[Column]) -> DcsvResult<String> {
        let mut acc = String::new();
        for col in columns {
            acc.push_str(
                &self
                    .values
                    .get(&col.name)
                    .ok_or_else(|| {
                        DcsvError::InvalidColumn(
                            "Given column was not present thus cannot construct row string"
                                .to_string(),
                        )
                    })?
                    .to_string(),
            );
            acc.push(',');
        }
        acc.pop(); // Remove trailing comma
        Ok(acc)
    }

    /// Rename column name inside row map
    ///
    /// This doesn't validate column's name and should comply with column name rule to avoid
    /// unintended behaviour.
    pub fn rename_column(&mut self, name: &str, new_name: &str) {
        let previous = self.values.remove(name);

        if let Some(prev) = previous {
            self.values.insert(new_name.to_string(), prev);
        }
    }

    /// Insert a new cell(key, value pair) into a row
    pub fn insert_cell(&mut self, key: &str, value: Value) {
        self.values.insert(key.to_string(), value);
    }

    /// Get a cell value by a key
    pub fn get_cell_value(&self, key: &str) -> Option<&Value> {
        self.values.get(key)
    }

    /// Update a cell's value with a given value
    ///
    /// This doesn't fail and silently do nothing if key doesn't exist.
    pub fn update_cell_value(&mut self, key: &str, value: Value) {
        if let Some(v) = self.values.get_mut(key) {
            *v = value;
        }
    }

    /// Chagnes a cell's value type
    ///
    /// This method tries to naturally convert cell's type.
    /// Empty text value defaults to "0".
    pub fn change_cell_type(&mut self, key: &str, target_type: ValueType) -> DcsvResult<()> {
        if let Some(v) = self.values.get_mut(key) {
            match v {
                Value::Text(t) => {
                    if target_type == ValueType::Number {
                        // Empty text value can be evaluted to 0 value number
                        if t.is_empty() {
                            *v = Value::Number(0);
                            return Ok(());
                        }

                        *v = Value::Number(t.parse::<isize>().map_err(|_| {
                            DcsvError::InvalidCellData(format!(
                                "\"{}\" is not a valid value to be converted to type : \"{}\"",
                                t, target_type
                            ))
                        })?);
                    }
                }
                Value::Number(n) => {
                    if target_type == ValueType::Text {
                        *v = Value::Text(n.to_string());
                    }
                }
            }
        }
        Ok(())
    }

    /// Remove a cell by key
    pub fn remove_cell(&mut self, key: &str) {
        self.values.remove(key);
    }

    /// Get iterator with given columns
    pub fn get_iterator(&self, columns: &[Column]) -> std::vec::IntoIter<&Value> {
        let mut iterate = vec![];
        for col in columns {
            if let Some(value) = self.values.get(&col.name) {
                iterate.push(value);
            }
        }
        iterate.into_iter()
    }
}

/// Read only data
///
/// This is a cloned data from virtual_data, thus lifetime independent
#[derive(Debug)]
pub struct ReadOnlyData {
    pub columns: Vec<Column>,
    pub rows: Vec<Vec<Value>>,
}

impl From<&VirtualData> for ReadOnlyData {
    fn from(data: &VirtualData) -> Self {
        let mut rows: Vec<Vec<Value>> = vec![];
        for row in &data.rows {
            let mut static_row: Vec<Value> = vec![];
            for col in &data.columns {
                static_row.push(row.get_cell_value(&col.name).unwrap().clone())
            }
            rows.push(static_row);
        }
        Self {
            columns: data.columns.clone(),
            rows,
        }
    }
}

/// Borrowed read only data from virtual_data
///
/// * Columns : Vec<&str>
/// * rows    : Vec<Vec<&Value>>
#[derive(Debug)]
pub struct ReadOnlyDataRef<'data> {
    pub columns: Vec<&'data Column>,
    pub rows: Vec<Vec<&'data Value>>,
}

impl<'data> ReadOnlyDataRef<'data> {
    /// Get owned ReadOnlyData struct
    ///
    /// This clones all information into a separate struct
    pub fn to_owned(&self) -> ReadOnlyData {
        ReadOnlyData {
            columns: self.columns.iter().map(|&c| c.clone()).collect::<Vec<_>>(),
            rows: self
                .rows
                .iter()
                .map(|vv| vv.iter().map(|&v| v.clone()).collect::<Vec<_>>())
                .collect::<Vec<Vec<_>>>(),
        }
    }
}

impl<'data> From<&'data VirtualData> for ReadOnlyDataRef<'data> {
    fn from(data: &'data VirtualData) -> Self {
        let mut rows: Vec<Vec<&'data Value>> = vec![];
        for row in &data.rows {
            let mut static_row: Vec<&'data Value> = vec![];
            for col in &data.columns {
                static_row.push(row.get_cell_value(&col.name).unwrap())
            }
            rows.push(static_row);
        }
        Self {
            columns: data.columns.iter().collect(),
            rows,
        }
    }
}