pub struct CompMaker {}
Expand description

Makes a [Compare or LineComp]

Implementations

Add a new Compare. If a Compare already exists by that name, replace it.

Add a new LineCompare. If a Compare already exists by that name, replace it.

Add a new alias. If an alias already exists by that name, replace it.

Print all available Matchers to stdout.

Examples found in repository
src/bin/cdx/sort_main.rs (line 39)
 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
pub fn main(argv: &[String]) -> Result<()> {
    let prog = args::ProgSpec::new("Sort lines.", args::FileCount::Many);
    const A: [ArgSpec; 6] = [
        arg! {"key", "k", "Spec", "How to compare adjacent lines"},
        arg! {"unique", "u", "", "Print only first of equal lines"},
        arg! {"merge", "m", "", "Merge already sorted files."},
        arg! {"show-comp", "s", "", "Print available comparisons"},
        arg! {"check", "c", "", "Check to see if each input file is sorted."},
        arg! {"Check", "C", "Number", "Check to see if each input file is sorted. Report this many failures before exiting."},
    ];
    let (args, files) = args::parse(&prog, &A, argv);

    let mut unique = false;
    let mut merge = false;
    let mut comp = LineCompList::new();
    let mut check = false;
    let mut num_checks = 1;
    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "merge" {
            merge = true;
        } else if x.name == "check" {
            check = true;
            num_checks = 1;
        } else if x.name == "Check" {
            check = true;
            num_checks = x.value.parse::<usize>()?;
        } else if x.name == "unique" {
            unique = true;
        } else if x.name == "show-comp" {
            CompMaker::help();
            return Ok(());
        } else {
            unreachable!();
        }
    }
    if check && merge {
        return err!("Check and Merge make no sense together");
    }
    if comp.is_empty() {
        comp.add("")?;
    }
    if check {
        let mut reported = 0;
        for x in &files {
            let mut f = LookbackReader::new_open(x, 1)?;
            if f.is_done() {
                continue;
            }
            loop {
                if f.getline()? {
                    break;
                }
                if comp_check(&f, &mut comp, unique) {
                    reported += 1;
                    if reported >= num_checks {
                        break;
                    }
                }
            }
        }
        if reported > 0 {
            return Err(Error::Silent);
        }
    } else {
        let mut w = get_writer("-")?;
        if merge {
            sort::merge(&files, &mut comp, &mut w, unique)?;
        } else {
            sort::sort(&files, comp, &mut w, unique)?;
        }
    }
    Ok(())
}

create Box from spec

Examples found in repository
src/util.rs (line 1709)
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
fn new_with(comp_spec: &str, r: &RangeSpec<'_>) -> Result<Self> {
        Ok(Self {
            op: r.op1.parse::<CompareOp>()?,
            val: {
                let mut c = CompMaker::make_comp_box(comp_spec)?;
                c.set(r.val1.as_bytes());
                c
            },
            op2: if r.op2.is_none() {
                None
            } else {
                Some(r.op2.unwrap().parse::<CompareOp>()?)
            },
            val2: if r.val2.is_none() {
                None
            } else {
                let mut c = CompMaker::make_comp_box(comp_spec)?;
                c.set(r.val2.unwrap().as_bytes());
                Some(c)
            },
        })
    }

create Box from spec

create Comp from spec

