Struct cdx::column::ColumnSet[][src]

pub struct ColumnSet { /* fields omitted */ }
Expand description

A column set is a collection of column specifictions, which when interpreted in the context of a set of named columns, produces a list of column numbers It contains a bunch of “yes” specs and “no” specs. If there are no “yes” specs, all columns are marked “yes” The resulting list of column numbers is all of the “yes” columns in order, minus any “no” columns. Thus if a column appears in both, it will be excluded.

Examples

   use cdx::column::ColumnSet;
   let header: [&str; 5] = ["zero", "one", "two", "three", "four"];

   let mut s = ColumnSet::new();
   s.lookup(&header);
   assert_eq!(s.get_cols_num(), &[0,1,2,3,4]);

   let mut s = ColumnSet::new();
   s.add_yes("-");
   s.lookup(&header);
   assert_eq!(s.get_cols_num(), &[0,1,2,3,4]);

   let mut s = ColumnSet::new();
   s.add_yes("one-three");
   s.lookup(&header);
   assert_eq!(s.get_cols_num(), &[1,2,3]);

   let mut s = ColumnSet::new();
   s.add_no("three,one");
   s.lookup(&header);
   assert_eq!(s.get_cols_num(), &[0,2,4]);

   let mut s = ColumnSet::new();
   s.add_no("+4-+2");
   s.lookup(&header);
   assert_eq!(s.get_cols_num(), &[0,4]);

   let mut s = ColumnSet::new();
   s.add_yes(">s<=two");
   s.lookup(&header);
   assert_eq!(s.get_cols_num(), &[2,3]);

Implementations

Create an empty column set, which selects all columns.

Examples found in repository
src/column.rs (line 457)
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
pub fn ranges(fieldnames: &[&str], rng: &str) -> Result<Vec<OutCol>> {
        let mut c = ColumnSet::new();
        c.add_yes(rng);
        c.lookup(fieldnames)?;
        Ok(c.get_cols_full())
    }
    /// turn range into list of column numbers
    fn range(fieldnames: &[&str], rng: &str) -> Result<Vec<OutCol>> {
        if rng.is_empty() {
            return err!("Empty Range {}", rng);
        }
        let (name, range) = match rng.split_once(':') {
            None => ("", rng),
            Some(x) => x,
        };

        let ch = range.chars().next().unwrap();
        if ch == '<' || ch == '>' || ch == '=' {
            return Ok(Self::to_outcols(
                &Self::text_range(fieldnames, range)?,
                name,
            ));
        }
        if range.contains('*') || rng.contains('?') {
            return Ok(Self::to_outcols(
                &Self::glob_range(fieldnames, range)?,
                name,
            ));
        }

        let mut parts: Vec<&str> = range.split('-').collect();
        if parts.len() > 2 {
            return err!("Malformed Range {}", rng);
        }
        if parts[0].is_empty() {
            parts[0] = "1";
        }

        let start: usize;
        let end: usize;
        if parts.len() == 1 {
            start = Self::single(fieldnames, parts[0])?;
            end = start;
        } else {
            if parts[1].is_empty() {
                parts[1] = "+1";
            }
            start = Self::single(fieldnames, parts[0])?;
            end = Self::single(fieldnames, parts[1])?;
        }

        if start > end {
            // throw new CdxException("start > end, i.e. {" + parts.get(0) + " > " + parts.get(1));
            return err!("Start greater than end : {}", rng);
        }
        let mut res = Vec::new();
        for i in start..=end {
            res.push(OutCol::new(i, name));
        }
        Ok(res)
    }

    /// resolve `ColumnSet` in context of the column names from an input file
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    assert_eq!(s.get_cols_num(), &[0,1,3,4]);
    /// ```
    pub fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.did_lookup = true;
        self.columns = Vec::new();
        let mut no_cols: HashSet<usize> = HashSet::new();

        for s in &self.neg {
            for x in Self::range(fieldnames, s)? {
                no_cols.insert(x.num);
            }
        }

        if self.pos.is_empty() {
            for x in 0..fieldnames.len() {
                if !no_cols.contains(&x) {
                    self.columns.push(OutCol::from_num(x));
                }
            }
        } else {
            for s in &self.pos {
                for x in Self::range(fieldnames, s)? {
                    if !no_cols.contains(&x.num) {
                        self.columns.push(x);
                    }
                }
            }
        }
        Ok(())
    }

    /// Select columns from input line based on `ColumnSet`. Fail if input is too short. """
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    let v = ["Zeroth", "First", "Second", "Third", "Fourth", "Fifth"];
    ///    let mut res = Vec::new();
    ///    s.select(&v, &mut res);
    ///    assert_eq!(res, vec!["Zeroth", "First", "Third", "Fourth"]);
    /// ```
    pub fn select<T: AsRef<str> + Clone>(&self, cols: &[T], result: &mut Vec<T>) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        result.clear();
        for x in &self.columns {
            if x.num < cols.len() {
                result.push(cols[x.num].clone());
            } else {
                return err!(
                    "Line has only {} columns, but column {} was requested.",
                    cols.len(),
                    x.num + 1
                );
            }
        }
        Ok(())
    }

    /// write the appropriate selection from the given columns
    /// trying to write a non-existant column is an error
    pub fn write(&self, w: &mut dyn Write, cols: &[&str], delim: &str) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols[first.num].as_bytes())?;

                for x in iter {
                    w.write_all(delim.as_bytes())?;
                    if x.num < cols.len() {
                        w.write_all(cols[x.num].as_bytes())?;
                    } else {
                        return err!(
                            "Line has only {} columns, but column {} was requested.",
                            cols.len(),
                            x.num + 1
                        );
                    }
                }
            }
        };
        w.write_all(&[b'\n'])?;
        Ok(())
    }

    /// write the appropriate selection from the given columns
    pub fn write2(&self, w: &mut dyn Write, cols: &TextLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(&cols[first.num])?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num))?;
                }
            }
        };
        w.write_all(&[b'\n'])?;
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    pub fn write3(&self, w: &mut dyn Write, cols: &TextLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols.get(first.num))?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num))?;
                }
            }
        };
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    pub fn write3s(&self, w: &mut dyn Write, cols: &StringLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols.get(first.num).as_bytes())?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num).as_bytes())?;
                }
            }
        };
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    /// trying to write a non-existant column writes the provided default value
    pub fn write_sloppy(&self, cols: &[&str], rest: &str, w: &mut dyn Write) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        for x in &self.columns {
            if x.num < cols.len() {
                w.write_all(cols[x.num].as_bytes())?;
            } else {
                w.write_all(rest.as_bytes())?;
            }
        }
        Ok(())
    }

    /// Select columns from input line based on `ColumnSet`, fill in default if line is too short """
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    let v = ["Zeroth", "First", "Second", "Third"];
    ///    let mut res = Vec::new();
    ///    s.select_sloppy(&v, &"extra", &mut res);
    ///    assert_eq!(res, vec!["Zeroth", "First", "Third", "extra"]);
    /// ```
    pub fn select_sloppy<T: AsRef<str> + Clone>(
        &self,
        cols: &[T],
        restval: &T,
        result: &mut Vec<T>,
    ) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        result.clear();
        for x in &self.columns {
            if x.num < cols.len() {
                result.push(cols[x.num].clone());
            } else {
                result.push(restval.clone());
            }
        }
        Ok(())
    }

    /// return owned columns by const reference
    pub fn get_cols(&self) -> &Vec<OutCol> {
        &self.columns
    }

    /// steal owned columns by value
    pub fn get_cols_full(self) -> Vec<OutCol> {
        self.columns
    }

    /// get owned column numbers
    pub fn get_cols_num(&self) -> Vec<usize> {
        let mut v = Vec::with_capacity(self.columns.len());
        for x in &self.columns {
            v.push(x.num);
        }
        v
    }

    /// Shorthand to look up some columns
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    assert_eq!(ColumnSet::lookup_cols("~2-3", &header).unwrap(), &[0,3,4]);
    /// ```
    pub fn lookup_cols(spec: &str, names: &[&str]) -> Result<Vec<usize>> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        Ok(s.get_cols_num())
    }

    /// Shorthand to look up some columns, with names
    pub fn lookup_cols_full(spec: &str, names: &[&str]) -> Result<Vec<OutCol>> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        Ok(s.get_cols_full())
    }

    /// Shorthand to look up a single column
    /// To look up a single named column, `lookup_col` is also available
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    assert_eq!(ColumnSet::lookup1("three", &header).unwrap(), 3);
    /// ```
    pub fn lookup1(spec: &str, names: &[&str]) -> Result<usize> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        if s.get_cols().len() != 1 {
            return err!(
                "Spec {} resolves to {} columns, rather than a single column",
                spec,
                s.get_cols().len()
            );
        }
        Ok(s.get_cols_num()[0])
    }
}

/// Write the columns with a custom delimiter
pub struct ColumnClump<'a> {
    cols: Box<dyn ColumnFun + 'a>,
    name: String,
    delim: u8,
}
impl fmt::Debug for ColumnClump<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ColumnClump")
    }
}