Examples found in repository
src/comp.rs (line 1015)
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
pub fn make_comp_box(spec: &str) -> Result<Box<dyn Compare>> {
        Ok(Self::make_comp(spec)?.comp)
    }
    /// create Box<dyn LineCompare> from spec
    pub fn make_line_comp_box(spec: &str) -> Result<Box<dyn LineCompare>> {
        Ok(Self::make_line_comp(spec)?.comp)
    }
    /// create Comp from spec
    pub fn make_comp(spec: &str) -> Result<Comp> {
        if let Some((a, b)) = spec.split_once(',') {
            Self::make_comp_parts(a, b)
        } else {
            Self::make_comp_parts(spec, "")
        }
    }
    /// create Comp from method and pattern
    pub fn make_comp_parts(method: &str, pattern: &str) -> Result<Comp> {
        let mut comp = Comp::new();
        comp.pattern = pattern.to_string();
        if !method.is_empty() {
            for x in method.split('.') {
                if x.eq_ignore_ascii_case("rev") {
                    comp.reverse = true;
                } else if x.eq_ignore_ascii_case("strict") {
                    comp.junk.junk_type = JunkType::None;
                } else if x.eq_ignore_ascii_case("trail") {
                    comp.junk.junk_type = JunkType::Trailing;
                } else if x.eq_ignore_ascii_case("low") {
                    comp.junk.junk_val = JunkVal::Min;
                } else {
                    comp.ctype = x.to_string();
                }
            }
        }
        Self::remake_comp(&mut comp)?;
        Ok(comp)
    }
    /// create LineComp from spec
    pub fn make_line_comp(spec: &str) -> Result<LineComp> {
        if let Some((a, b)) = spec.split_once(',') {
            if let Some((c, d)) = b.split_once(',') {
                Self::make_line_comp_parts(a, c, d)
            } else {
                Self::make_line_comp_parts(a, b, "")
            }
        } else {
            Self::make_line_comp_parts(spec, "", "")
        }
    }
    /// create LineComp from columns, method and pattern
    pub fn make_line_comp_parts(cols: &str, method: &str, pattern: &str) -> Result<LineComp> {
        let mut comp = LineComp::new();
        comp.pattern = pattern.to_string();
        comp.cols = cols.to_string();
        if !method.is_empty() {
            for x in method.split('.') {
                if x.eq_ignore_ascii_case("rev") {
                    comp.reverse = true;
                } else if x.eq_ignore_ascii_case("strict") {
                    comp.junk.junk_type = JunkType::None;
                } else if x.eq_ignore_ascii_case("trail") {
                    comp.junk.junk_type = JunkType::Trailing;
                } else if x.eq_ignore_ascii_case("low") {
                    comp.junk.junk_val = JunkVal::Min;
                } else {
                    comp.ctype = x.to_string();
                }
            }
        }
        Self::remake_line_comp(&mut comp)?;
        Ok(comp)
    }
    /// reset the Compare inside the Comp
    pub fn remake_comp(comp: &mut Comp) -> Result<()> {
        Self::init()?;
        let ctype = Self::resolve_alias(&comp.ctype);
        let mm = COMP_MAKER.lock().unwrap();
        for x in &*mm {
            if ctype.eq_ignore_ascii_case(x.tag) {
                comp.comp = (x.maker)(comp)?;
                return Ok(());
            }
        }
        err!("No such compare type : '{}'", comp.ctype)
    }
    /// reset the LineCompare inside the LineComp
    pub fn remake_line_comp(comp: &mut LineComp) -> Result<()> {
        Self::init()?;
        let ctype = Self::resolve_alias(&comp.ctype);
        let mm = LINE_MAKER.lock().unwrap();
        for x in &*mm {
            if ctype.eq_ignore_ascii_case(x.tag) {
                comp.comp = (x.maker)(comp)?;
                return Ok(());
            }
        }
        let mm = COMP_MAKER.lock().unwrap();
        let mut new_comp = Comp::with_line_comp(comp);
        for x in &*mm {
            if ctype.eq_ignore_ascii_case(x.tag) {
                new_comp.comp = (x.maker)(&new_comp)?;
                if comp.cols.is_empty() {
                    comp.comp = Box::new(LineCompWhole::new(new_comp));
                } else {
                    comp.comp = Box::new(LineCompCol::new(new_comp, &comp.cols)?);
                }
                return Ok(());
            }
        }
        err!("No such compare type : '{}'", comp.ctype)
    }
}