impl<'a> ColumnClump<'a> {
    /// new ColumnClump from parts
    pub fn new(cols: Box<dyn ColumnFun + 'a>, name: &str, delim: u8) -> Self {
        Self {
            cols,
            name: name.to_string(),
            delim,
        }
    }
    /// new ColumnClump from spec : DelimOutcol:Columns
    /// e.g. ,group:1-3
    pub fn from_spec(orig_spec: &str) -> Result<Self> {
        let mut spec = orig_spec;
        if spec.is_empty() {
            return err!("Can't construct a group from an empty string");
        }
        let delim = spec.take_first();
        if delim.len_utf8() != 1 {
            return err!("Delimiter must be a plain ascii character : {}", orig_spec);
        }
        let parts = spec.split_once(':');
        if parts.is_none() {
            return err!(
                "No colon found. Group format is DelimOutname:Columns : {}",
                orig_spec
            );
        }
        let parts = parts.unwrap();
        let mut g = ColumnSet::new();
        g.add_yes(parts.1);
        let cols = Box::new(ReaderColumns::new(g));
        Ok(Self {
            cols,
            name: parts.0.to_string(),
            delim: delim as u8,
        })
    }
More examples
src/bin/cdx/join_main.rs (line 25)
 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
pub fn main(argv: &[String]) -> Result<()> {
    let prog = args::ProgSpec::new("Join files on a matching column.", args::FileCount::Many);
    const A: [ArgSpec; 4] = [
        arg! {"also", "a", "FileNum,FileName", "Write non-matching lines from this file to this file."},
        arg! {"file", "f", "OutputFile", "Output File Name, default '-' for stdout"},
        arg! {"key", "k", "Spec", "How to compare lines"},
        arg! {"output", "o", "Spec", "Output columns : file.ColumnSet,file.ColumnSet"},
    ];
    let (args, files) = args::parse(&prog, &A, argv);

    let mut config = JoinConfig::new();
    config.infiles = files;
    for x in args {
        if x.name == "key" {
            config.keys.push(x.value);
        } else if x.name == "output" {
            let mut file: Option<usize> = None;
            let mut set = ColumnSet::new();
            for y in x.value.split(',') {
                let z = y.split_once('.');
                if let Some((num, spec)) = z {
                    if !set.is_empty() {
                        config.out_cols.push(OutColSpec::new(file.unwrap(), set));
                        set = ColumnSet::new();
                    }
                    let fnum = num.parse::<usize>()?;
                    if fnum == 0 {
                        return err!("file number must be greater than zero {}", y);
                    }
                    file = Some(fnum - 1);
                    set.add_yes(spec);
                } else {
                    if file.is_none() {
                        return err!(
                            "First part of output spec must start with 'file.' {}",
                            x.value
                        );
                    }
                    set.add_yes(y);
                }
            }
            if !set.is_empty() {
                config.out_cols.push(OutColSpec::new(file.unwrap(), set));
            }
        } else if x.name == "file" {
            config.match_out = x.value;
        } else if x.name == "also" {
            let parts = x.value.split_once(',');
            if let Some((a, b)) = parts {
                config
                    .unmatch_out
                    .push(NoMatch::new(a.parse::<usize>()?, b));
            } else {
                return err!("--also format is FileNum,FileName {}", x.value);
            }
        } else {
            unreachable!();
        }
    }
    config.join()
}

is empty?

Examples found in repository
src/bin/cdx/join_main.rs (line 29)
 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
pub fn main(argv: &[String]) -> Result<()> {
    let prog = args::ProgSpec::new("Join files on a matching column.", args::FileCount::Many);
    const A: [ArgSpec; 4] = [
        arg! {"also", "a", "FileNum,FileName", "Write non-matching lines from this file to this file."},
        arg! {"file", "f", "OutputFile", "Output File Name, default '-' for stdout"},
        arg! {"key", "k", "Spec", "How to compare lines"},
        arg! {"output", "o", "Spec", "Output columns : file.ColumnSet,file.ColumnSet"},
    ];
    let (args, files) = args::parse(&prog, &A, argv);

    let mut config = JoinConfig::new();
    config.infiles = files;
    for x in args {
        if x.name == "key" {
            config.keys.push(x.value);
        } else if x.name == "output" {
            let mut file: Option<usize> = None;
            let mut set = ColumnSet::new();
            for y in x.value.split(',') {
                let z = y.split_once('.');
                if let Some((num, spec)) = z {
                    if !set.is_empty() {
                        config.out_cols.push(OutColSpec::new(file.unwrap(), set));
                        set = ColumnSet::new();
                    }
                    let fnum = num.parse::<usize>()?;
                    if fnum == 0 {
                        return err!("file number must be greater than zero {}", y);
                    }
                    file = Some(fnum - 1);
                    set.add_yes(spec);
                } else {
                    if file.is_none() {
                        return err!(
                            "First part of output spec must start with 'file.' {}",
                            x.value
                        );
                    }
                    set.add_yes(y);
                }
            }
            if !set.is_empty() {
                config.out_cols.push(OutColSpec::new(file.unwrap(), set));
            }
        } else if x.name == "file" {
            config.match_out = x.value;
        } else if x.name == "also" {
            let parts = x.value.split_once(',');
            if let Some((a, b)) = parts {
                config
                    .unmatch_out
                    .push(NoMatch::new(a.parse::<usize>()?, b));
            } else {
                return err!("--also format is FileNum,FileName {}", x.value);
            }
        } else {
            unreachable!();
        }
    }
    config.join()
}

Create an column set from a spec, e.g. “1-3”

Examples found in repository
src/bin/cdx/cut_main.rs (line 23)
 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
pub fn main(argv: &[String]) -> Result<()> {
    let prog = args::ProgSpec::new("Select columns", args::FileCount::Many);
    const A: [ArgSpec; 4] = [
        arg! {"fields", "f", "Columns", "the columns to select."},
        arg! {"group", "g", "Columns", "the columns in a bunch, e.g. '.group:1-3'"},
        arg! {"composite", "c", "Spec", "new value made from parts. e.g. 'stuff:abc^{two}def'"},
        arg_enum! {"header", "h", "Mode", "header requirements", &HEADER_MODE},
    ];
    let (args, files) = args::parse(&prog, &A, argv);
    let mut checker = HeaderChecker::new();
    let mut v = Writer::new(b'\t');
    for x in args {
        if x.name == "header" {
            checker.mode = HeaderMode::from_str(&x.value)?;
        } else if x.name == "fields" {
            v.push(Box::new(ReaderColumns::new(ColumnSet::from_spec(&x.value))));
        } else if x.name == "group" {
            v.push(Box::new(ColumnClump::from_spec(&x.value)?));
        } else if x.name == "composite" {
            v.push(Box::new(CompositeColumn::new(&x.value)?));
        } else {
            unreachable!();
        }
    }

    if v.is_empty() {
        return Err(Error::Error(
            "cut requires at lease one --columns or --groups".to_string(),
        ));
    }

    let mut w = get_writer("-")?;
    let mut not_header: Vec<u8> = Vec::new();
    for x in &files {
        let mut f = Reader::new();
        f.open(x)?;
        if f.is_empty() {
            continue;
        }
        v.lookup(&f.names())?;
        not_header.clear();
        v.write_names(&mut not_header, f.header())?;
        if checker.check(&not_header, x)? && f.cont.has_header {
            w.write_all(&not_header)?;
        }
        if f.is_done() {
            continue;
        }
        loop {
            v.write(&mut w, f.curr())?;
            if f.getline()? {
                break;
            }
        }
    }
    Ok(())
}

Add some columns to be selected

Examples found in repository
src/column.rs (line 132)
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
pub fn new(spec: &str, del: char) -> Self {
        let mut s = ScopedValue::default();
        if spec.is_empty() {
            return s;
        }
        let mut spec = spec;
        let ch = spec.first();
        if ch == del {
            spec.skip_first();
            if spec.is_empty() {
                s.value.push(del);
                return s;
            }
            let ch = spec.first();
            if ch == del {
                s.value.push(del);
            }
        }
        while !spec.is_empty() {
            let ch = spec.take_first();
            if ch == del {
                s.cols.add_yes(spec);
                return s;
            }
            s.value.push(ch);
        }
        s
    }
    /// two strings
    pub fn new2(value: &str, cols: &str) -> Self {
        let mut s = ScopedValue::default();
        s.cols.add_yes(cols);
        s.value = value.to_string();
        s
    }
    /// resolve named columns
    pub fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.cols.lookup(fieldnames)
    }
}

/// A per-column value
#[derive(Debug, Clone, Default)]
pub struct ScopedValues {
    default: String,
    data: Vec<ScopedValue>,

    has_value: Vec<bool>,
    strings: Vec<String>,
    ints: Vec<i64>,
    floats: Vec<f64>,
}

impl ScopedValues {
    /// new
    pub fn new() -> Self {
        ScopedValues::default()
    }
    /// value for column not otherwise assigned a value
    pub fn set_default(&mut self, d: &str) {
        self.default = d.to_string();
    }
    /// resolve named columns
    pub fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.has_value.clear();
        self.has_value.resize(fieldnames.len(), false);
        self.strings.clear();
        self.strings.resize(fieldnames.len(), self.default.clone());
        for x in &mut self.data {
            x.lookup(fieldnames)?;
            for i in 0..x.cols.columns.len() {
                self.strings[i] = x.value.clone();
                self.has_value[i] = true;
            }
        }
        Ok(())
    }
    /// do the work so that get_int() will work properly
    pub fn make_ints(&mut self) -> Result<()> {
        self.ints.clear();
        for i in 0..self.strings.len() {
            self.ints[i] = self.get(i).parse::<i64>()?;
        }
        Ok(())
    }
    /// do the work so that get_int() will work properly
    pub fn make_floats(&mut self) -> Result<()> {
        self.floats.clear();
        for i in 0..self.strings.len() {
            self.floats[i] = self.get(i).parse::<f64>()?;
        }
        Ok(())
    }

    /// add one ScopedValue
    pub fn add(&mut self, spec: &str, del: char) {
        self.data.push(ScopedValue::new(spec, del));
    }
    /// add one ScopedValue
    pub fn add2(&mut self, value: &str, cols: &str) {
        self.data.push(ScopedValue::new2(value, cols));
    }
    /// get appropriate value for the column
    pub fn get(&self, col: usize) -> &str {
        if col < self.strings.len() {
            &self.strings[col]
        } else {
            self.strings.last().unwrap()
        }
    }
    /// get appropriate int value for the column
    pub fn get_int(&self, col: usize) -> i64 {
        if col < self.ints.len() {
            self.ints[col]
        } else {
            *self.ints.last().unwrap()
        }
    }
    /// get appropriate int value for the column
    pub fn get_float(&self, col: usize) -> f64 {
        if col < self.floats.len() {
            self.floats[col]
        } else {
            *self.floats.last().unwrap()
        }
    }
    /// has this column been assigned a value?
    pub fn has_value(&self, col: usize) -> bool {
        if col < self.has_value.len() {
            self.has_value[col]
        } else {
            false
        }
    }
    /// Have any column been assigned values?
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
}

/// Write some output
pub trait ColumnFun {
    /// write the column names (called once)
    fn write_names(&self, w: &mut dyn Write, head: &StringLine, delim: u8) -> Result<()>;
    /// write the column values (called many times)
    fn write(&self, w: &mut dyn Write, line: &TextLine, delim: u8) -> Result<()>;
    /// resolve any named columns
    fn lookup(&mut self, fieldnames: &[&str]) -> Result<()>;
}

impl fmt::Debug for dyn ColumnFun {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "ColumnFun")
    }
}

impl ColumnSet {
    /// Create an empty column set, which selects all columns.
    pub fn new() -> Self {
        ColumnSet::default()
    }
    /// is empty?
    pub fn is_empty(&self) -> bool {
        self.pos.is_empty() && self.neg.is_empty()
    }

    /// Create an column set from a spec, e.g. "1-3"
    pub fn from_spec(spec: &str) -> Self {
        let mut s = ColumnSet::default();
        s.add_yes(spec);
        s
    }

    /// Add some columns to be selected
    pub fn add_yes(&mut self, spec: &str) {
        self.add(spec, false);
    }

    /// Add some columns to be rejected.
    pub fn add_no(&mut self, spec: &str) {
        self.add(spec, true);
    }

    /// Add a spec, "yes" or "no" based on a flag.
    pub fn add(&mut self, spec: &str, negate: bool) {
        for s in spec.split(',') {
            if let Some(stripped) = s.strip_prefix('~') {
                let st = stripped.to_string();
                if negate {
                    self.pos.push(st);
                } else {
                    self.neg.push(st);
                }
            } else {
                let st = s.to_string();
                if negate {
                    self.neg.push(st);
                } else {
                    self.pos.push(st);
                }
            }
        }
    }

    /// Turn column name into column number
    /// To also handle numbers and ranges, use `lookup1`
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    assert_eq!(ColumnSet::lookup_col(&["zero", "one", "two"], "one").unwrap(), 1);
    /// ```
    pub fn lookup_col(fieldnames: &[&str], colname: &str) -> Result<usize> {
        for f in fieldnames.iter().enumerate() {
            if f.1 == &colname {
                return Ok(f.0);
            }
        }
        err!("{} not found", colname)
    }
    /*
        /// turn a u8 column name into a column number
        pub fn lookup_col2(fieldnames: &[&str], colname: &[u8]) -> Result<usize> {
        let name = str::from_utf8_lossy(colname);
            for f in fieldnames.iter().enumerate() {
                if *f.1 == name {
                    return Ok(f.0);
                }
            }
            err!("{:?} not found", &colname)
        }
    */
    /// resolve a single name or number into a column number
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    assert_eq!(ColumnSet::single(&["zero", "one", "two"], "+1").unwrap(), 2);
    /// ```
    pub fn single(fieldnames: &[&str], colname: &str) -> Result<usize> {
        if let Some(stripped) = colname.strip_prefix('+') {
            let n = str_to_u_whole(stripped.as_bytes())? as usize;
            let len = fieldnames.len();
            if n > len {
                err!("Column {} out of bounds", colname)
            } else {
                Ok(len - n)
            }
        } else {
            let ch = colname.chars().next().unwrap();
            if ch.is_ascii_digit() {
                let n = str_to_u_whole(colname.as_bytes())? as usize;
                if n < 1 {
                    err!("Column {} out of bounds", colname)
                } else {
                    Ok(n - 1)
                }
            } else {
                Self::lookup_col(fieldnames, colname)
            }
        }
    }

    /// determine if two strings match, given an operator
    fn do_compare(left: &str, right: &str, operator: &str) -> Result<bool> {
        let val = left.cmp(right);
        if operator == "<" {
            return Ok(val == Ordering::Less);
        }
        if operator == "<=" {
            return Ok(val != Ordering::Greater);
        }
        if operator == ">" {
            return Ok(val == Ordering::Greater);
        }
        if operator == ">=" {
            return Ok(val != Ordering::Less);
        }
        err!(operator.to_string())
    }

    /// determine if a name is within a range
    fn do_compare2(name: &str, key1: &str, op1: &str, key2: &str, op2: &str) -> Result<bool> {
        Ok(Self::do_compare(name, key1, op1)? && Self::do_compare(name, key2, op2)?)
    }