#[derive(Default, Debug)]
/// Ordered list of [Comp]
pub struct CompList {
    c: Vec<Comp>,
}
#[derive(Default, Debug)]
/// Ordered list of [LineComp]
pub struct LineCompList {
    c: Vec<LineComp>,
    value: Vec<u8>,
}

impl CompList {
    /// new
    pub fn new() -> Self {
        Self::default()
    }
    /// any [Comp]s in the list?
    pub fn is_empty(&self) -> bool {
        self.c.is_empty()
    }
    /// add
    pub fn push(&mut self, x: Comp) {
        self.c.push(x);
    }
    /// add
    pub fn add(&mut self, x: &str) -> Result<()> {
        self.c.push(CompMaker::make_comp(x)?);
        Ok(())
    }
More examples
src/agg.rs (line 527)
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
fn add_one(&mut self, spec: &str) -> Result<()> {
        if spec.is_empty() {
            return err!("Invalid empty Merge Part");
        } else if spec.as_bytes()[0] == b'D' {
            if spec.len() != 3 {
                return err!("Merge Delim Spec must be three bytes, e.g. 'D.,'");
            }
            self.delim = spec.as_bytes()[1];
            self.out_delim = spec.as_bytes()[2];
        } else if spec.eq_ignore_ascii_case("sort") {
            self.do_sort = true;
        } else if spec.eq_ignore_ascii_case("uniq") {
            self.do_uniq = true;
        } else if spec.eq_ignore_ascii_case("count") {
            self.do_count = true;
        } else if let Some(val) = spec.strip_prefix("comp:") {
            self.comp = CompMaker::make_comp(val)?;
        } else if let Some(val) = spec.strip_prefix("min_len:") {
            self.min_len = val.parse::<usize>()?;
        } else if let Some(val) = spec.strip_prefix("max_len:") {
            self.max_len = val.parse::<usize>()?;
        } else if let Some(val) = spec.strip_prefix("max_parts:") {
            self.max_parts = val.parse::<usize>()?;
        } else {
            return err!("Unrecognized Merge Part '{}'", spec);
        }
        Ok(())
    }
}

impl Agg for Merge {
    fn add(&mut self, data: &[u8]) {
        if !data.is_empty() {
            if !self.data.line.is_empty() {
                self.data.line.push(self.delim);
            }
            self.data.line.extend_from_slice(data);
        }
    }
    fn result(&mut self, w: &mut dyn Write) -> Result<()> {
        self.data.split(self.delim);
        if self.do_sort {
            self.data.parts.sort_by(|a, b| {
                self.comp
                    .comp(a.get(&self.data.line), b.get(&self.data.line))
            });
        }
        if self.do_uniq {
            self.data.parts.dedup_by(|a, b| {
                self.comp
                    .equal(a.get(&self.data.line), b.get(&self.data.line))
            });
        }
        if self.do_count {
            write!(w, "{}", self.data.parts.len())?;
        } else {
            let mut num_written = 0;
            for x in &self.data.parts {
                if x.len() >= self.min_len && x.len() <= self.max_len {
                    if num_written > 0 {
                        w.write_all(&[self.out_delim])?;
                    }
                    w.write_all(x.get(&self.data.line))?;
                    num_written += 1;
                    if num_written >= self.max_parts {
                        break;
                    }
                }
            }
        }
        Ok(())
    }
    fn reset(&mut self) {
        self.data.line.clear();
    }
}

struct Min {
    comp: Comp,
    val: Vec<u8>,
    empty: bool,
}

impl Min {
    fn new(spec: &str) -> Result<Self> {
        Ok(Self {
            comp: CompMaker::make_comp(spec)?,
            val: Vec::new(),
            empty: true,
        })
    }
}

impl Agg for Min {
    fn value(&self) -> f64 {
        self.val.to_f64_lossy()
    }
    fn add(&mut self, data: &[u8]) {
        if self.empty {
            self.empty = false;
            self.val.extend_from_slice(data);
            return;
        }
        if self.comp.comp.comp(&self.val, data) == Ordering::Greater {
            self.val.clear();
            self.val.extend_from_slice(data);
        }
    }
    fn result(&mut self, w: &mut dyn Write) -> Result<()> {
        w.write_all(&self.val)?;
        Ok(())
    }
    fn reset(&mut self) {
        self.val.clear();
        self.empty = true;
    }
}

struct Mean {
    val: f64,
    cnt: f64,
    fmt: num::NumFormat,
}

impl Mean {
    fn new(spec: &str) -> Result<Self> {
        if spec.is_empty() {
            Ok(Self {
                val: 0.0,
                cnt: 0.0,
                fmt: num::NumFormat::default(),
            })
        } else {
            err!("Unexpected pattern with 'Mean' aggregator : '{}'", spec)
        }
    }
}

impl Agg for Mean {
    fn fmt(&mut self, f: num::NumFormat) {
        self.fmt = f;
    }
    fn add(&mut self, data: &[u8]) {
        self.val += data.to_f64_lossy();
        self.cnt += 1.0;
    }

    fn result(&mut self, w: &mut dyn Write) -> Result<()> {
        num::format_hnum(self.value(), self.fmt, w)
    }
    fn value(&self) -> f64 {
        if self.cnt > 0.0 {
            self.val / self.cnt
        } else {
            0.0
        }
    }
    fn reset(&mut self) {
        self.val = 0.0;
        self.cnt = 0.0;
    }
}

struct Sum {
    val: f64,
    fmt: num::NumFormat,
}

impl Sum {
    fn new(spec: &str) -> Result<Self> {
        if spec.is_empty() {
            Ok(Self {
                val: 0.0,
                fmt: num::NumFormat::default(),
            })
        } else {
            err!("Unexpected pattern with 'Sum' aggregator : '{}'", spec)
        }
    }
}

impl Agg for Sum {
    fn fmt(&mut self, f: num::NumFormat) {
        self.fmt = f;
    }
    fn add(&mut self, data: &[u8]) {
        self.val += data.to_f64_lossy();
    }
    fn result(&mut self, w: &mut dyn Write) -> Result<()> {
        num::format_hnum(self.value(), self.fmt, w)
    }
    fn value(&self) -> f64 {
        self.val
    }
    fn reset(&mut self) {
        self.val = 0.0;
    }
}

struct ASum {
    val: usize,
    cnt: Box<dyn Counter>,
    fmt: num::NumFormat,
}

impl ASum {
    fn new(spec: &str) -> Result<Self> {
        Ok(Self {
            val: 0,
            cnt: AggMaker::make_counter(spec)?,
            fmt: num::NumFormat::default(),
        })
    }
}

impl Agg for ASum {
    fn fmt(&mut self, f: num::NumFormat) {
        self.fmt = f;
    }
    fn value(&self) -> f64 {
        self.val as f64
    }
    fn add(&mut self, data: &[u8]) {
        self.val += self.cnt.counter(data);
    }
    fn result(&mut self, w: &mut dyn Write) -> Result<()> {
        num::format_hnum(self.val as f64, self.fmt, w)
    }
    fn reset(&mut self) {
        self.val = 0;
    }
}

struct AMin {
    val: usize,
    cnt: Box<dyn Counter>,
    fmt: num::NumFormat,
}

impl AMin {
    fn new(spec: &str) -> Result<Self> {
        Ok(Self {
            val: usize::MAX,
            cnt: AggMaker::make_counter(spec)?,
            fmt: num::NumFormat::default(),
        })
    }
}

impl Agg for AMin {
    fn fmt(&mut self, f: num::NumFormat) {
        self.fmt = f;
    }
    fn value(&self) -> f64 {
        self.val as f64
    }
    fn add(&mut self, data: &[u8]) {
        self.val = cmp::min(self.val, self.cnt.counter(data));
    }
    fn result(&mut self, w: &mut dyn Write) -> Result<()> {
        num::format_hnum(self.val as f64, self.fmt, w)
    }
    fn reset(&mut self) {
        self.val = usize::MAX;
    }
}