    /// Return all the fields that match the glob
    fn glob_range(fieldnames: &[&str], rng: &str) -> Result<Vec<usize>> {
        let mut ret = Vec::new();
        for f in fieldnames.iter().enumerate() {
            if f.1.glob(rng, Case::Sens) {
                // allow case insensitive?
                ret.push(f.0);
            }
        }
        Ok(ret)
    }
    /// Return all the field numbers that match a textual spec like <foo or <foo>bar """
    fn text_range(fieldnames: &[&str], rng: &str) -> Result<Vec<usize>> {
        let mut ret = Vec::new();
        lazy_static! {
            static ref RE1: Regex = Regex::new("^([<>]=?)([^<>]+)$").unwrap();
            static ref RE2: Regex = Regex::new("^([<>]=?)([^<>]+)([<>]=?)([^<>]+)$").unwrap();
        }

        if let Some(caps) = RE1.captures(rng) {
            for f in fieldnames.iter().enumerate() {
                if Self::do_compare(
                    f.1,
                    caps.get(2).unwrap().as_str(),
                    caps.get(1).unwrap().as_str(),
                )? {
                    ret.push(f.0);
                }
            }
            return Ok(ret);
        }

        if let Some(caps) = RE2.captures(rng) {
            for f in fieldnames.iter().enumerate() {
                if Self::do_compare2(
                    f.1,
                    caps.get(2).unwrap().as_str(),
                    caps.get(1).unwrap().as_str(),
                    caps.get(4).unwrap().as_str(),
                    caps.get(3).unwrap().as_str(),
                )? {
                    ret.push(f.0);
                }
            }
            return Ok(ret);
        }

        err!("Malformed Range {}", rng)
    }

    fn to_outcols(data: &[usize], name: &str) -> Vec<OutCol> {
        let mut ret = Vec::with_capacity(data.len());
        for x in data {
            ret.push(OutCol::new(*x, name));
        }
        ret
    }

    /// turn comma delimited list of ranges into list of possibly named column numbers
    pub fn ranges(fieldnames: &[&str], rng: &str) -> Result<Vec<OutCol>> {
        let mut c = ColumnSet::new();
        c.add_yes(rng);
        c.lookup(fieldnames)?;
        Ok(c.get_cols_full())
    }
    /// turn range into list of column numbers
    fn range(fieldnames: &[&str], rng: &str) -> Result<Vec<OutCol>> {
        if rng.is_empty() {
            return err!("Empty Range {}", rng);
        }
        let (name, range) = match rng.split_once(':') {
            None => ("", rng),
            Some(x) => x,
        };

        let ch = range.chars().next().unwrap();
        if ch == '<' || ch == '>' || ch == '=' {
            return Ok(Self::to_outcols(
                &Self::text_range(fieldnames, range)?,
                name,
            ));
        }
        if range.contains('*') || rng.contains('?') {
            return Ok(Self::to_outcols(
                &Self::glob_range(fieldnames, range)?,
                name,
            ));
        }

        let mut parts: Vec<&str> = range.split('-').collect();
        if parts.len() > 2 {
            return err!("Malformed Range {}", rng);
        }
        if parts[0].is_empty() {
            parts[0] = "1";
        }

        let start: usize;
        let end: usize;
        if parts.len() == 1 {
            start = Self::single(fieldnames, parts[0])?;
            end = start;
        } else {
            if parts[1].is_empty() {
                parts[1] = "+1";
            }
            start = Self::single(fieldnames, parts[0])?;
            end = Self::single(fieldnames, parts[1])?;
        }

        if start > end {
            // throw new CdxException("start > end, i.e. {" + parts.get(0) + " > " + parts.get(1));
            return err!("Start greater than end : {}", rng);
        }
        let mut res = Vec::new();
        for i in start..=end {
            res.push(OutCol::new(i, name));
        }
        Ok(res)
    }

    /// resolve `ColumnSet` in context of the column names from an input file
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    assert_eq!(s.get_cols_num(), &[0,1,3,4]);
    /// ```
    pub fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.did_lookup = true;
        self.columns = Vec::new();
        let mut no_cols: HashSet<usize> = HashSet::new();

        for s in &self.neg {
            for x in Self::range(fieldnames, s)? {
                no_cols.insert(x.num);
            }
        }

        if self.pos.is_empty() {
            for x in 0..fieldnames.len() {
                if !no_cols.contains(&x) {
                    self.columns.push(OutCol::from_num(x));
                }
            }
        } else {
            for s in &self.pos {
                for x in Self::range(fieldnames, s)? {
                    if !no_cols.contains(&x.num) {
                        self.columns.push(x);
                    }
                }
            }
        }
        Ok(())
    }

    /// Select columns from input line based on `ColumnSet`. Fail if input is too short. """
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    let v = ["Zeroth", "First", "Second", "Third", "Fourth", "Fifth"];
    ///    let mut res = Vec::new();
    ///    s.select(&v, &mut res);
    ///    assert_eq!(res, vec!["Zeroth", "First", "Third", "Fourth"]);
    /// ```
    pub fn select<T: AsRef<str> + Clone>(&self, cols: &[T], result: &mut Vec<T>) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        result.clear();
        for x in &self.columns {
            if x.num < cols.len() {
                result.push(cols[x.num].clone());
            } else {
                return err!(
                    "Line has only {} columns, but column {} was requested.",
                    cols.len(),
                    x.num + 1
                );
            }
        }
        Ok(())
    }

    /// write the appropriate selection from the given columns
    /// trying to write a non-existant column is an error
    pub fn write(&self, w: &mut dyn Write, cols: &[&str], delim: &str) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols[first.num].as_bytes())?;

                for x in iter {
                    w.write_all(delim.as_bytes())?;
                    if x.num < cols.len() {
                        w.write_all(cols[x.num].as_bytes())?;
                    } else {
                        return err!(
                            "Line has only {} columns, but column {} was requested.",
                            cols.len(),
                            x.num + 1
                        );
                    }
                }
            }
        };
        w.write_all(&[b'\n'])?;
        Ok(())
    }

    /// write the appropriate selection from the given columns
    pub fn write2(&self, w: &mut dyn Write, cols: &TextLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(&cols[first.num])?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num))?;
                }
            }
        };
        w.write_all(&[b'\n'])?;
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    pub fn write3(&self, w: &mut dyn Write, cols: &TextLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols.get(first.num))?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num))?;
                }
            }
        };
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    pub fn write3s(&self, w: &mut dyn Write, cols: &StringLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols.get(first.num).as_bytes())?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num).as_bytes())?;
                }
            }
        };
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    /// trying to write a non-existant column writes the provided default value
    pub fn write_sloppy(&self, cols: &[&str], rest: &str, w: &mut dyn Write) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        for x in &self.columns {
            if x.num < cols.len() {
                w.write_all(cols[x.num].as_bytes())?;
            } else {
                w.write_all(rest.as_bytes())?;
            }
        }
        Ok(())
    }

    /// Select columns from input line based on `ColumnSet`, fill in default if line is too short """
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    let v = ["Zeroth", "First", "Second", "Third"];
    ///    let mut res = Vec::new();
    ///    s.select_sloppy(&v, &"extra", &mut res);
    ///    assert_eq!(res, vec!["Zeroth", "First", "Third", "extra"]);
    /// ```
    pub fn select_sloppy<T: AsRef<str> + Clone>(
        &self,
        cols: &[T],
        restval: &T,
        result: &mut Vec<T>,
    ) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        result.clear();
        for x in &self.columns {
            if x.num < cols.len() {
                result.push(cols[x.num].clone());
            } else {
                result.push(restval.clone());
            }
        }
        Ok(())
    }

    /// return owned columns by const reference
    pub fn get_cols(&self) -> &Vec<OutCol> {
        &self.columns
    }

    /// steal owned columns by value
    pub fn get_cols_full(self) -> Vec<OutCol> {
        self.columns
    }

    /// get owned column numbers
    pub fn get_cols_num(&self) -> Vec<usize> {
        let mut v = Vec::with_capacity(self.columns.len());
        for x in &self.columns {
            v.push(x.num);
        }
        v
    }

    /// Shorthand to look up some columns
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    assert_eq!(ColumnSet::lookup_cols("~2-3", &header).unwrap(), &[0,3,4]);
    /// ```
    pub fn lookup_cols(spec: &str, names: &[&str]) -> Result<Vec<usize>> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        Ok(s.get_cols_num())
    }

    /// Shorthand to look up some columns, with names
    pub fn lookup_cols_full(spec: &str, names: &[&str]) -> Result<Vec<OutCol>> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        Ok(s.get_cols_full())
    }

    /// Shorthand to look up a single column
    /// To look up a single named column, `lookup_col` is also available
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    assert_eq!(ColumnSet::lookup1("three", &header).unwrap(), 3);
    /// ```
    pub fn lookup1(spec: &str, names: &[&str]) -> Result<usize> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        if s.get_cols().len() != 1 {
            return err!(
                "Spec {} resolves to {} columns, rather than a single column",
                spec,
                s.get_cols().len()
            );
        }
        Ok(s.get_cols_num()[0])
    }
}

/// Write the columns with a custom delimiter
pub struct ColumnClump<'a> {
    cols: Box<dyn ColumnFun + 'a>,
    name: String,
    delim: u8,
}
impl fmt::Debug for ColumnClump<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ColumnClump")
    }
}

impl<'a> ColumnClump<'a> {
    /// new ColumnClump from parts
    pub fn new(cols: Box<dyn ColumnFun + 'a>, name: &str, delim: u8) -> Self {
        Self {
            cols,
            name: name.to_string(),
            delim,
        }
    }
    /// new ColumnClump from spec : DelimOutcol:Columns
    /// e.g. ,group:1-3
    pub fn from_spec(orig_spec: &str) -> Result<Self> {
        let mut spec = orig_spec;
        if spec.is_empty() {
            return err!("Can't construct a group from an empty string");
        }
        let delim = spec.take_first();
        if delim.len_utf8() != 1 {
            return err!("Delimiter must be a plain ascii character : {}", orig_spec);
        }
        let parts = spec.split_once(':');
        if parts.is_none() {
            return err!(
                "No colon found. Group format is DelimOutname:Columns : {}",
                orig_spec
            );
        }
        let parts = parts.unwrap();
        let mut g = ColumnSet::new();
        g.add_yes(parts.1);
        let cols = Box::new(ReaderColumns::new(g));
        Ok(Self {
            cols,
            name: parts.0.to_string(),
            delim: delim as u8,
        })
    }
More examples
src/bin/cdx/join_main.rs (line 38)
 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
pub fn main(argv: &[String]) -> Result<()> {
    let prog = args::ProgSpec::new("Join files on a matching column.", args::FileCount::Many);
    const A: [ArgSpec; 4] = [
        arg! {"also", "a", "FileNum,FileName", "Write non-matching lines from this file to this file."},
        arg! {"file", "f", "OutputFile", "Output File Name, default '-' for stdout"},
        arg! {"key", "k", "Spec", "How to compare lines"},
        arg! {"output", "o", "Spec", "Output columns : file.ColumnSet,file.ColumnSet"},
    ];
    let (args, files) = args::parse(&prog, &A, argv);

    let mut config = JoinConfig::new();
    config.infiles = files;
    for x in args {
        if x.name == "key" {
            config.keys.push(x.value);
        } else if x.name == "output" {
            let mut file: Option<usize> = None;
            let mut set = ColumnSet::new();
            for y in x.value.split(',') {
                let z = y.split_once('.');
                if let Some((num, spec)) = z {
                    if !set.is_empty() {
                        config.out_cols.push(OutColSpec::new(file.unwrap(), set));
                        set = ColumnSet::new();
                    }
                    let fnum = num.parse::<usize>()?;
                    if fnum == 0 {
                        return err!("file number must be greater than zero {}", y);
                    }
                    file = Some(fnum - 1);
                    set.add_yes(spec);
                } else {
                    if file.is_none() {
                        return err!(
                            "First part of output spec must start with 'file.' {}",
                            x.value
                        );
                    }
                    set.add_yes(y);
                }
            }
            if !set.is_empty() {
                config.out_cols.push(OutColSpec::new(file.unwrap(), set));
            }
        } else if x.name == "file" {
            config.match_out = x.value;
        } else if x.name == "also" {
            let parts = x.value.split_once(',');
            if let Some((a, b)) = parts {
                config
                    .unmatch_out
                    .push(NoMatch::new(a.parse::<usize>()?, b));
            } else {
                return err!("--also format is FileNum,FileName {}", x.value);
            }
        } else {
            unreachable!();
        }
    }
    config.join()
}

Add some columns to be rejected.

Add a spec, “yes” or “no” based on a flag.

Examples found in repository
src/column.rs (line 286)
285
286
287
288
289
290
291
292
pub fn add_yes(&mut self, spec: &str) {
        self.add(spec, false);
    }