struct AMax {
    val: usize,
    cnt: Box<dyn Counter>,
    fmt: num::NumFormat,
}

impl AMax {
    fn new(spec: &str) -> Result<Self> {
        Ok(Self {
            val: 0,
            cnt: AggMaker::make_counter(spec)?,
            fmt: num::NumFormat::default(),
        })
    }
}

impl Agg for AMax {
    fn fmt(&mut self, f: num::NumFormat) {
        self.fmt = f;
    }
    fn value(&self) -> f64 {
        self.val as f64
    }
    fn add(&mut self, data: &[u8]) {
        self.val = cmp::max(self.val, self.cnt.counter(data));
    }
    fn result(&mut self, w: &mut dyn Write) -> Result<()> {
        num::format_hnum(self.val as f64, self.fmt, w)
    }
    fn reset(&mut self) {
        self.val = 0;
    }
}

struct AMean {
    val: usize,
    num: usize,
    cnt: Box<dyn Counter>,
    fmt: num::NumFormat,
}

impl AMean {
    fn new(spec: &str) -> Result<Self> {
        Ok(Self {
            val: 0,
            num: 0,
            cnt: AggMaker::make_counter(spec)?,
            fmt: num::NumFormat::default(),
        })
    }
}

impl Agg for AMean {
    fn fmt(&mut self, f: num::NumFormat) {
        self.fmt = f;
    }
    fn value(&self) -> f64 {
        if self.num > 0 {
            self.val as f64 / self.num as f64
        } else {
            0.0
        }
    }
    fn add(&mut self, data: &[u8]) {
        self.val += self.cnt.counter(data);
        self.num += 1;
    }
    fn result(&mut self, w: &mut dyn Write) -> Result<()> {
        num::format_hnum(self.val as f64, self.fmt, w)
    }
    fn reset(&mut self) {
        self.val = 0;
        self.num = 0;
    }
}

struct Max {
    comp: Comp,
    val: Vec<u8>,
}

impl Max {
    fn new(spec: &str) -> Result<Self> {
        Ok(Self {
            comp: CompMaker::make_comp(spec)?,
            val: Vec::new(),
        })
    }

create Comp from method and pattern

Examples found in repository
src/comp.rs (line 1024)
1022
1023
1024
1025
1026
1027
1028
pub fn make_comp(spec: &str) -> Result<Comp> {
        if let Some((a, b)) = spec.split_once(',') {
            Self::make_comp_parts(a, b)
        } else {
            Self::make_comp_parts(spec, "")
        }
    }

create LineComp from spec

Examples found in repository
src/comp.rs (line 1019)
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
pub fn make_line_comp_box(spec: &str) -> Result<Box<dyn LineCompare>> {
        Ok(Self::make_line_comp(spec)?.comp)
    }
    /// create Comp from spec
    pub fn make_comp(spec: &str) -> Result<Comp> {
        if let Some((a, b)) = spec.split_once(',') {
            Self::make_comp_parts(a, b)
        } else {
            Self::make_comp_parts(spec, "")
        }
    }
    /// create Comp from method and pattern
    pub fn make_comp_parts(method: &str, pattern: &str) -> Result<Comp> {
        let mut comp = Comp::new();
        comp.pattern = pattern.to_string();
        if !method.is_empty() {
            for x in method.split('.') {
                if x.eq_ignore_ascii_case("rev") {
                    comp.reverse = true;
                } else if x.eq_ignore_ascii_case("strict") {
                    comp.junk.junk_type = JunkType::None;
                } else if x.eq_ignore_ascii_case("trail") {
                    comp.junk.junk_type = JunkType::Trailing;
                } else if x.eq_ignore_ascii_case("low") {
                    comp.junk.junk_val = JunkVal::Min;
                } else {
                    comp.ctype = x.to_string();
                }
            }
        }
        Self::remake_comp(&mut comp)?;
        Ok(comp)
    }
    /// create LineComp from spec
    pub fn make_line_comp(spec: &str) -> Result<LineComp> {
        if let Some((a, b)) = spec.split_once(',') {
            if let Some((c, d)) = b.split_once(',') {
                Self::make_line_comp_parts(a, c, d)
            } else {
                Self::make_line_comp_parts(a, b, "")
            }
        } else {
            Self::make_line_comp_parts(spec, "", "")
        }
    }
    /// create LineComp from columns, method and pattern
    pub fn make_line_comp_parts(cols: &str, method: &str, pattern: &str) -> Result<LineComp> {
        let mut comp = LineComp::new();
        comp.pattern = pattern.to_string();
        comp.cols = cols.to_string();
        if !method.is_empty() {
            for x in method.split('.') {
                if x.eq_ignore_ascii_case("rev") {
                    comp.reverse = true;
                } else if x.eq_ignore_ascii_case("strict") {
                    comp.junk.junk_type = JunkType::None;
                } else if x.eq_ignore_ascii_case("trail") {
                    comp.junk.junk_type = JunkType::Trailing;
                } else if x.eq_ignore_ascii_case("low") {
                    comp.junk.junk_val = JunkVal::Min;
                } else {
                    comp.ctype = x.to_string();
                }
            }
        }
        Self::remake_line_comp(&mut comp)?;
        Ok(comp)
    }
    /// reset the Compare inside the Comp
    pub fn remake_comp(comp: &mut Comp) -> Result<()> {
        Self::init()?;
        let ctype = Self::resolve_alias(&comp.ctype);
        let mm = COMP_MAKER.lock().unwrap();
        for x in &*mm {
            if ctype.eq_ignore_ascii_case(x.tag) {
                comp.comp = (x.maker)(comp)?;
                return Ok(());
            }
        }
        err!("No such compare type : '{}'", comp.ctype)
    }
    /// reset the LineCompare inside the LineComp
    pub fn remake_line_comp(comp: &mut LineComp) -> Result<()> {
        Self::init()?;
        let ctype = Self::resolve_alias(&comp.ctype);
        let mm = LINE_MAKER.lock().unwrap();
        for x in &*mm {
            if ctype.eq_ignore_ascii_case(x.tag) {
                comp.comp = (x.maker)(comp)?;
                return Ok(());
            }
        }
        let mm = COMP_MAKER.lock().unwrap();
        let mut new_comp = Comp::with_line_comp(comp);
        for x in &*mm {
            if ctype.eq_ignore_ascii_case(x.tag) {
                new_comp.comp = (x.maker)(&new_comp)?;
                if comp.cols.is_empty() {
                    comp.comp = Box::new(LineCompWhole::new(new_comp));
                } else {
                    comp.comp = Box::new(LineCompCol::new(new_comp, &comp.cols)?);
                }
                return Ok(());
            }
        }
        err!("No such compare type : '{}'", comp.ctype)
    }
}

#[derive(Default, Debug)]
/// Ordered list of [Comp]
pub struct CompList {
    c: Vec<Comp>,
}
#[derive(Default, Debug)]
/// Ordered list of [LineComp]
pub struct LineCompList {
    c: Vec<LineComp>,
    value: Vec<u8>,
}