    /// Add some columns to be rejected.
    pub fn add_no(&mut self, spec: &str) {
        self.add(spec, true);
    }

Turn column name into column number To also handle numbers and ranges, use lookup1

Examples
   use cdx::column::ColumnSet;
   assert_eq!(ColumnSet::lookup_col(&["zero", "one", "two"], "one").unwrap(), 1);
Examples found in repository
src/column.rs (line 369)
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
pub fn single(fieldnames: &[&str], colname: &str) -> Result<usize> {
        if let Some(stripped) = colname.strip_prefix('+') {
            let n = str_to_u_whole(stripped.as_bytes())? as usize;
            let len = fieldnames.len();
            if n > len {
                err!("Column {} out of bounds", colname)
            } else {
                Ok(len - n)
            }
        } else {
            let ch = colname.chars().next().unwrap();
            if ch.is_ascii_digit() {
                let n = str_to_u_whole(colname.as_bytes())? as usize;
                if n < 1 {
                    err!("Column {} out of bounds", colname)
                } else {
                    Ok(n - 1)
                }
            } else {
                Self::lookup_col(fieldnames, colname)
            }
        }
    }

    /// determine if two strings match, given an operator
    fn do_compare(left: &str, right: &str, operator: &str) -> Result<bool> {
        let val = left.cmp(right);
        if operator == "<" {
            return Ok(val == Ordering::Less);
        }
        if operator == "<=" {
            return Ok(val != Ordering::Greater);
        }
        if operator == ">" {
            return Ok(val == Ordering::Greater);
        }
        if operator == ">=" {
            return Ok(val != Ordering::Less);
        }
        err!(operator.to_string())
    }

    /// determine if a name is within a range
    fn do_compare2(name: &str, key1: &str, op1: &str, key2: &str, op2: &str) -> Result<bool> {
        Ok(Self::do_compare(name, key1, op1)? && Self::do_compare(name, key2, op2)?)
    }

    /// Return all the fields that match the glob
    fn glob_range(fieldnames: &[&str], rng: &str) -> Result<Vec<usize>> {
        let mut ret = Vec::new();
        for f in fieldnames.iter().enumerate() {
            if f.1.glob(rng, Case::Sens) {
                // allow case insensitive?
                ret.push(f.0);
            }
        }
        Ok(ret)
    }
    /// Return all the field numbers that match a textual spec like <foo or <foo>bar """
    fn text_range(fieldnames: &[&str], rng: &str) -> Result<Vec<usize>> {
        let mut ret = Vec::new();
        lazy_static! {
            static ref RE1: Regex = Regex::new("^([<>]=?)([^<>]+)$").unwrap();
            static ref RE2: Regex = Regex::new("^([<>]=?)([^<>]+)([<>]=?)([^<>]+)$").unwrap();
        }

        if let Some(caps) = RE1.captures(rng) {
            for f in fieldnames.iter().enumerate() {
                if Self::do_compare(
                    f.1,
                    caps.get(2).unwrap().as_str(),
                    caps.get(1).unwrap().as_str(),
                )? {
                    ret.push(f.0);
                }
            }
            return Ok(ret);
        }

        if let Some(caps) = RE2.captures(rng) {
            for f in fieldnames.iter().enumerate() {
                if Self::do_compare2(
                    f.1,
                    caps.get(2).unwrap().as_str(),
                    caps.get(1).unwrap().as_str(),
                    caps.get(4).unwrap().as_str(),
                    caps.get(3).unwrap().as_str(),
                )? {
                    ret.push(f.0);
                }
            }
            return Ok(ret);
        }

        err!("Malformed Range {}", rng)
    }

    fn to_outcols(data: &[usize], name: &str) -> Vec<OutCol> {
        let mut ret = Vec::with_capacity(data.len());
        for x in data {
            ret.push(OutCol::new(*x, name));
        }
        ret
    }

    /// turn comma delimited list of ranges into list of possibly named column numbers
    pub fn ranges(fieldnames: &[&str], rng: &str) -> Result<Vec<OutCol>> {
        let mut c = ColumnSet::new();
        c.add_yes(rng);
        c.lookup(fieldnames)?;
        Ok(c.get_cols_full())
    }
    /// turn range into list of column numbers
    fn range(fieldnames: &[&str], rng: &str) -> Result<Vec<OutCol>> {
        if rng.is_empty() {
            return err!("Empty Range {}", rng);
        }
        let (name, range) = match rng.split_once(':') {
            None => ("", rng),
            Some(x) => x,
        };

        let ch = range.chars().next().unwrap();
        if ch == '<' || ch == '>' || ch == '=' {
            return Ok(Self::to_outcols(
                &Self::text_range(fieldnames, range)?,
                name,
            ));
        }
        if range.contains('*') || rng.contains('?') {
            return Ok(Self::to_outcols(
                &Self::glob_range(fieldnames, range)?,
                name,
            ));
        }

        let mut parts: Vec<&str> = range.split('-').collect();
        if parts.len() > 2 {
            return err!("Malformed Range {}", rng);
        }
        if parts[0].is_empty() {
            parts[0] = "1";
        }

        let start: usize;
        let end: usize;
        if parts.len() == 1 {
            start = Self::single(fieldnames, parts[0])?;
            end = start;
        } else {
            if parts[1].is_empty() {
                parts[1] = "+1";
            }
            start = Self::single(fieldnames, parts[0])?;
            end = Self::single(fieldnames, parts[1])?;
        }

        if start > end {
            // throw new CdxException("start > end, i.e. {" + parts.get(0) + " > " + parts.get(1));
            return err!("Start greater than end : {}", rng);
        }
        let mut res = Vec::new();
        for i in start..=end {
            res.push(OutCol::new(i, name));
        }
        Ok(res)
    }

    /// resolve `ColumnSet` in context of the column names from an input file
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    assert_eq!(s.get_cols_num(), &[0,1,3,4]);
    /// ```
    pub fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.did_lookup = true;
        self.columns = Vec::new();
        let mut no_cols: HashSet<usize> = HashSet::new();

        for s in &self.neg {
            for x in Self::range(fieldnames, s)? {
                no_cols.insert(x.num);
            }
        }

        if self.pos.is_empty() {
            for x in 0..fieldnames.len() {
                if !no_cols.contains(&x) {
                    self.columns.push(OutCol::from_num(x));
                }
            }
        } else {
            for s in &self.pos {
                for x in Self::range(fieldnames, s)? {
                    if !no_cols.contains(&x.num) {
                        self.columns.push(x);
                    }
                }
            }
        }
        Ok(())
    }

    /// Select columns from input line based on `ColumnSet`. Fail if input is too short. """
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    let v = ["Zeroth", "First", "Second", "Third", "Fourth", "Fifth"];
    ///    let mut res = Vec::new();
    ///    s.select(&v, &mut res);
    ///    assert_eq!(res, vec!["Zeroth", "First", "Third", "Fourth"]);
    /// ```
    pub fn select<T: AsRef<str> + Clone>(&self, cols: &[T], result: &mut Vec<T>) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        result.clear();
        for x in &self.columns {
            if x.num < cols.len() {
                result.push(cols[x.num].clone());
            } else {
                return err!(
                    "Line has only {} columns, but column {} was requested.",
                    cols.len(),
                    x.num + 1
                );
            }
        }
        Ok(())
    }

    /// write the appropriate selection from the given columns
    /// trying to write a non-existant column is an error
    pub fn write(&self, w: &mut dyn Write, cols: &[&str], delim: &str) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols[first.num].as_bytes())?;

                for x in iter {
                    w.write_all(delim.as_bytes())?;
                    if x.num < cols.len() {
                        w.write_all(cols[x.num].as_bytes())?;
                    } else {
                        return err!(
                            "Line has only {} columns, but column {} was requested.",
                            cols.len(),
                            x.num + 1
                        );
                    }
                }
            }
        };
        w.write_all(&[b'\n'])?;
        Ok(())
    }

    /// write the appropriate selection from the given columns
    pub fn write2(&self, w: &mut dyn Write, cols: &TextLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(&cols[first.num])?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num))?;
                }
            }
        };
        w.write_all(&[b'\n'])?;
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    pub fn write3(&self, w: &mut dyn Write, cols: &TextLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols.get(first.num))?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num))?;
                }
            }
        };
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    pub fn write3s(&self, w: &mut dyn Write, cols: &StringLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols.get(first.num).as_bytes())?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num).as_bytes())?;
                }
            }
        };
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    /// trying to write a non-existant column writes the provided default value
    pub fn write_sloppy(&self, cols: &[&str], rest: &str, w: &mut dyn Write) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        for x in &self.columns {
            if x.num < cols.len() {
                w.write_all(cols[x.num].as_bytes())?;
            } else {
                w.write_all(rest.as_bytes())?;
            }
        }
        Ok(())
    }

    /// Select columns from input line based on `ColumnSet`, fill in default if line is too short """
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    let v = ["Zeroth", "First", "Second", "Third"];
    ///    let mut res = Vec::new();
    ///    s.select_sloppy(&v, &"extra", &mut res);
    ///    assert_eq!(res, vec!["Zeroth", "First", "Third", "extra"]);
    /// ```
    pub fn select_sloppy<T: AsRef<str> + Clone>(
        &self,
        cols: &[T],
        restval: &T,
        result: &mut Vec<T>,
    ) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        result.clear();
        for x in &self.columns {
            if x.num < cols.len() {
                result.push(cols[x.num].clone());
            } else {
                result.push(restval.clone());
            }
        }
        Ok(())
    }

    /// return owned columns by const reference
    pub fn get_cols(&self) -> &Vec<OutCol> {
        &self.columns
    }

    /// steal owned columns by value
    pub fn get_cols_full(self) -> Vec<OutCol> {
        self.columns
    }

    /// get owned column numbers
    pub fn get_cols_num(&self) -> Vec<usize> {
        let mut v = Vec::with_capacity(self.columns.len());
        for x in &self.columns {
            v.push(x.num);
        }
        v
    }

    /// Shorthand to look up some columns
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    assert_eq!(ColumnSet::lookup_cols("~2-3", &header).unwrap(), &[0,3,4]);
    /// ```
    pub fn lookup_cols(spec: &str, names: &[&str]) -> Result<Vec<usize>> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        Ok(s.get_cols_num())
    }

    /// Shorthand to look up some columns, with names
    pub fn lookup_cols_full(spec: &str, names: &[&str]) -> Result<Vec<OutCol>> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        Ok(s.get_cols_full())
    }

    /// Shorthand to look up a single column
    /// To look up a single named column, `lookup_col` is also available
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    assert_eq!(ColumnSet::lookup1("three", &header).unwrap(), 3);
    /// ```
    pub fn lookup1(spec: &str, names: &[&str]) -> Result<usize> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        if s.get_cols().len() != 1 {
            return err!(
                "Spec {} resolves to {} columns, rather than a single column",
                spec,
                s.get_cols().len()
            );
        }
        Ok(s.get_cols_num()[0])
    }
}

/// Write the columns with a custom delimiter
pub struct ColumnClump<'a> {
    cols: Box<dyn ColumnFun + 'a>,
    name: String,
    delim: u8,
}
impl fmt::Debug for ColumnClump<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ColumnClump")
    }
}

impl<'a> ColumnClump<'a> {
    /// new ColumnClump from parts
    pub fn new(cols: Box<dyn ColumnFun + 'a>, name: &str, delim: u8) -> Self {
        Self {
            cols,
            name: name.to_string(),
            delim,
        }
    }
    /// new ColumnClump from spec : DelimOutcol:Columns
    /// e.g. ,group:1-3
    pub fn from_spec(orig_spec: &str) -> Result<Self> {
        let mut spec = orig_spec;
        if spec.is_empty() {
            return err!("Can't construct a group from an empty string");
        }
        let delim = spec.take_first();
        if delim.len_utf8() != 1 {
            return err!("Delimiter must be a plain ascii character : {}", orig_spec);
        }
        let parts = spec.split_once(':');
        if parts.is_none() {
            return err!(
                "No colon found. Group format is DelimOutname:Columns : {}",
                orig_spec
            );
        }
        let parts = parts.unwrap();
        let mut g = ColumnSet::new();
        g.add_yes(parts.1);
        let cols = Box::new(ReaderColumns::new(g));
        Ok(Self {
            cols,
            name: parts.0.to_string(),
            delim: delim as u8,
        })
    }
}

impl<'a> ColumnFun for ColumnClump<'a> {
    fn write(&self, w: &mut dyn Write, line: &TextLine, _delim: u8) -> Result<()> {
        self.cols.write(w, line, self.delim)?;
        Ok(())
    }

    fn write_names(&self, w: &mut dyn Write, _head: &StringLine, _delim: u8) -> Result<()> {
        w.write_all(self.name.as_bytes())?;
        Ok(())
    }
    fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.cols.lookup(fieldnames)
    }
}

/// Selection of columns from a Reader
#[derive(Debug)]
pub struct ReaderColumns {
    columns: ColumnSet,
}

impl ReaderColumns {
    /// new ReaderColumns
    pub fn new(columns: ColumnSet) -> Self {
        Self { columns }
    }
}

/// Write column name : col.name if non empty, else head[col.num]
pub fn write_colname(w: &mut dyn Write, col: &OutCol, head: &StringLine) -> Result<()> {
    if col.name.is_empty() {
        w.write_all(head.get(col.num).as_bytes())?;
    } else {
        w.write_all(col.name.as_bytes())?;
    }
    Ok(())
}

impl ColumnFun for ReaderColumns {
    fn write(&self, w: &mut dyn Write, line: &TextLine, delim: u8) -> Result<()> {
        self.columns.write3(w, line, delim)?;
        Ok(())
    }

    fn write_names(&self, w: &mut dyn Write, head: &StringLine, delim: u8) -> Result<()> {
        let mut iter = self.columns.get_cols().iter();
        match iter.next() {
            None => {}
            Some(first) => {
                write_colname(w, first, head)?;
                for x in iter {
                    w.write_all(&[delim])?;
                    write_colname(w, x, head)?;
                }
            }
        }
        //        self.columns.write3s(w, head, delim)?;
        Ok(())
    }
    fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.columns.lookup(fieldnames)
    }
}

/// A collection of ColumnFun writers
pub struct Writer<'a> {
    v: Vec<Box<dyn ColumnFun + 'a>>,
    delim: u8,
}
impl fmt::Debug for Writer<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Writer")
    }
}

impl<'a> Writer<'a> {
    /// new Writer
    pub fn new(delim: u8) -> Self {
        Self {
            v: Vec::new(),
            delim,
        }
    }
    /// is it empty
    pub fn is_empty(&self) -> bool {
        self.v.is_empty()
    }
    /// resolve column names
    pub fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        for x in self.v.iter_mut() {
            x.lookup(fieldnames)?
        }
        Ok(())
    }
    /// Add a new writer
    pub fn push(&mut self, x: Box<dyn ColumnFun + 'a>) {
        self.v.push(x);
    }
    /// Write the column names
    pub fn write_names(&self, w: &mut dyn Write, head: &StringLine) -> Result<()> {
        w.write_all(b" CDX")?;
        for x in self.v.iter() {
            w.write_all(&[self.delim])?;
            x.write_names(w, head, self.delim)?;
        }
        w.write_all(&[b'\n'])?;
        Ok(())
    }
    /// Write the column values
    pub fn write(&self, w: &mut dyn Write, line: &TextLine) -> Result<()> {
        let mut iter = self.v.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                first.write(w, line, self.delim)?;
                for x in iter {
                    w.write_all(&[self.delim])?;
                    x.write(w, line, self.delim)?;
                }
            }
        };
        w.write_all(&[b'\n'])?;
        Ok(())
    }
}

impl<'a> Default for Writer<'a> {
    fn default() -> Self {
        Self::new(b'\t')
    }
}

/// a column, by name or number
#[derive(Debug, Clone)]
pub struct NamedCol {
    /// the column name. Empty if using column by number
    pub name: String,
    /// the columnn number, either as originally set or after lookup
    pub num: usize,
    /// if non-zero, input was "+2" so num should be calculated as (num_cols - from_end)
    pub from_end: usize,
}

impl NamedCol {
    /// new named column
    pub fn new() -> Self {
        Self {
            name: String::new(),
            num: 0,
            from_end: 0,
        }
    }
    /// Resolve the column name
    pub fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        if !self.name.is_empty() {
            self.num = ColumnSet::lookup_col(fieldnames, &self.name)?
        } else if self.from_end > 0 {
            if self.from_end > fieldnames.len() {
                return err!(
                    "Requested column +{}, but there are only {} columns",
                    self.from_end,
                    fieldnames.len()
                );
            }
            self.num = fieldnames.len() - self.from_end
        }
        Ok(())
    }

resolve a single name or number into a column number

Examples
   use cdx::column::ColumnSet;
   assert_eq!(ColumnSet::single(&["zero", "one", "two"], "+1").unwrap(), 2);
Examples found in repository
src/column.rs (line 497)
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
fn range(fieldnames: &[&str], rng: &str) -> Result<Vec<OutCol>> {
        if rng.is_empty() {
            return err!("Empty Range {}", rng);
        }
        let (name, range) = match rng.split_once(':') {
            None => ("", rng),
            Some(x) => x,
        };

        let ch = range.chars().next().unwrap();
        if ch == '<' || ch == '>' || ch == '=' {
            return Ok(Self::to_outcols(
                &Self::text_range(fieldnames, range)?,
                name,
            ));
        }
        if range.contains('*') || rng.contains('?') {
            return Ok(Self::to_outcols(
                &Self::glob_range(fieldnames, range)?,
                name,
            ));
        }

        let mut parts: Vec<&str> = range.split('-').collect();
        if parts.len() > 2 {
            return err!("Malformed Range {}", rng);
        }
        if parts[0].is_empty() {
            parts[0] = "1";
        }

        let start: usize;
        let end: usize;
        if parts.len() == 1 {
            start = Self::single(fieldnames, parts[0])?;
            end = start;
        } else {
            if parts[1].is_empty() {
                parts[1] = "+1";
            }
            start = Self::single(fieldnames, parts[0])?;
            end = Self::single(fieldnames, parts[1])?;
        }

        if start > end {
            // throw new CdxException("start > end, i.e. {" + parts.get(0) + " > " + parts.get(1));
            return err!("Start greater than end : {}", rng);
        }
        let mut res = Vec::new();
        for i in start..=end {
            res.push(OutCol::new(i, name));
        }
        Ok(res)
    }

turn comma delimited list of ranges into list of possibly named column numbers

resolve ColumnSet in context of the column names from an input file

Examples
   use cdx::column::ColumnSet;
   let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
   let mut s = ColumnSet::new();
   s.add_no("two");
   s.lookup(&header);
   assert_eq!(s.get_cols_num(), &[0,1,3,4]);
Examples found in repository
src/column.rs (line 148)
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
pub fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.cols.lookup(fieldnames)
    }
}

/// A per-column value
#[derive(Debug, Clone, Default)]
pub struct ScopedValues {
    default: String,
    data: Vec<ScopedValue>,

    has_value: Vec<bool>,
    strings: Vec<String>,
    ints: Vec<i64>,
    floats: Vec<f64>,
}

impl ScopedValues {
    /// new
    pub fn new() -> Self {
        ScopedValues::default()
    }
    /// value for column not otherwise assigned a value
    pub fn set_default(&mut self, d: &str) {
        self.default = d.to_string();
    }
    /// resolve named columns
    pub fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.has_value.clear();
        self.has_value.resize(fieldnames.len(), false);
        self.strings.clear();
        self.strings.resize(fieldnames.len(), self.default.clone());
        for x in &mut self.data {
            x.lookup(fieldnames)?;
            for i in 0..x.cols.columns.len() {
                self.strings[i] = x.value.clone();
                self.has_value[i] = true;
            }
        }
        Ok(())
    }
    /// do the work so that get_int() will work properly
    pub fn make_ints(&mut self) -> Result<()> {
        self.ints.clear();
        for i in 0..self.strings.len() {
            self.ints[i] = self.get(i).parse::<i64>()?;
        }
        Ok(())
    }
    /// do the work so that get_int() will work properly
    pub fn make_floats(&mut self) -> Result<()> {
        self.floats.clear();
        for i in 0..self.strings.len() {
            self.floats[i] = self.get(i).parse::<f64>()?;
        }
        Ok(())
    }

    /// add one ScopedValue
    pub fn add(&mut self, spec: &str, del: char) {
        self.data.push(ScopedValue::new(spec, del));
    }
    /// add one ScopedValue
    pub fn add2(&mut self, value: &str, cols: &str) {
        self.data.push(ScopedValue::new2(value, cols));
    }
    /// get appropriate value for the column
    pub fn get(&self, col: usize) -> &str {
        if col < self.strings.len() {
            &self.strings[col]
        } else {
            self.strings.last().unwrap()
        }
    }
    /// get appropriate int value for the column
    pub fn get_int(&self, col: usize) -> i64 {
        if col < self.ints.len() {
            self.ints[col]
        } else {
            *self.ints.last().unwrap()
        }
    }
    /// get appropriate int value for the column
    pub fn get_float(&self, col: usize) -> f64 {
        if col < self.floats.len() {
            self.floats[col]
        } else {
            *self.floats.last().unwrap()
        }
    }
    /// has this column been assigned a value?
    pub fn has_value(&self, col: usize) -> bool {
        if col < self.has_value.len() {
            self.has_value[col]
        } else {
            false
        }
    }
    /// Have any column been assigned values?
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
}

/// Write some output
pub trait ColumnFun {
    /// write the column names (called once)
    fn write_names(&self, w: &mut dyn Write, head: &StringLine, delim: u8) -> Result<()>;
    /// write the column values (called many times)
    fn write(&self, w: &mut dyn Write, line: &TextLine, delim: u8) -> Result<()>;
    /// resolve any named columns
    fn lookup(&mut self, fieldnames: &[&str]) -> Result<()>;
}

impl fmt::Debug for dyn ColumnFun {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "ColumnFun")
    }
}

impl ColumnSet {
    /// Create an empty column set, which selects all columns.
    pub fn new() -> Self {
        ColumnSet::default()
    }
    /// is empty?
    pub fn is_empty(&self) -> bool {
        self.pos.is_empty() && self.neg.is_empty()
    }

    /// Create an column set from a spec, e.g. "1-3"
    pub fn from_spec(spec: &str) -> Self {
        let mut s = ColumnSet::default();
        s.add_yes(spec);
        s
    }

    /// Add some columns to be selected
    pub fn add_yes(&mut self, spec: &str) {
        self.add(spec, false);
    }

    /// Add some columns to be rejected.
    pub fn add_no(&mut self, spec: &str) {
        self.add(spec, true);
    }

    /// Add a spec, "yes" or "no" based on a flag.
    pub fn add(&mut self, spec: &str, negate: bool) {
        for s in spec.split(',') {
            if let Some(stripped) = s.strip_prefix('~') {
                let st = stripped.to_string();
                if negate {
                    self.pos.push(st);
                } else {
                    self.neg.push(st);
                }
            } else {
                let st = s.to_string();
                if negate {
                    self.neg.push(st);
                } else {
                    self.pos.push(st);
                }
            }
        }
    }