impl CompList {
    /// new
    pub fn new() -> Self {
        Self::default()
    }
    /// any [Comp]s in the list?
    pub fn is_empty(&self) -> bool {
        self.c.is_empty()
    }
    /// add
    pub fn push(&mut self, x: Comp) {
        self.c.push(x);
    }
    /// add
    pub fn add(&mut self, x: &str) -> Result<()> {
        self.c.push(CompMaker::make_comp(x)?);
        Ok(())
    }
    /// Compare two slices, usually column values
    pub fn comp(&self, left: &[u8], right: &[u8]) -> Ordering {
        for x in &self.c {
            let ret = x.comp(left, right);
            if ret != Ordering::Equal {
                return ret;
            }
        }
        Ordering::Equal
    }
    /// Compare two slices for equality
    pub fn equal(&self, left: &[u8], right: &[u8]) -> bool {
        for x in &self.c {
            if !x.comp.equal(left, right) {
                return false;
            }
        }
        true
    }
    /// set cache for this value
    pub fn fill_cache(&self, item: &mut Item, value: &[u8]) {
        if !self.c.is_empty() {
            self.c[0].fill_cache(item, value);
        }
    }
    /// set my value
    pub fn set(&mut self, value: &[u8], delim: u8) -> Result<()> {
        if self.c.len() == 1 {
            self.c[0].set(value);
        } else {
            let values: Vec<&[u8]> = value.split(|ch| *ch == delim).collect();
            if values.len() != self.c.len() {
                return err!(
                    "Tried to use a {} part value for a {} part Comparison",
                    values.len(),
                    self.c.len()
                );
            }
            for (n, x) in self.c.iter_mut().enumerate() {
                x.set(values[n]);
            }
        }
        Ok(())
    }
    /// Compare self to slice
    pub fn comp_self(&self, right: &[u8]) -> Ordering {
        for x in &self.c {
            let ret = x.comp_self(right);
            if ret != Ordering::Equal {
                return ret;
            }
        }
        Ordering::Equal
    }
    /// Compare self to slice for equality
    pub fn equal_self(&self, right: &[u8]) -> bool {
        for x in &self.c {
            if !x.equal_self(right) {
                return false;
            }
        }
        true
    }
}