    /// Turn column name into column number
    /// To also handle numbers and ranges, use `lookup1`
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    assert_eq!(ColumnSet::lookup_col(&["zero", "one", "two"], "one").unwrap(), 1);
    /// ```
    pub fn lookup_col(fieldnames: &[&str], colname: &str) -> Result<usize> {
        for f in fieldnames.iter().enumerate() {
            if f.1 == &colname {
                return Ok(f.0);
            }
        }
        err!("{} not found", colname)
    }
    /*
        /// turn a u8 column name into a column number
        pub fn lookup_col2(fieldnames: &[&str], colname: &[u8]) -> Result<usize> {
        let name = str::from_utf8_lossy(colname);
            for f in fieldnames.iter().enumerate() {
                if *f.1 == name {
                    return Ok(f.0);
                }
            }
            err!("{:?} not found", &colname)
        }
    */
    /// resolve a single name or number into a column number
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    assert_eq!(ColumnSet::single(&["zero", "one", "two"], "+1").unwrap(), 2);
    /// ```
    pub fn single(fieldnames: &[&str], colname: &str) -> Result<usize> {
        if let Some(stripped) = colname.strip_prefix('+') {
            let n = str_to_u_whole(stripped.as_bytes())? as usize;
            let len = fieldnames.len();
            if n > len {
                err!("Column {} out of bounds", colname)
            } else {
                Ok(len - n)
            }
        } else {
            let ch = colname.chars().next().unwrap();
            if ch.is_ascii_digit() {
                let n = str_to_u_whole(colname.as_bytes())? as usize;
                if n < 1 {
                    err!("Column {} out of bounds", colname)
                } else {
                    Ok(n - 1)
                }
            } else {
                Self::lookup_col(fieldnames, colname)
            }
        }
    }

    /// determine if two strings match, given an operator
    fn do_compare(left: &str, right: &str, operator: &str) -> Result<bool> {
        let val = left.cmp(right);
        if operator == "<" {
            return Ok(val == Ordering::Less);
        }
        if operator == "<=" {
            return Ok(val != Ordering::Greater);
        }
        if operator == ">" {
            return Ok(val == Ordering::Greater);
        }
        if operator == ">=" {
            return Ok(val != Ordering::Less);
        }
        err!(operator.to_string())
    }

    /// determine if a name is within a range
    fn do_compare2(name: &str, key1: &str, op1: &str, key2: &str, op2: &str) -> Result<bool> {
        Ok(Self::do_compare(name, key1, op1)? && Self::do_compare(name, key2, op2)?)
    }

    /// Return all the fields that match the glob
    fn glob_range(fieldnames: &[&str], rng: &str) -> Result<Vec<usize>> {
        let mut ret = Vec::new();
        for f in fieldnames.iter().enumerate() {
            if f.1.glob(rng, Case::Sens) {
                // allow case insensitive?
                ret.push(f.0);
            }
        }
        Ok(ret)
    }
    /// Return all the field numbers that match a textual spec like <foo or <foo>bar """
    fn text_range(fieldnames: &[&str], rng: &str) -> Result<Vec<usize>> {
        let mut ret = Vec::new();
        lazy_static! {
            static ref RE1: Regex = Regex::new("^([<>]=?)([^<>]+)$").unwrap();
            static ref RE2: Regex = Regex::new("^([<>]=?)([^<>]+)([<>]=?)([^<>]+)$").unwrap();
        }

        if let Some(caps) = RE1.captures(rng) {
            for f in fieldnames.iter().enumerate() {
                if Self::do_compare(
                    f.1,
                    caps.get(2).unwrap().as_str(),
                    caps.get(1).unwrap().as_str(),
                )? {
                    ret.push(f.0);
                }
            }
            return Ok(ret);
        }

        if let Some(caps) = RE2.captures(rng) {
            for f in fieldnames.iter().enumerate() {
                if Self::do_compare2(
                    f.1,
                    caps.get(2).unwrap().as_str(),
                    caps.get(1).unwrap().as_str(),
                    caps.get(4).unwrap().as_str(),
                    caps.get(3).unwrap().as_str(),
                )? {
                    ret.push(f.0);
                }
            }
            return Ok(ret);
        }

        err!("Malformed Range {}", rng)
    }

    fn to_outcols(data: &[usize], name: &str) -> Vec<OutCol> {
        let mut ret = Vec::with_capacity(data.len());
        for x in data {
            ret.push(OutCol::new(*x, name));
        }
        ret
    }

    /// turn comma delimited list of ranges into list of possibly named column numbers
    pub fn ranges(fieldnames: &[&str], rng: &str) -> Result<Vec<OutCol>> {
        let mut c = ColumnSet::new();
        c.add_yes(rng);
        c.lookup(fieldnames)?;
        Ok(c.get_cols_full())
    }
    /// turn range into list of column numbers
    fn range(fieldnames: &[&str], rng: &str) -> Result<Vec<OutCol>> {
        if rng.is_empty() {
            return err!("Empty Range {}", rng);
        }
        let (name, range) = match rng.split_once(':') {
            None => ("", rng),
            Some(x) => x,
        };

        let ch = range.chars().next().unwrap();
        if ch == '<' || ch == '>' || ch == '=' {
            return Ok(Self::to_outcols(
                &Self::text_range(fieldnames, range)?,
                name,
            ));
        }
        if range.contains('*') || rng.contains('?') {
            return Ok(Self::to_outcols(
                &Self::glob_range(fieldnames, range)?,
                name,
            ));
        }

        let mut parts: Vec<&str> = range.split('-').collect();
        if parts.len() > 2 {
            return err!("Malformed Range {}", rng);
        }
        if parts[0].is_empty() {
            parts[0] = "1";
        }

        let start: usize;
        let end: usize;
        if parts.len() == 1 {
            start = Self::single(fieldnames, parts[0])?;
            end = start;
        } else {
            if parts[1].is_empty() {
                parts[1] = "+1";
            }
            start = Self::single(fieldnames, parts[0])?;
            end = Self::single(fieldnames, parts[1])?;
        }

        if start > end {
            // throw new CdxException("start > end, i.e. {" + parts.get(0) + " > " + parts.get(1));
            return err!("Start greater than end : {}", rng);
        }
        let mut res = Vec::new();
        for i in start..=end {
            res.push(OutCol::new(i, name));
        }
        Ok(res)
    }

    /// resolve `ColumnSet` in context of the column names from an input file
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    assert_eq!(s.get_cols_num(), &[0,1,3,4]);
    /// ```
    pub fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.did_lookup = true;
        self.columns = Vec::new();
        let mut no_cols: HashSet<usize> = HashSet::new();

        for s in &self.neg {
            for x in Self::range(fieldnames, s)? {
                no_cols.insert(x.num);
            }
        }

        if self.pos.is_empty() {
            for x in 0..fieldnames.len() {
                if !no_cols.contains(&x) {
                    self.columns.push(OutCol::from_num(x));
                }
            }
        } else {
            for s in &self.pos {
                for x in Self::range(fieldnames, s)? {
                    if !no_cols.contains(&x.num) {
                        self.columns.push(x);
                    }
                }
            }
        }
        Ok(())
    }

    /// Select columns from input line based on `ColumnSet`. Fail if input is too short. """
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    let v = ["Zeroth", "First", "Second", "Third", "Fourth", "Fifth"];
    ///    let mut res = Vec::new();
    ///    s.select(&v, &mut res);
    ///    assert_eq!(res, vec!["Zeroth", "First", "Third", "Fourth"]);
    /// ```
    pub fn select<T: AsRef<str> + Clone>(&self, cols: &[T], result: &mut Vec<T>) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        result.clear();
        for x in &self.columns {
            if x.num < cols.len() {
                result.push(cols[x.num].clone());
            } else {
                return err!(
                    "Line has only {} columns, but column {} was requested.",
                    cols.len(),
                    x.num + 1
                );
            }
        }
        Ok(())
    }

    /// write the appropriate selection from the given columns
    /// trying to write a non-existant column is an error
    pub fn write(&self, w: &mut dyn Write, cols: &[&str], delim: &str) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols[first.num].as_bytes())?;

                for x in iter {
                    w.write_all(delim.as_bytes())?;
                    if x.num < cols.len() {
                        w.write_all(cols[x.num].as_bytes())?;
                    } else {
                        return err!(
                            "Line has only {} columns, but column {} was requested.",
                            cols.len(),
                            x.num + 1
                        );
                    }
                }
            }
        };
        w.write_all(&[b'\n'])?;
        Ok(())
    }

    /// write the appropriate selection from the given columns
    pub fn write2(&self, w: &mut dyn Write, cols: &TextLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(&cols[first.num])?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num))?;
                }
            }
        };
        w.write_all(&[b'\n'])?;
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    pub fn write3(&self, w: &mut dyn Write, cols: &TextLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols.get(first.num))?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num))?;
                }
            }
        };
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    pub fn write3s(&self, w: &mut dyn Write, cols: &StringLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols.get(first.num).as_bytes())?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num).as_bytes())?;
                }
            }
        };
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    /// trying to write a non-existant column writes the provided default value
    pub fn write_sloppy(&self, cols: &[&str], rest: &str, w: &mut dyn Write) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        for x in &self.columns {
            if x.num < cols.len() {
                w.write_all(cols[x.num].as_bytes())?;
            } else {
                w.write_all(rest.as_bytes())?;
            }
        }
        Ok(())
    }

    /// Select columns from input line based on `ColumnSet`, fill in default if line is too short """
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    let v = ["Zeroth", "First", "Second", "Third"];
    ///    let mut res = Vec::new();
    ///    s.select_sloppy(&v, &"extra", &mut res);
    ///    assert_eq!(res, vec!["Zeroth", "First", "Third", "extra"]);
    /// ```
    pub fn select_sloppy<T: AsRef<str> + Clone>(
        &self,
        cols: &[T],
        restval: &T,
        result: &mut Vec<T>,
    ) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        result.clear();
        for x in &self.columns {
            if x.num < cols.len() {
                result.push(cols[x.num].clone());
            } else {
                result.push(restval.clone());
            }
        }
        Ok(())
    }

    /// return owned columns by const reference
    pub fn get_cols(&self) -> &Vec<OutCol> {
        &self.columns
    }

    /// steal owned columns by value
    pub fn get_cols_full(self) -> Vec<OutCol> {
        self.columns
    }

    /// get owned column numbers
    pub fn get_cols_num(&self) -> Vec<usize> {
        let mut v = Vec::with_capacity(self.columns.len());
        for x in &self.columns {
            v.push(x.num);
        }
        v
    }

    /// Shorthand to look up some columns
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    assert_eq!(ColumnSet::lookup_cols("~2-3", &header).unwrap(), &[0,3,4]);
    /// ```
    pub fn lookup_cols(spec: &str, names: &[&str]) -> Result<Vec<usize>> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        Ok(s.get_cols_num())
    }

    /// Shorthand to look up some columns, with names
    pub fn lookup_cols_full(spec: &str, names: &[&str]) -> Result<Vec<OutCol>> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        Ok(s.get_cols_full())
    }

    /// Shorthand to look up a single column
    /// To look up a single named column, `lookup_col` is also available
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    assert_eq!(ColumnSet::lookup1("three", &header).unwrap(), 3);
    /// ```
    pub fn lookup1(spec: &str, names: &[&str]) -> Result<usize> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        if s.get_cols().len() != 1 {
            return err!(
                "Spec {} resolves to {} columns, rather than a single column",
                spec,
                s.get_cols().len()
            );
        }
        Ok(s.get_cols_num()[0])
    }
}

/// Write the columns with a custom delimiter
pub struct ColumnClump<'a> {
    cols: Box<dyn ColumnFun + 'a>,
    name: String,
    delim: u8,
}
impl fmt::Debug for ColumnClump<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ColumnClump")
    }
}

impl<'a> ColumnClump<'a> {
    /// new ColumnClump from parts
    pub fn new(cols: Box<dyn ColumnFun + 'a>, name: &str, delim: u8) -> Self {
        Self {
            cols,
            name: name.to_string(),
            delim,
        }
    }
    /// new ColumnClump from spec : DelimOutcol:Columns
    /// e.g. ,group:1-3
    pub fn from_spec(orig_spec: &str) -> Result<Self> {
        let mut spec = orig_spec;
        if spec.is_empty() {
            return err!("Can't construct a group from an empty string");
        }
        let delim = spec.take_first();
        if delim.len_utf8() != 1 {
            return err!("Delimiter must be a plain ascii character : {}", orig_spec);
        }
        let parts = spec.split_once(':');
        if parts.is_none() {
            return err!(
                "No colon found. Group format is DelimOutname:Columns : {}",
                orig_spec
            );
        }
        let parts = parts.unwrap();
        let mut g = ColumnSet::new();
        g.add_yes(parts.1);
        let cols = Box::new(ReaderColumns::new(g));
        Ok(Self {
            cols,
            name: parts.0.to_string(),
            delim: delim as u8,
        })
    }
}

impl<'a> ColumnFun for ColumnClump<'a> {
    fn write(&self, w: &mut dyn Write, line: &TextLine, _delim: u8) -> Result<()> {
        self.cols.write(w, line, self.delim)?;
        Ok(())
    }

    fn write_names(&self, w: &mut dyn Write, _head: &StringLine, _delim: u8) -> Result<()> {
        w.write_all(self.name.as_bytes())?;
        Ok(())
    }
    fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.cols.lookup(fieldnames)
    }
}

/// Selection of columns from a Reader
#[derive(Debug)]
pub struct ReaderColumns {
    columns: ColumnSet,
}

impl ReaderColumns {
    /// new ReaderColumns
    pub fn new(columns: ColumnSet) -> Self {
        Self { columns }
    }
}

/// Write column name : col.name if non empty, else head[col.num]
pub fn write_colname(w: &mut dyn Write, col: &OutCol, head: &StringLine) -> Result<()> {
    if col.name.is_empty() {
        w.write_all(head.get(col.num).as_bytes())?;
    } else {
        w.write_all(col.name.as_bytes())?;
    }
    Ok(())
}

impl ColumnFun for ReaderColumns {
    fn write(&self, w: &mut dyn Write, line: &TextLine, delim: u8) -> Result<()> {
        self.columns.write3(w, line, delim)?;
        Ok(())
    }

    fn write_names(&self, w: &mut dyn Write, head: &StringLine, delim: u8) -> Result<()> {
        let mut iter = self.columns.get_cols().iter();
        match iter.next() {
            None => {}
            Some(first) => {
                write_colname(w, first, head)?;
                for x in iter {
                    w.write_all(&[delim])?;
                    write_colname(w, x, head)?;
                }
            }
        }
        //        self.columns.write3s(w, head, delim)?;
        Ok(())
    }
    fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.columns.lookup(fieldnames)
    }
More examples
src/join.rs (line 256)
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
pub fn quick_join(&mut self) -> Result<()> {
        if self.infiles.len() != 2 {
            return err!(
                "{} files specified, exactly two required",
                self.infiles.len()
            );
        }

        let mut f1 = Reader::new();
        let mut f2 = Reader::new();
        f1.open(&self.infiles[0])?;
        f2.open(&self.infiles[1])?;
        if f1.is_empty() && f2.is_empty() {
            return Ok(());
        }

        let mut comp = if self.keys.is_empty() {
            make_comp("1")?
        } else if self.keys.len() == 1 {
            make_comp(&self.keys[0])?
        } else {
            make_comp(&self.keys[1])?
            /*
                    let mut cc = CompareList::new();
                    for x in &self.keys {
                    cc.push(Box::new(make_comp(x)?));
                    }
                    cc
            */
        };

        let mut nomatch: Vec<Option<Outfile>> = vec![None, None];
        for x in &self.unmatch_out {
            if x.file_num == 1 {
                if nomatch[0].is_none() {
                    let mut w = get_writer(&x.file_name)?;
                    f1.write_header(&mut w)?;
                    nomatch[0] = Some(w);
                } else {
                    return err!("Multiple uses of --also for file 1");
                }
            } else if x.file_num == 2 {
                if nomatch[1].is_none() {
                    let mut w = get_writer(&x.file_name)?;
                    f2.write_header(&mut w)?;
                    nomatch[1] = Some(w);
                } else {
                    return err!("Multiple uses of --also for file 2");
                }
            } else {
                return err!(
                    "Join had 2 input files, but requested non matching lines from file {}",
                    x.file_num
                );
            }
        }

        let mut w = get_writer(&self.match_out)?;

        comp.lookup_left(&f1.names())?;
        comp.lookup_right(&f2.names())?;

        let mut out_cols: Vec<OneOutCol> = Vec::new();
        if self.out_cols.is_empty() {
            for x in 0..f1.names().len() {
                out_cols.push(OneOutCol::new_plain(0, x));
            }
            for x in 0..f2.names().len() {
                if x != comp.mode.right_col.num {
                    out_cols.push(OneOutCol::new_plain(1, x));
                }
            }
        } else {
            for x in &mut self.out_cols {
                if x.file == 0 {
                    x.cols.lookup(&f1.names())?;
                } else if x.file == 1 {
                    x.cols.lookup(&f2.names())?;
                } else {
                    return err!(
                        "Two input files, but file {} referred to as an output column",
                        x.file
                    );
                }
                for y in x.cols.get_cols() {
                    out_cols.push(OneOutCol::new(x.file, y));
                }
            }
        }
        if out_cols.is_empty() {
            return err!("No output columns specified");
        }
        if f1.cont.has_header {
            w.write_all(b" CDX")?;
            for x in &out_cols {
                w.write_all(&[self.out_delim])?;
                x.write_head(&mut w, &f1, &f2)?;
            }
            w.write_all(&[b'\n'])?;
        }

        loop {
            if f1.is_done() || f2.is_done() {
                break;
            }
            match comp.comp_cols(f1.curr(), f2.curr()) {
                Ordering::Equal => {
                    out_cols[0].write(&mut w, &f1, &f2)?;
                    for x in &out_cols[1..] {
                        w.write_all(&[self.out_delim])?;
                        x.write(&mut w, &f1, &f2)?;
                    }
                    w.write_all(&[b'\n'])?;

                    f1.getline()?;
                    f2.getline()?;
                }
                Ordering::Less => {
                    if let Some(x) = &mut nomatch[0] {
                        f1.write(x)?;
                    }
                    f1.getline()?;
                }
                Ordering::Greater => {
                    if let Some(x) = &mut nomatch[1] {
                        f2.write(x)?;
                    }
                    f2.getline()?;
                }
            }
        }
        while !f1.is_done() {
            if let Some(x) = &mut nomatch[0] {
                f1.write(x)?;
            }
            f1.getline()?;
        }
        while !f2.is_done() {
            if let Some(x) = &mut nomatch[1] {
                f2.write(x)?;
            }
            f2.getline()?;
        }
        // drain f1 or f2 as needed
        Ok(())
    }

Select columns from input line based on ColumnSet. Fail if input is too short. “”“

Examples
   use cdx::column::ColumnSet;
   let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
   let mut s = ColumnSet::new();
   s.add_no("two");
   s.lookup(&header);
   let v = ["Zeroth", "First", "Second", "Third", "Fourth", "Fifth"];
   let mut res = Vec::new();
   s.select(&v, &mut res);
   assert_eq!(res, vec!["Zeroth", "First", "Third", "Fourth"]);

write the appropriate selection from the given columns trying to write a non-existant column is an error

write the appropriate selection from the given columns

write the appropriate selection from the given columns, but no trailing newline

Examples found in repository
src/column.rs (line 886)
885
886
887
888
fn write(&self, w: &mut dyn Write, line: &TextLine, delim: u8) -> Result<()> {
        self.columns.write3(w, line, delim)?;
        Ok(())
    }

write the appropriate selection from the given columns, but no trailing newline

write the appropriate selection from the given columns, but no trailing newline trying to write a non-existant column writes the provided default value

Select columns from input line based on ColumnSet, fill in default if line is too short “”“

Examples
   use cdx::column::ColumnSet;
   let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
   let mut s = ColumnSet::new();
   s.add_no("two");
   s.lookup(&header);
   let v = ["Zeroth", "First", "Second", "Third"];
   let mut res = Vec::new();
   s.select_sloppy(&v, &"extra", &mut res);
   assert_eq!(res, vec!["Zeroth", "First", "Third", "extra"]);

return owned columns by const reference

Examples found in repository
src/column.rs (line 784)
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
pub fn lookup1(spec: &str, names: &[&str]) -> Result<usize> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        if s.get_cols().len() != 1 {
            return err!(
                "Spec {} resolves to {} columns, rather than a single column",
                spec,
                s.get_cols().len()
            );
        }
        Ok(s.get_cols_num()[0])
    }
}

/// Write the columns with a custom delimiter
pub struct ColumnClump<'a> {
    cols: Box<dyn ColumnFun + 'a>,
    name: String,
    delim: u8,
}
impl fmt::Debug for ColumnClump<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ColumnClump")
    }
}

impl<'a> ColumnClump<'a> {
    /// new ColumnClump from parts
    pub fn new(cols: Box<dyn ColumnFun + 'a>, name: &str, delim: u8) -> Self {
        Self {
            cols,
            name: name.to_string(),
            delim,
        }
    }
    /// new ColumnClump from spec : DelimOutcol:Columns
    /// e.g. ,group:1-3
    pub fn from_spec(orig_spec: &str) -> Result<Self> {
        let mut spec = orig_spec;
        if spec.is_empty() {
            return err!("Can't construct a group from an empty string");
        }
        let delim = spec.take_first();
        if delim.len_utf8() != 1 {
            return err!("Delimiter must be a plain ascii character : {}", orig_spec);
        }
        let parts = spec.split_once(':');
        if parts.is_none() {
            return err!(
                "No colon found. Group format is DelimOutname:Columns : {}",
                orig_spec
            );
        }
        let parts = parts.unwrap();
        let mut g = ColumnSet::new();
        g.add_yes(parts.1);
        let cols = Box::new(ReaderColumns::new(g));
        Ok(Self {
            cols,
            name: parts.0.to_string(),
            delim: delim as u8,
        })
    }
}

impl<'a> ColumnFun for ColumnClump<'a> {
    fn write(&self, w: &mut dyn Write, line: &TextLine, _delim: u8) -> Result<()> {
        self.cols.write(w, line, self.delim)?;
        Ok(())
    }

    fn write_names(&self, w: &mut dyn Write, _head: &StringLine, _delim: u8) -> Result<()> {
        w.write_all(self.name.as_bytes())?;
        Ok(())
    }
    fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.cols.lookup(fieldnames)
    }
}

/// Selection of columns from a Reader
#[derive(Debug)]
pub struct ReaderColumns {
    columns: ColumnSet,
}

impl ReaderColumns {
    /// new ReaderColumns
    pub fn new(columns: ColumnSet) -> Self {
        Self { columns }
    }
}

/// Write column name : col.name if non empty, else head[col.num]
pub fn write_colname(w: &mut dyn Write, col: &OutCol, head: &StringLine) -> Result<()> {
    if col.name.is_empty() {
        w.write_all(head.get(col.num).as_bytes())?;
    } else {
        w.write_all(col.name.as_bytes())?;
    }
    Ok(())
}

impl ColumnFun for ReaderColumns {
    fn write(&self, w: &mut dyn Write, line: &TextLine, delim: u8) -> Result<()> {
        self.columns.write3(w, line, delim)?;
        Ok(())
    }