impl LineCompList {
    /// new
    pub fn new() -> Self {
        Self::default()
    }
    /// any [LineComp]s in the list?
    pub fn is_empty(&self) -> bool {
        self.c.is_empty()
    }
    /// which columns used as part of key?
    pub fn used_cols(&self, file_num: usize) -> Vec<usize> {
        let mut v = Vec::new();
        for x in &self.c {
            x.used_cols(&mut v, file_num);
        }
        v
    }
    /// add
    pub fn add(&mut self, x: &str) -> Result<()> {
        self.c.push(CompMaker::make_line_comp(x)?);
        Ok(())
    }
More examples
src/bin/cdx/uniq_main.rs (line 99)
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
fn get_which2(&mut self, which: &str, pattern: &str) -> Result<()> {
        self.which = if which.eq_ignore_ascii_case("first") {
            Which::First
        } else if which.eq_ignore_ascii_case("last") {
            Which::Last
        } else if which.eq_ignore_ascii_case("min") {
            Which::Min
        } else if which.eq_ignore_ascii_case("max") {
            Which::Max
        } else {
            return err!("Which must be one of first,last,min,max : {}", which);
        };
        self.comp = CompMaker::make_line_comp(pattern)?;
        Ok(())
    }
src/join.rs (line 199)
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
fn join(&mut self, config: &JoinConfig) -> Result<()> {
        if config.infiles.len() < 2 {
            return err!(
                "Join requires at least two input files, {} found",
                config.infiles.len()
            );
        }

        for x in &config.infiles {
            self.r.push(Reader::new_open(x)?);
        }

        for _x in 0..config.infiles.len() {
            self.no_match.push(None)
        }
        for x in &config.unmatch_out {
            if (x.file_num < 1) || (x.file_num > config.infiles.len()) {
                return err!(
                    "Join had {} input files, but requested non matching lines from file {}",
                    config.infiles.len(),
                    x.file_num
                );
            }
            let num = x.file_num - 1;
            if self.no_match[num].is_none() {
                let mut w = get_writer(&x.file_name)?;
                self.r[num].write_header(&mut w)?;
                self.no_match[num] = Some(w);
            } else {
                return err!("Multiple uses of --also for file {}", x.file_num);
            }
        }

        if config.keys.is_empty() {
            self.comp.push(CompMaker::make_line_comp("1")?);
        } else {
            for x in &config.keys {
                self.comp.push(CompMaker::make_line_comp(x)?);
            }
        }
        for i in 0..self.r.len() {
            self.comp.lookup_n(&self.r[i].names(), i)?;
        }

        if config.col_specs.is_empty() {
            for f in 0..self.r.len() {
                let used = self.comp.used_cols(f);
                for x in 0..self.r[f].names().len() {
                    if (f == 0) || !used.contains(&x) {
                        self.out_cols.push(OneOutCol::new_plain(f, x));
                    }
                }
            }
        } else {
            for x in &config.col_specs {
                let mut x = x.clone();
                if x.file >= self.r.len() {
                    return err!(
                        "{} input files, but file {} referred to as an output column",
                        self.r.len(),
                        x.file
                    );
                }
                x.cols.lookup(&self.r[x.file].names())?;
                for y in x.cols.get_cols() {
                    self.out_cols.push(OneOutCol::new(x.file, y));
                }
            }
        }
        if self.out_cols.is_empty() {
            return err!("No output columns specified");
        }

        if self.r[0].cont.has_header {
            self.yes_match.write_all(b" CDX")?;
            for x in &self.out_cols {
                self.yes_match.write_all(&[config.out_delim])?;
                x.write_head(&mut self.yes_match, &self.r)?;
            }
            self.yes_match.write_all(&[b'\n'])?;
        }
        if config.jtype == JoinType::Quick {
            self.join_quick(config)
        } else {
            err!("Only quick supported")
        }
    }

create LineComp from columns, method and pattern

Examples found in repository
src/comp.rs (line 1055)
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
pub fn make_line_comp(spec: &str) -> Result<LineComp> {
        if let Some((a, b)) = spec.split_once(',') {
            if let Some((c, d)) = b.split_once(',') {
                Self::make_line_comp_parts(a, c, d)
            } else {
                Self::make_line_comp_parts(a, b, "")
            }
        } else {
            Self::make_line_comp_parts(spec, "", "")
        }
    }

reset the Compare inside the Comp

Examples found in repository
src/comp.rs (line 1048)
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
pub fn make_comp_parts(method: &str, pattern: &str) -> Result<Comp> {
        let mut comp = Comp::new();
        comp.pattern = pattern.to_string();
        if !method.is_empty() {
            for x in method.split('.') {
                if x.eq_ignore_ascii_case("rev") {
                    comp.reverse = true;
                } else if x.eq_ignore_ascii_case("strict") {
                    comp.junk.junk_type = JunkType::None;
                } else if x.eq_ignore_ascii_case("trail") {
                    comp.junk.junk_type = JunkType::Trailing;
                } else if x.eq_ignore_ascii_case("low") {
                    comp.junk.junk_val = JunkVal::Min;
                } else {
                    comp.ctype = x.to_string();
                }
            }
        }
        Self::remake_comp(&mut comp)?;
        Ok(comp)
    }

reset the LineCompare inside the LineComp

Examples found in repository
src/comp.rs (line 1083)
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
pub fn make_line_comp_parts(cols: &str, method: &str, pattern: &str) -> Result<LineComp> {
        let mut comp = LineComp::new();
        comp.pattern = pattern.to_string();
        comp.cols = cols.to_string();
        if !method.is_empty() {
            for x in method.split('.') {
                if x.eq_ignore_ascii_case("rev") {
                    comp.reverse = true;
                } else if x.eq_ignore_ascii_case("strict") {
                    comp.junk.junk_type = JunkType::None;
                } else if x.eq_ignore_ascii_case("trail") {
                    comp.junk.junk_type = JunkType::Trailing;
                } else if x.eq_ignore_ascii_case("low") {
                    comp.junk.junk_val = JunkVal::Min;
                } else {
                    comp.ctype = x.to_string();
                }
            }
        }
        Self::remake_line_comp(&mut comp)?;
        Ok(comp)
    }

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Performs the conversion.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more