    fn write_names(&self, w: &mut dyn Write, head: &StringLine, delim: u8) -> Result<()> {
        let mut iter = self.columns.get_cols().iter();
        match iter.next() {
            None => {}
            Some(first) => {
                write_colname(w, first, head)?;
                for x in iter {
                    w.write_all(&[delim])?;
                    write_colname(w, x, head)?;
                }
            }
        }
        //        self.columns.write3s(w, head, delim)?;
        Ok(())
    }
More examples
src/join.rs (line 265)
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
pub fn quick_join(&mut self) -> Result<()> {
        if self.infiles.len() != 2 {
            return err!(
                "{} files specified, exactly two required",
                self.infiles.len()
            );
        }

        let mut f1 = Reader::new();
        let mut f2 = Reader::new();
        f1.open(&self.infiles[0])?;
        f2.open(&self.infiles[1])?;
        if f1.is_empty() && f2.is_empty() {
            return Ok(());
        }

        let mut comp = if self.keys.is_empty() {
            make_comp("1")?
        } else if self.keys.len() == 1 {
            make_comp(&self.keys[0])?
        } else {
            make_comp(&self.keys[1])?
            /*
                    let mut cc = CompareList::new();
                    for x in &self.keys {
                    cc.push(Box::new(make_comp(x)?));
                    }
                    cc
            */
        };

        let mut nomatch: Vec<Option<Outfile>> = vec![None, None];
        for x in &self.unmatch_out {
            if x.file_num == 1 {
                if nomatch[0].is_none() {
                    let mut w = get_writer(&x.file_name)?;
                    f1.write_header(&mut w)?;
                    nomatch[0] = Some(w);
                } else {
                    return err!("Multiple uses of --also for file 1");
                }
            } else if x.file_num == 2 {
                if nomatch[1].is_none() {
                    let mut w = get_writer(&x.file_name)?;
                    f2.write_header(&mut w)?;
                    nomatch[1] = Some(w);
                } else {
                    return err!("Multiple uses of --also for file 2");
                }
            } else {
                return err!(
                    "Join had 2 input files, but requested non matching lines from file {}",
                    x.file_num
                );
            }
        }

        let mut w = get_writer(&self.match_out)?;

        comp.lookup_left(&f1.names())?;
        comp.lookup_right(&f2.names())?;

        let mut out_cols: Vec<OneOutCol> = Vec::new();
        if self.out_cols.is_empty() {
            for x in 0..f1.names().len() {
                out_cols.push(OneOutCol::new_plain(0, x));
            }
            for x in 0..f2.names().len() {
                if x != comp.mode.right_col.num {
                    out_cols.push(OneOutCol::new_plain(1, x));
                }
            }
        } else {
            for x in &mut self.out_cols {
                if x.file == 0 {
                    x.cols.lookup(&f1.names())?;
                } else if x.file == 1 {
                    x.cols.lookup(&f2.names())?;
                } else {
                    return err!(
                        "Two input files, but file {} referred to as an output column",
                        x.file
                    );
                }
                for y in x.cols.get_cols() {
                    out_cols.push(OneOutCol::new(x.file, y));
                }
            }
        }
        if out_cols.is_empty() {
            return err!("No output columns specified");
        }
        if f1.cont.has_header {
            w.write_all(b" CDX")?;
            for x in &out_cols {
                w.write_all(&[self.out_delim])?;
                x.write_head(&mut w, &f1, &f2)?;
            }
            w.write_all(&[b'\n'])?;
        }

        loop {
            if f1.is_done() || f2.is_done() {
                break;
            }
            match comp.comp_cols(f1.curr(), f2.curr()) {
                Ordering::Equal => {
                    out_cols[0].write(&mut w, &f1, &f2)?;
                    for x in &out_cols[1..] {
                        w.write_all(&[self.out_delim])?;
                        x.write(&mut w, &f1, &f2)?;
                    }
                    w.write_all(&[b'\n'])?;

                    f1.getline()?;
                    f2.getline()?;
                }
                Ordering::Less => {
                    if let Some(x) = &mut nomatch[0] {
                        f1.write(x)?;
                    }
                    f1.getline()?;
                }
                Ordering::Greater => {
                    if let Some(x) = &mut nomatch[1] {
                        f2.write(x)?;
                    }
                    f2.getline()?;
                }
            }
        }
        while !f1.is_done() {
            if let Some(x) = &mut nomatch[0] {
                f1.write(x)?;
            }
            f1.getline()?;
        }
        while !f2.is_done() {
            if let Some(x) = &mut nomatch[1] {
                f2.write(x)?;
            }
            f2.getline()?;
        }
        // drain f1 or f2 as needed
        Ok(())
    }

steal owned columns by value

Examples found in repository
src/column.rs (line 460)
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
pub fn ranges(fieldnames: &[&str], rng: &str) -> Result<Vec<OutCol>> {
        let mut c = ColumnSet::new();
        c.add_yes(rng);
        c.lookup(fieldnames)?;
        Ok(c.get_cols_full())
    }
    /// turn range into list of column numbers
    fn range(fieldnames: &[&str], rng: &str) -> Result<Vec<OutCol>> {
        if rng.is_empty() {
            return err!("Empty Range {}", rng);
        }
        let (name, range) = match rng.split_once(':') {
            None => ("", rng),
            Some(x) => x,
        };

        let ch = range.chars().next().unwrap();
        if ch == '<' || ch == '>' || ch == '=' {
            return Ok(Self::to_outcols(
                &Self::text_range(fieldnames, range)?,
                name,
            ));
        }
        if range.contains('*') || rng.contains('?') {
            return Ok(Self::to_outcols(
                &Self::glob_range(fieldnames, range)?,
                name,
            ));
        }

        let mut parts: Vec<&str> = range.split('-').collect();
        if parts.len() > 2 {
            return err!("Malformed Range {}", rng);
        }
        if parts[0].is_empty() {
            parts[0] = "1";
        }

        let start: usize;
        let end: usize;
        if parts.len() == 1 {
            start = Self::single(fieldnames, parts[0])?;
            end = start;
        } else {
            if parts[1].is_empty() {
                parts[1] = "+1";
            }
            start = Self::single(fieldnames, parts[0])?;
            end = Self::single(fieldnames, parts[1])?;
        }

        if start > end {
            // throw new CdxException("start > end, i.e. {" + parts.get(0) + " > " + parts.get(1));
            return err!("Start greater than end : {}", rng);
        }
        let mut res = Vec::new();
        for i in start..=end {
            res.push(OutCol::new(i, name));
        }
        Ok(res)
    }

    /// resolve `ColumnSet` in context of the column names from an input file
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    assert_eq!(s.get_cols_num(), &[0,1,3,4]);
    /// ```
    pub fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.did_lookup = true;
        self.columns = Vec::new();
        let mut no_cols: HashSet<usize> = HashSet::new();

        for s in &self.neg {
            for x in Self::range(fieldnames, s)? {
                no_cols.insert(x.num);
            }
        }

        if self.pos.is_empty() {
            for x in 0..fieldnames.len() {
                if !no_cols.contains(&x) {
                    self.columns.push(OutCol::from_num(x));
                }
            }
        } else {
            for s in &self.pos {
                for x in Self::range(fieldnames, s)? {
                    if !no_cols.contains(&x.num) {
                        self.columns.push(x);
                    }
                }
            }
        }
        Ok(())
    }

    /// Select columns from input line based on `ColumnSet`. Fail if input is too short. """
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    let v = ["Zeroth", "First", "Second", "Third", "Fourth", "Fifth"];
    ///    let mut res = Vec::new();
    ///    s.select(&v, &mut res);
    ///    assert_eq!(res, vec!["Zeroth", "First", "Third", "Fourth"]);
    /// ```
    pub fn select<T: AsRef<str> + Clone>(&self, cols: &[T], result: &mut Vec<T>) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        result.clear();
        for x in &self.columns {
            if x.num < cols.len() {
                result.push(cols[x.num].clone());
            } else {
                return err!(
                    "Line has only {} columns, but column {} was requested.",
                    cols.len(),
                    x.num + 1
                );
            }
        }
        Ok(())
    }

    /// write the appropriate selection from the given columns
    /// trying to write a non-existant column is an error
    pub fn write(&self, w: &mut dyn Write, cols: &[&str], delim: &str) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols[first.num].as_bytes())?;

                for x in iter {
                    w.write_all(delim.as_bytes())?;
                    if x.num < cols.len() {
                        w.write_all(cols[x.num].as_bytes())?;
                    } else {
                        return err!(
                            "Line has only {} columns, but column {} was requested.",
                            cols.len(),
                            x.num + 1
                        );
                    }
                }
            }
        };
        w.write_all(&[b'\n'])?;
        Ok(())
    }

    /// write the appropriate selection from the given columns
    pub fn write2(&self, w: &mut dyn Write, cols: &TextLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(&cols[first.num])?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num))?;
                }
            }
        };
        w.write_all(&[b'\n'])?;
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    pub fn write3(&self, w: &mut dyn Write, cols: &TextLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols.get(first.num))?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num))?;
                }
            }
        };
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    pub fn write3s(&self, w: &mut dyn Write, cols: &StringLine, delim: u8) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        let mut iter = self.columns.iter();
        match iter.next() {
            None => {}
            Some(first) => {
                w.write_all(cols.get(first.num).as_bytes())?;
                for x in iter {
                    w.write_all(&[delim])?;
                    w.write_all(cols.get(x.num).as_bytes())?;
                }
            }
        };
        Ok(())
    }

    /// write the appropriate selection from the given columns, but no trailing newline
    /// trying to write a non-existant column writes the provided default value
    pub fn write_sloppy(&self, cols: &[&str], rest: &str, w: &mut dyn Write) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        for x in &self.columns {
            if x.num < cols.len() {
                w.write_all(cols[x.num].as_bytes())?;
            } else {
                w.write_all(rest.as_bytes())?;
            }
        }
        Ok(())
    }

    /// Select columns from input line based on `ColumnSet`, fill in default if line is too short """
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    let mut s = ColumnSet::new();
    ///    s.add_no("two");
    ///    s.lookup(&header);
    ///    let v = ["Zeroth", "First", "Second", "Third"];
    ///    let mut res = Vec::new();
    ///    s.select_sloppy(&v, &"extra", &mut res);
    ///    assert_eq!(res, vec!["Zeroth", "First", "Third", "extra"]);
    /// ```
    pub fn select_sloppy<T: AsRef<str> + Clone>(
        &self,
        cols: &[T],
        restval: &T,
        result: &mut Vec<T>,
    ) -> Result<()> {
        if !self.did_lookup {
            return Err(Error::NeedLookup);
        }
        result.clear();
        for x in &self.columns {
            if x.num < cols.len() {
                result.push(cols[x.num].clone());
            } else {
                result.push(restval.clone());
            }
        }
        Ok(())
    }

    /// return owned columns by const reference
    pub fn get_cols(&self) -> &Vec<OutCol> {
        &self.columns
    }

    /// steal owned columns by value
    pub fn get_cols_full(self) -> Vec<OutCol> {
        self.columns
    }

    /// get owned column numbers
    pub fn get_cols_num(&self) -> Vec<usize> {
        let mut v = Vec::with_capacity(self.columns.len());
        for x in &self.columns {
            v.push(x.num);
        }
        v
    }

    /// Shorthand to look up some columns
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    assert_eq!(ColumnSet::lookup_cols("~2-3", &header).unwrap(), &[0,3,4]);
    /// ```
    pub fn lookup_cols(spec: &str, names: &[&str]) -> Result<Vec<usize>> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        Ok(s.get_cols_num())
    }

    /// Shorthand to look up some columns, with names
    pub fn lookup_cols_full(spec: &str, names: &[&str]) -> Result<Vec<OutCol>> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        Ok(s.get_cols_full())
    }

get owned column numbers

Examples found in repository
src/column.rs (line 760)
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
pub fn lookup_cols(spec: &str, names: &[&str]) -> Result<Vec<usize>> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        Ok(s.get_cols_num())
    }

    /// Shorthand to look up some columns, with names
    pub fn lookup_cols_full(spec: &str, names: &[&str]) -> Result<Vec<OutCol>> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        Ok(s.get_cols_full())
    }

    /// Shorthand to look up a single column
    /// To look up a single named column, `lookup_col` is also available
    /// # Examples
    ///
    /// ```
    ///    use cdx::column::ColumnSet;
    ///    let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
    ///    assert_eq!(ColumnSet::lookup1("three", &header).unwrap(), 3);
    /// ```
    pub fn lookup1(spec: &str, names: &[&str]) -> Result<usize> {
        let mut s = ColumnSet::new();
        s.add_yes(spec);
        s.lookup(names)?;
        if s.get_cols().len() != 1 {
            return err!(
                "Spec {} resolves to {} columns, rather than a single column",
                spec,
                s.get_cols().len()
            );
        }
        Ok(s.get_cols_num()[0])
    }

Shorthand to look up some columns

Examples
   use cdx::column::ColumnSet;
   let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
   assert_eq!(ColumnSet::lookup_cols("~2-3", &header).unwrap(), &[0,3,4]);

Shorthand to look up some columns, with names

Shorthand to look up a single column To look up a single named column, lookup_col is also available

Examples
   use cdx::column::ColumnSet;
   let header: [&str; 5] = ["zero", "one", "two", "three", "four"];
   assert_eq!(ColumnSet::lookup1("three", &header).unwrap(), 3);

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.

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)

recently added

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.