pub struct LineCompList { /* private fields */ }
Expand description

Ordered list of LineComp

Implementations

new

Examples found in repository?
src/join.rs (line 158)
155
156
157
158
159
160
161
162
163
    fn new(config: &JoinConfig) -> Result<Self> {
        Ok(Self {
            r: Vec::new(),
            comp: LineCompList::new(),
            yes_match: get_writer(&config.match_out)?,
            no_match: Vec::new(),
            out_cols: Vec::new(),
        })
    }
More examples
Hide additional examples
src/bin/cdx/sort_main.rs (line 21)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Sort lines.", args::FileCount::Many);
    const A: [ArgSpec; 7] = [
        arg! {"key", "k", "Spec", "How to compare adjacent lines"},
        arg! {"unique", "u", "", "Print only first of equal lines"},
        arg! {"merge", "m", "", "Merge already sorted files."},
        arg! {"check", "c", "", "Check to see if each input file is sorted."},
        arg! {"Check", "C", "Number", "Check to see if each input file is sorted. Report this many failures before exiting."},
        arg! {"alt-sort", "a", "", "Use alternate sort algorithm"},
        arg! {"alt-merge", "A", "", "Use alternate merge algorithm"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut unique = false;
    let mut merge = false;
    let mut comp = LineCompList::new();
    let mut check = false;
    let mut num_checks = 1;
    let mut config = SortConfig::default();
    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "alt-merge" {
            config.alt_merge = true;
        } else if x.name == "alt-sort" {
            config.alt_sort = true;
        } else if x.name == "merge" {
            merge = true;
        } else if x.name == "check" {
            check = true;
            num_checks = 1;
        } else if x.name == "Check" {
            check = true;
            num_checks = x
                .value
                .to_usize_whole(x.value.as_bytes(), "number of reports")?;
        } else if x.name == "unique" {
            unique = true;
        } else {
            unreachable!();
        }
    }
    if check && merge {
        return err!("Check and Merge make no sense together");
    }
    if comp.is_empty() {
        comp.add("")?;
    }
    if check {
        let mut reported = 0;
        for x in &files {
            let mut f = Reader::new_open(x, &settings.text_in)?;
            if f.is_done() {
                continue;
            }
            loop {
                if f.getline()? {
                    break;
                }
                if comp_check(&f, &mut comp, unique) {
                    reported += 1;
                    if reported >= num_checks {
                        break;
                    }
                }
            }
        }
        if reported > 0 {
            return cdx_err(CdxError::Silent);
        }
    } else {
        let mut w = get_writer("-")?;
        if merge {
            config.merge(&files, &mut comp, &mut w.0, unique)?;
        } else {
            config.sort(&files, comp, &mut w.0, unique)?;
        }
    }
    Ok(())
}
src/bin/cdx/binsearch_main.rs (line 103)
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Search sorted files.", args::FileCount::Many);
    const A: [ArgSpec; 5] = [
        arg! {"key", "k", "Spec", "How to compare value to lines"},
        arg! {"filename", "H", "ColName:Parts", "Prefix output lines with file name."},
        arg! {"context", "C", "before,after",  "print lines of context around matches"},
        arg! {"sub-delim", "s", "Char",  "Delimiter between keys for multi-column searches"},
        arg_pos! {"pattern", "search string",  "Search for this string in each file"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut filename: Option<FileNameColumn> = None;
    let mut context = Context::new();
    let mut subdelim = b',';
    let mut comp = LineCompList::new();
    let mut pattern: Option<String> = None;

    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "filename" {
            if filename.is_some() {
                return err!("You cant use --filename twice");
            }
            let mut f = FileNameColumn::new();
            f.set(&x.value)?;
            filename = Some(f);
        } else if x.name == "context" {
            context.set(&x.value)?;
        } else if x.name == "subdelim" {
            if x.value.len() != 1 {
                return err!("--sub-delim value must be a single character");
            }
            subdelim = x.value.as_bytes()[0];
        } else if x.name == "pattern" {
            pattern = Some(x.value);
        } else {
            unreachable!();
        }
    }
    if pattern.is_none() {
        return err!("The pattern is required");
    }
    let pattern = pattern.unwrap();
    if files.is_empty() {
        return err!("At least one file is required : you can't binary search stdin.");
    }
    if comp.is_empty() {
        comp.add("1")?;
    }
    comp.set(pattern.as_bytes(), subdelim)?;
    let mut w = get_writer("-")?;
    let mut not_header: Vec<u8> = Vec::new();

    for f in &files {
        let m = MemMap::new(f)?;
        not_header.clear();
        if m.has_header() {
            if filename.is_none() {
                not_header.extend(m.header());
            } else {
                not_header.extend(b" CDX\t");
                not_header.extend(filename.as_ref().unwrap().name.as_bytes());
                not_header.extend(&m.header()[4..]);
            }
        }
        if settings.checker.check(&not_header, f)? {
            w.write_all(&not_header)?;
        }
        comp.lookup(&m.names())?;
        let (mut start, mut stop) = equal_range_n(m.get(), &mut comp);
        let (before, after) = context.get(start == stop);
        for _x in 0..before {
            if start == 0 {
                break;
            }
            start = find_prev(m.get(), start);
        }
        for _x in 0..after {
            stop = find_end(m.get(), stop);
        }
        if filename.is_none() {
            write_all_nl(&mut w.0, &m.get()[start..stop])?;
        } else {
            let file: &FileNameColumn = filename.as_ref().unwrap();
            while start < stop {
                let end = find_end(m.get(), start);
                w.write_all(f.tail_path_u8(file.tail, b'/').as_bytes())?;
                w.write_all(&[b'\t'])?;
                write_all_nl(&mut w.0, &m.get()[start..end])?;
                start = end;
            }
        }
    }
    Ok(())
}
src/bin/cdx/verify_main.rs (line 37)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Verify file contents.", args::FileCount::Many);
    const A: [ArgSpec; 10] = [
        arg! {"report", "r", "Number", "How many failures to report before exit."},
        arg! {"first", "f", "Op,Value", "'FirstLine Op Value' must be true. E.g LT,a for first line is less than 'a'."},
        arg! {"last", "l", "Op,Value", "'LastLine Op Value' must be true."},
        arg! {"key", "k", "Spec", "How to compare adjacent lines"},
        arg! {"sort", "s", "", "Check that the file is sorted."},
        arg! {"unique", "u", "", "Check that the file is sorted, with unique lines."},
        arg! {"pattern", "p", "Col,Spec,Pattern", "Select line where this col matches this pattern."},
        arg! {"show-matchers", "", "", "Print available matchers"},
        arg! {"show-const", "", "", "Print available constants"},
        arg! {"show-func", "", "", "Print available functions"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut list = LineMatcherList::new_with(Combiner::And);
    let mut comp = LineCompList::new();
    let mut do_sort = false;
    let mut do_unique = false;
    let mut max_fails = 5;
    let mut first: Option<CheckLine> = None;
    let mut last: Option<CheckLine> = None;

    for x in args {
        if x.name == "pattern" {
            list.push(&x.value)?;
        } else if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "or" {
            list.multi = Combiner::Or;
        } else if x.name == "fail" {
            max_fails = x.value.to_usize_whole(x.value.as_bytes(), "max fails")?;
        } else if x.name == "sort" {
            do_sort = true;
        } else if x.name == "first" {
            first = Some(CheckLine::new(&x.value)?);
        } else if x.name == "last" {
            last = Some(CheckLine::new(&x.value)?);
        } else if x.name == "unique" {
            do_sort = true;
            do_unique = true;
        } else if x.name == "show-const" {
            expr::show_const();
            return Ok(());
        } else if x.name == "show-func" {
            expr::show_func();
            return Ok(());
        } else {
            unreachable!();
        }
    }
    if comp.is_empty() {
        comp.add("")?;
    }

    let mut fails = 0;
    for x in &files {
        let mut f = Reader::new(&settings.text_in);
        f.open(x)?;
        if f.is_empty() {
            continue;
        }
        list.lookup(&f.names())?;
        comp.lookup(&f.names())?;
        if f.is_done() {
            continue;
        }
        if first.is_some()
            && !first.as_ref().unwrap().line_ok_verbose(
                f.curr_line(),
                &mut comp,
                f.line_number(),
            )?
        {
            fails += 1;
        }
        let num_cols = f.names().len();
        loop {
            let mut did_fail = false;
            if f.curr().len() != num_cols {
                eprintln!(
                    "Expected {num_cols} columns, but line {} of {} had {}",
                    f.line_number() + 1,
                    x,
                    f.curr().len()
                );
                did_fail = true;
            }
            if !list.ok_verbose(f.curr_line(), f.line_number(), x) {
                did_fail = true;
            }
            if f.getline()? {
                if last.is_some()
                    && !last.as_ref().unwrap().line_ok_verbose(
                        f.prev_line(1),
                        &mut comp,
                        f.line_number() - 1,
                    )?
                {
                    fails += 1;
                }
                break;
            }
            if do_sort {
                did_fail = did_fail || comp_check(&f, &mut comp, do_unique);
            }
            if did_fail {
                fails += 1;
                if fails >= max_fails {
                    break;
                }
            }
        }
        if fails > 0 {
            return cdx_err(CdxError::Silent);
        }
    }
    Ok(())
}
src/bin/cdx/uniq_main.rs (line 169)
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
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Select uniq lines.", args::FileCount::One);
    const A: [ArgSpec; 7] = [
        arg! {"agg", "a", "Col,Spec", "Merge value from this column, in place."},
        arg! {"agg-pre", "", "NewCol,SrcCol,Spec", "Merge value from SrcCol into new column, before other columns."},
        arg! {"agg-post", "", "NewCol,SrcCol,Spec", "Merge value from SrcCol into new column, after other columns."},
        arg! {"key", "k", "Spec", "How to compare adjacent lines"},
        arg! {"count", "c", "ColName,Position", "Write the count of matching line."},
        arg! {"which", "w", "(First,Last,Min,Max)[,LineCompare]", "Which of the matching lines should be printed."},
        arg! {"agg-help", "", "", "Print help for aggregators"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut agg = LineAggList::new();
    let mut comp = LineCompList::new();
    let mut count = Count::default();

    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "count" {
            count.get_count(&x.value)?;
        } else if x.name == "which" {
            count.get_which(&x.value)?;
        } else if x.name == "agg" {
            agg.push_replace(&x.value)?;
        } else if x.name == "agg-post" {
            agg.push_append(&x.value)?;
        } else if x.name == "agg-pre" {
            agg.push_prefix(&x.value)?;
        } else {
            unreachable!();
        }
    }

    assert_eq!(files.len(), 1);

    let mut f = Reader::new(&settings.text_in);
    f.open(&files[0])?;
    if f.is_empty() {
        return Ok(());
    }
    comp.lookup(&f.names())?;
    count.lookup(&f.names())?;
    let mut c_write = Writer::new(settings.text_out());
    if !agg.is_empty() {
        if count.pos == CountPos::Begin {
            agg.push_first_prefix(&format!("{},1,count", count.name))?;
        }
        if count.pos == CountPos::End {
            agg.push_append(&format!("{},1,count", count.name))?;
        }
        agg.lookup(&f.names())?;
        agg.fill(&mut c_write, f.header());
        c_write.lookup(&f.names())?;
    }

    let mut w = get_writer("-")?;
    if f.has_header() {
        let mut ch = ColumnHeader::new();
        if agg.is_empty() {
            if count.pos == CountPos::Begin {
                ch.push(&count.name)?;
            }
            ch.push_all(f.header())?;
            if count.pos == CountPos::End {
                ch.push(&count.name)?;
            }
        } else {
            c_write.add_names(&mut ch, f.header())?;
        }
        w.write_all(ch.get_head(&settings.text_out()).as_bytes())?;
    }
    if f.is_done() {
        return Ok(());
    }

    f.do_split(comp.need_split());
    let mut matches = 1;
    if !agg.is_empty() {
        agg.add(f.curr_line());
        let mut tmp = f.curr_line().clone();
        loop {
            if f.getline()? {
                c_write.write(&mut w.0, &tmp)?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                count.assign(&mut tmp, f.curr_line());
                agg.add(f.curr_line());
            } else {
                c_write.write(&mut w.0, &tmp)?;
                tmp.assign(f.curr_line());
                agg.reset();
                agg.add(f.curr_line());
            }
        }
    } else if count.which == Which::Last {
        loop {
            if f.getline()? {
                count.write(&mut w.0, matches, f.prev_line(1).line(), f.delim())?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                matches += 1;
            } else {
                count.write(&mut w.0, matches, f.prev_line(1).line(), f.delim())?;
                matches = 1;
            }
        }
    } else if count.which == Which::First && count.is_plain() {
        f.write_curr(&mut w.0)?;
        loop {
            if f.getline()? {
                break;
            }
            if !comp.equal_cols(f.prev_line(1), f.curr_line()) {
                f.write_curr(&mut w.0)?;
            }
        }
    } else {
        let mut tmp = f.curr_line().clone();
        loop {
            if f.getline()? {
                count.write(&mut w.0, matches, tmp.line(), f.delim())?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                count.assign(&mut tmp, f.curr_line());
                matches += 1;
            } else {
                count.write(&mut w.0, matches, tmp.line(), f.delim())?;
                tmp.assign(f.curr_line());
                matches = 1;
            }
        }
    }
    Ok(())
}

any LineComps in the list?

Examples found in repository?
src/bin/cdx/sort_main.rs (line 51)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Sort lines.", args::FileCount::Many);
    const A: [ArgSpec; 7] = [
        arg! {"key", "k", "Spec", "How to compare adjacent lines"},
        arg! {"unique", "u", "", "Print only first of equal lines"},
        arg! {"merge", "m", "", "Merge already sorted files."},
        arg! {"check", "c", "", "Check to see if each input file is sorted."},
        arg! {"Check", "C", "Number", "Check to see if each input file is sorted. Report this many failures before exiting."},
        arg! {"alt-sort", "a", "", "Use alternate sort algorithm"},
        arg! {"alt-merge", "A", "", "Use alternate merge algorithm"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut unique = false;
    let mut merge = false;
    let mut comp = LineCompList::new();
    let mut check = false;
    let mut num_checks = 1;
    let mut config = SortConfig::default();
    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "alt-merge" {
            config.alt_merge = true;
        } else if x.name == "alt-sort" {
            config.alt_sort = true;
        } else if x.name == "merge" {
            merge = true;
        } else if x.name == "check" {
            check = true;
            num_checks = 1;
        } else if x.name == "Check" {
            check = true;
            num_checks = x
                .value
                .to_usize_whole(x.value.as_bytes(), "number of reports")?;
        } else if x.name == "unique" {
            unique = true;
        } else {
            unreachable!();
        }
    }
    if check && merge {
        return err!("Check and Merge make no sense together");
    }
    if comp.is_empty() {
        comp.add("")?;
    }
    if check {
        let mut reported = 0;
        for x in &files {
            let mut f = Reader::new_open(x, &settings.text_in)?;
            if f.is_done() {
                continue;
            }
            loop {
                if f.getline()? {
                    break;
                }
                if comp_check(&f, &mut comp, unique) {
                    reported += 1;
                    if reported >= num_checks {
                        break;
                    }
                }
            }
        }
        if reported > 0 {
            return cdx_err(CdxError::Silent);
        }
    } else {
        let mut w = get_writer("-")?;
        if merge {
            config.merge(&files, &mut comp, &mut w.0, unique)?;
        } else {
            config.sort(&files, comp, &mut w.0, unique)?;
        }
    }
    Ok(())
}
More examples
Hide additional examples
src/bin/cdx/binsearch_main.rs (line 136)
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Search sorted files.", args::FileCount::Many);
    const A: [ArgSpec; 5] = [
        arg! {"key", "k", "Spec", "How to compare value to lines"},
        arg! {"filename", "H", "ColName:Parts", "Prefix output lines with file name."},
        arg! {"context", "C", "before,after",  "print lines of context around matches"},
        arg! {"sub-delim", "s", "Char",  "Delimiter between keys for multi-column searches"},
        arg_pos! {"pattern", "search string",  "Search for this string in each file"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut filename: Option<FileNameColumn> = None;
    let mut context = Context::new();
    let mut subdelim = b',';
    let mut comp = LineCompList::new();
    let mut pattern: Option<String> = None;

    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "filename" {
            if filename.is_some() {
                return err!("You cant use --filename twice");
            }
            let mut f = FileNameColumn::new();
            f.set(&x.value)?;
            filename = Some(f);
        } else if x.name == "context" {
            context.set(&x.value)?;
        } else if x.name == "subdelim" {
            if x.value.len() != 1 {
                return err!("--sub-delim value must be a single character");
            }
            subdelim = x.value.as_bytes()[0];
        } else if x.name == "pattern" {
            pattern = Some(x.value);
        } else {
            unreachable!();
        }
    }
    if pattern.is_none() {
        return err!("The pattern is required");
    }
    let pattern = pattern.unwrap();
    if files.is_empty() {
        return err!("At least one file is required : you can't binary search stdin.");
    }
    if comp.is_empty() {
        comp.add("1")?;
    }
    comp.set(pattern.as_bytes(), subdelim)?;
    let mut w = get_writer("-")?;
    let mut not_header: Vec<u8> = Vec::new();

    for f in &files {
        let m = MemMap::new(f)?;
        not_header.clear();
        if m.has_header() {
            if filename.is_none() {
                not_header.extend(m.header());
            } else {
                not_header.extend(b" CDX\t");
                not_header.extend(filename.as_ref().unwrap().name.as_bytes());
                not_header.extend(&m.header()[4..]);
            }
        }
        if settings.checker.check(&not_header, f)? {
            w.write_all(&not_header)?;
        }
        comp.lookup(&m.names())?;
        let (mut start, mut stop) = equal_range_n(m.get(), &mut comp);
        let (before, after) = context.get(start == stop);
        for _x in 0..before {
            if start == 0 {
                break;
            }
            start = find_prev(m.get(), start);
        }
        for _x in 0..after {
            stop = find_end(m.get(), stop);
        }
        if filename.is_none() {
            write_all_nl(&mut w.0, &m.get()[start..stop])?;
        } else {
            let file: &FileNameColumn = filename.as_ref().unwrap();
            while start < stop {
                let end = find_end(m.get(), start);
                w.write_all(f.tail_path_u8(file.tail, b'/').as_bytes())?;
                w.write_all(&[b'\t'])?;
                write_all_nl(&mut w.0, &m.get()[start..end])?;
                start = end;
            }
        }
    }
    Ok(())
}
src/bin/cdx/verify_main.rs (line 72)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Verify file contents.", args::FileCount::Many);
    const A: [ArgSpec; 10] = [
        arg! {"report", "r", "Number", "How many failures to report before exit."},
        arg! {"first", "f", "Op,Value", "'FirstLine Op Value' must be true. E.g LT,a for first line is less than 'a'."},
        arg! {"last", "l", "Op,Value", "'LastLine Op Value' must be true."},
        arg! {"key", "k", "Spec", "How to compare adjacent lines"},
        arg! {"sort", "s", "", "Check that the file is sorted."},
        arg! {"unique", "u", "", "Check that the file is sorted, with unique lines."},
        arg! {"pattern", "p", "Col,Spec,Pattern", "Select line where this col matches this pattern."},
        arg! {"show-matchers", "", "", "Print available matchers"},
        arg! {"show-const", "", "", "Print available constants"},
        arg! {"show-func", "", "", "Print available functions"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut list = LineMatcherList::new_with(Combiner::And);
    let mut comp = LineCompList::new();
    let mut do_sort = false;
    let mut do_unique = false;
    let mut max_fails = 5;
    let mut first: Option<CheckLine> = None;
    let mut last: Option<CheckLine> = None;

    for x in args {
        if x.name == "pattern" {
            list.push(&x.value)?;
        } else if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "or" {
            list.multi = Combiner::Or;
        } else if x.name == "fail" {
            max_fails = x.value.to_usize_whole(x.value.as_bytes(), "max fails")?;
        } else if x.name == "sort" {
            do_sort = true;
        } else if x.name == "first" {
            first = Some(CheckLine::new(&x.value)?);
        } else if x.name == "last" {
            last = Some(CheckLine::new(&x.value)?);
        } else if x.name == "unique" {
            do_sort = true;
            do_unique = true;
        } else if x.name == "show-const" {
            expr::show_const();
            return Ok(());
        } else if x.name == "show-func" {
            expr::show_func();
            return Ok(());
        } else {
            unreachable!();
        }
    }
    if comp.is_empty() {
        comp.add("")?;
    }

    let mut fails = 0;
    for x in &files {
        let mut f = Reader::new(&settings.text_in);
        f.open(x)?;
        if f.is_empty() {
            continue;
        }
        list.lookup(&f.names())?;
        comp.lookup(&f.names())?;
        if f.is_done() {
            continue;
        }
        if first.is_some()
            && !first.as_ref().unwrap().line_ok_verbose(
                f.curr_line(),
                &mut comp,
                f.line_number(),
            )?
        {
            fails += 1;
        }
        let num_cols = f.names().len();
        loop {
            let mut did_fail = false;
            if f.curr().len() != num_cols {
                eprintln!(
                    "Expected {num_cols} columns, but line {} of {} had {}",
                    f.line_number() + 1,
                    x,
                    f.curr().len()
                );
                did_fail = true;
            }
            if !list.ok_verbose(f.curr_line(), f.line_number(), x) {
                did_fail = true;
            }
            if f.getline()? {
                if last.is_some()
                    && !last.as_ref().unwrap().line_ok_verbose(
                        f.prev_line(1),
                        &mut comp,
                        f.line_number() - 1,
                    )?
                {
                    fails += 1;
                }
                break;
            }
            if do_sort {
                did_fail = did_fail || comp_check(&f, &mut comp, do_unique);
            }
            if did_fail {
                fails += 1;
                if fails >= max_fails {
                    break;
                }
            }
        }
        if fails > 0 {
            return cdx_err(CdxError::Silent);
        }
    }
    Ok(())
}

which columns used as part of key?

Examples found in repository?
src/join.rs (line 210)
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
    fn join(&mut self, config: &JoinConfig) -> Result<()> {
        if config.infiles.len() < 2 {
            return err!(
                "Join requires at least two input files, {} found",
                config.infiles.len()
            );
        }

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

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

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

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

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

add

Examples found in repository?
src/bin/cdx/sort_main.rs (line 27)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Sort lines.", args::FileCount::Many);
    const A: [ArgSpec; 7] = [
        arg! {"key", "k", "Spec", "How to compare adjacent lines"},
        arg! {"unique", "u", "", "Print only first of equal lines"},
        arg! {"merge", "m", "", "Merge already sorted files."},
        arg! {"check", "c", "", "Check to see if each input file is sorted."},
        arg! {"Check", "C", "Number", "Check to see if each input file is sorted. Report this many failures before exiting."},
        arg! {"alt-sort", "a", "", "Use alternate sort algorithm"},
        arg! {"alt-merge", "A", "", "Use alternate merge algorithm"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut unique = false;
    let mut merge = false;
    let mut comp = LineCompList::new();
    let mut check = false;
    let mut num_checks = 1;
    let mut config = SortConfig::default();
    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "alt-merge" {
            config.alt_merge = true;
        } else if x.name == "alt-sort" {
            config.alt_sort = true;
        } else if x.name == "merge" {
            merge = true;
        } else if x.name == "check" {
            check = true;
            num_checks = 1;
        } else if x.name == "Check" {
            check = true;
            num_checks = x
                .value
                .to_usize_whole(x.value.as_bytes(), "number of reports")?;
        } else if x.name == "unique" {
            unique = true;
        } else {
            unreachable!();
        }
    }
    if check && merge {
        return err!("Check and Merge make no sense together");
    }
    if comp.is_empty() {
        comp.add("")?;
    }
    if check {
        let mut reported = 0;
        for x in &files {
            let mut f = Reader::new_open(x, &settings.text_in)?;
            if f.is_done() {
                continue;
            }
            loop {
                if f.getline()? {
                    break;
                }
                if comp_check(&f, &mut comp, unique) {
                    reported += 1;
                    if reported >= num_checks {
                        break;
                    }
                }
            }
        }
        if reported > 0 {
            return cdx_err(CdxError::Silent);
        }
    } else {
        let mut w = get_writer("-")?;
        if merge {
            config.merge(&files, &mut comp, &mut w.0, unique)?;
        } else {
            config.sort(&files, comp, &mut w.0, unique)?;
        }
    }
    Ok(())
}
More examples
Hide additional examples
src/bin/cdx/binsearch_main.rs (line 108)
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Search sorted files.", args::FileCount::Many);
    const A: [ArgSpec; 5] = [
        arg! {"key", "k", "Spec", "How to compare value to lines"},
        arg! {"filename", "H", "ColName:Parts", "Prefix output lines with file name."},
        arg! {"context", "C", "before,after",  "print lines of context around matches"},
        arg! {"sub-delim", "s", "Char",  "Delimiter between keys for multi-column searches"},
        arg_pos! {"pattern", "search string",  "Search for this string in each file"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut filename: Option<FileNameColumn> = None;
    let mut context = Context::new();
    let mut subdelim = b',';
    let mut comp = LineCompList::new();
    let mut pattern: Option<String> = None;

    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "filename" {
            if filename.is_some() {
                return err!("You cant use --filename twice");
            }
            let mut f = FileNameColumn::new();
            f.set(&x.value)?;
            filename = Some(f);
        } else if x.name == "context" {
            context.set(&x.value)?;
        } else if x.name == "subdelim" {
            if x.value.len() != 1 {
                return err!("--sub-delim value must be a single character");
            }
            subdelim = x.value.as_bytes()[0];
        } else if x.name == "pattern" {
            pattern = Some(x.value);
        } else {
            unreachable!();
        }
    }
    if pattern.is_none() {
        return err!("The pattern is required");
    }
    let pattern = pattern.unwrap();
    if files.is_empty() {
        return err!("At least one file is required : you can't binary search stdin.");
    }
    if comp.is_empty() {
        comp.add("1")?;
    }
    comp.set(pattern.as_bytes(), subdelim)?;
    let mut w = get_writer("-")?;
    let mut not_header: Vec<u8> = Vec::new();

    for f in &files {
        let m = MemMap::new(f)?;
        not_header.clear();
        if m.has_header() {
            if filename.is_none() {
                not_header.extend(m.header());
            } else {
                not_header.extend(b" CDX\t");
                not_header.extend(filename.as_ref().unwrap().name.as_bytes());
                not_header.extend(&m.header()[4..]);
            }
        }
        if settings.checker.check(&not_header, f)? {
            w.write_all(&not_header)?;
        }
        comp.lookup(&m.names())?;
        let (mut start, mut stop) = equal_range_n(m.get(), &mut comp);
        let (before, after) = context.get(start == stop);
        for _x in 0..before {
            if start == 0 {
                break;
            }
            start = find_prev(m.get(), start);
        }
        for _x in 0..after {
            stop = find_end(m.get(), stop);
        }
        if filename.is_none() {
            write_all_nl(&mut w.0, &m.get()[start..stop])?;
        } else {
            let file: &FileNameColumn = filename.as_ref().unwrap();
            while start < stop {
                let end = find_end(m.get(), start);
                w.write_all(f.tail_path_u8(file.tail, b'/').as_bytes())?;
                w.write_all(&[b'\t'])?;
                write_all_nl(&mut w.0, &m.get()[start..end])?;
                start = end;
            }
        }
    }
    Ok(())
}
src/bin/cdx/verify_main.rs (line 48)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Verify file contents.", args::FileCount::Many);
    const A: [ArgSpec; 10] = [
        arg! {"report", "r", "Number", "How many failures to report before exit."},
        arg! {"first", "f", "Op,Value", "'FirstLine Op Value' must be true. E.g LT,a for first line is less than 'a'."},
        arg! {"last", "l", "Op,Value", "'LastLine Op Value' must be true."},
        arg! {"key", "k", "Spec", "How to compare adjacent lines"},
        arg! {"sort", "s", "", "Check that the file is sorted."},
        arg! {"unique", "u", "", "Check that the file is sorted, with unique lines."},
        arg! {"pattern", "p", "Col,Spec,Pattern", "Select line where this col matches this pattern."},
        arg! {"show-matchers", "", "", "Print available matchers"},
        arg! {"show-const", "", "", "Print available constants"},
        arg! {"show-func", "", "", "Print available functions"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut list = LineMatcherList::new_with(Combiner::And);
    let mut comp = LineCompList::new();
    let mut do_sort = false;
    let mut do_unique = false;
    let mut max_fails = 5;
    let mut first: Option<CheckLine> = None;
    let mut last: Option<CheckLine> = None;

    for x in args {
        if x.name == "pattern" {
            list.push(&x.value)?;
        } else if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "or" {
            list.multi = Combiner::Or;
        } else if x.name == "fail" {
            max_fails = x.value.to_usize_whole(x.value.as_bytes(), "max fails")?;
        } else if x.name == "sort" {
            do_sort = true;
        } else if x.name == "first" {
            first = Some(CheckLine::new(&x.value)?);
        } else if x.name == "last" {
            last = Some(CheckLine::new(&x.value)?);
        } else if x.name == "unique" {
            do_sort = true;
            do_unique = true;
        } else if x.name == "show-const" {
            expr::show_const();
            return Ok(());
        } else if x.name == "show-func" {
            expr::show_func();
            return Ok(());
        } else {
            unreachable!();
        }
    }
    if comp.is_empty() {
        comp.add("")?;
    }

    let mut fails = 0;
    for x in &files {
        let mut f = Reader::new(&settings.text_in);
        f.open(x)?;
        if f.is_empty() {
            continue;
        }
        list.lookup(&f.names())?;
        comp.lookup(&f.names())?;
        if f.is_done() {
            continue;
        }
        if first.is_some()
            && !first.as_ref().unwrap().line_ok_verbose(
                f.curr_line(),
                &mut comp,
                f.line_number(),
            )?
        {
            fails += 1;
        }
        let num_cols = f.names().len();
        loop {
            let mut did_fail = false;
            if f.curr().len() != num_cols {
                eprintln!(
                    "Expected {num_cols} columns, but line {} of {} had {}",
                    f.line_number() + 1,
                    x,
                    f.curr().len()
                );
                did_fail = true;
            }
            if !list.ok_verbose(f.curr_line(), f.line_number(), x) {
                did_fail = true;
            }
            if f.getline()? {
                if last.is_some()
                    && !last.as_ref().unwrap().line_ok_verbose(
                        f.prev_line(1),
                        &mut comp,
                        f.line_number() - 1,
                    )?
                {
                    fails += 1;
                }
                break;
            }
            if do_sort {
                did_fail = did_fail || comp_check(&f, &mut comp, do_unique);
            }
            if did_fail {
                fails += 1;
                if fails >= max_fails {
                    break;
                }
            }
        }
        if fails > 0 {
            return cdx_err(CdxError::Silent);
        }
    }
    Ok(())
}
src/bin/cdx/uniq_main.rs (line 174)
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
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Select uniq lines.", args::FileCount::One);
    const A: [ArgSpec; 7] = [
        arg! {"agg", "a", "Col,Spec", "Merge value from this column, in place."},
        arg! {"agg-pre", "", "NewCol,SrcCol,Spec", "Merge value from SrcCol into new column, before other columns."},
        arg! {"agg-post", "", "NewCol,SrcCol,Spec", "Merge value from SrcCol into new column, after other columns."},
        arg! {"key", "k", "Spec", "How to compare adjacent lines"},
        arg! {"count", "c", "ColName,Position", "Write the count of matching line."},
        arg! {"which", "w", "(First,Last,Min,Max)[,LineCompare]", "Which of the matching lines should be printed."},
        arg! {"agg-help", "", "", "Print help for aggregators"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut agg = LineAggList::new();
    let mut comp = LineCompList::new();
    let mut count = Count::default();

    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "count" {
            count.get_count(&x.value)?;
        } else if x.name == "which" {
            count.get_which(&x.value)?;
        } else if x.name == "agg" {
            agg.push_replace(&x.value)?;
        } else if x.name == "agg-post" {
            agg.push_append(&x.value)?;
        } else if x.name == "agg-pre" {
            agg.push_prefix(&x.value)?;
        } else {
            unreachable!();
        }
    }

    assert_eq!(files.len(), 1);

    let mut f = Reader::new(&settings.text_in);
    f.open(&files[0])?;
    if f.is_empty() {
        return Ok(());
    }
    comp.lookup(&f.names())?;
    count.lookup(&f.names())?;
    let mut c_write = Writer::new(settings.text_out());
    if !agg.is_empty() {
        if count.pos == CountPos::Begin {
            agg.push_first_prefix(&format!("{},1,count", count.name))?;
        }
        if count.pos == CountPos::End {
            agg.push_append(&format!("{},1,count", count.name))?;
        }
        agg.lookup(&f.names())?;
        agg.fill(&mut c_write, f.header());
        c_write.lookup(&f.names())?;
    }

    let mut w = get_writer("-")?;
    if f.has_header() {
        let mut ch = ColumnHeader::new();
        if agg.is_empty() {
            if count.pos == CountPos::Begin {
                ch.push(&count.name)?;
            }
            ch.push_all(f.header())?;
            if count.pos == CountPos::End {
                ch.push(&count.name)?;
            }
        } else {
            c_write.add_names(&mut ch, f.header())?;
        }
        w.write_all(ch.get_head(&settings.text_out()).as_bytes())?;
    }
    if f.is_done() {
        return Ok(());
    }

    f.do_split(comp.need_split());
    let mut matches = 1;
    if !agg.is_empty() {
        agg.add(f.curr_line());
        let mut tmp = f.curr_line().clone();
        loop {
            if f.getline()? {
                c_write.write(&mut w.0, &tmp)?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                count.assign(&mut tmp, f.curr_line());
                agg.add(f.curr_line());
            } else {
                c_write.write(&mut w.0, &tmp)?;
                tmp.assign(f.curr_line());
                agg.reset();
                agg.add(f.curr_line());
            }
        }
    } else if count.which == Which::Last {
        loop {
            if f.getline()? {
                count.write(&mut w.0, matches, f.prev_line(1).line(), f.delim())?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                matches += 1;
            } else {
                count.write(&mut w.0, matches, f.prev_line(1).line(), f.delim())?;
                matches = 1;
            }
        }
    } else if count.which == Which::First && count.is_plain() {
        f.write_curr(&mut w.0)?;
        loop {
            if f.getline()? {
                break;
            }
            if !comp.equal_cols(f.prev_line(1), f.curr_line()) {
                f.write_curr(&mut w.0)?;
            }
        }
    } else {
        let mut tmp = f.curr_line().clone();
        loop {
            if f.getline()? {
                count.write(&mut w.0, matches, tmp.line(), f.delim())?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                count.assign(&mut tmp, f.curr_line());
                matches += 1;
            } else {
                count.write(&mut w.0, matches, tmp.line(), f.delim())?;
                tmp.assign(f.curr_line());
                matches = 1;
            }
        }
    }
    Ok(())
}

add

Examples found in repository?
src/join.rs (line 198)
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
    fn join(&mut self, config: &JoinConfig) -> Result<()> {
        if config.infiles.len() < 2 {
            return err!(
                "Join requires at least two input files, {} found",
                config.infiles.len()
            );
        }

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

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

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

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

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

compare Items

Examples found in repository?
src/sort.rs (line 473)
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
    fn do_sort(&mut self) {
        if self.config.alt_sort {
            do_sort_lines(&self.data, &mut self.ptrs, &mut self.cmp);
        } else {
            self.ptrs
                .sort_by(|a, b| self.cmp.comp_items(&self.data, a, b));
        }
        if self.unique {
            self.ptrs
                .dedup_by(|a, b| self.cmp.equal_items(&self.data, a, b));
        }
    }
    /// All files have been added, write final results
    pub fn finalize(&mut self, mut w: impl Write) -> Result<()> {
        self.calc();
        self.do_sort();
        if self.tmp_files.is_empty() {
            for &x in &self.ptrs {
                w.write_all(x.get(&self.data))?;
            }
        } else {
            self.write_tmp()?;
            self.config
                .merge_t(&self.tmp_files, &mut self.cmp, w, self.unique, &self.tmp)?;
        }
        Ok(())
    }

    #[allow(dead_code)]
    fn no_del(self) {
        eprintln!(
            "Not deleting {}",
            self.tmp.into_path().into_os_string().to_string_lossy()
        );
    }
    /// add another file to be sorted
    pub fn add_file<W: Write>(&mut self, fname: &str, w: &mut W) -> Result<()> {
        let mut f = get_reader(fname)?;
        let mut first_line = Vec::new();
        let n = f.read_until(b'\n', &mut first_line)?;
        if n == 0 {
            return Ok(());
        }
        if self.checker.check(&first_line, fname)? {
            let s = make_header(&first_line);
            self.cmp.lookup(&s.vec())?;
            if is_cdx(&first_line) {
                w.write_all(&first_line)?;
            } else {
                self.add_data(&first_line)?;
            }
        }
        self.add(&mut *f)
    }
}

type NodeType = Box<MergeTreeItem>;
struct NodeData {
    left: NodeType,
    right: NodeType,
    left_data: Option<usize>,
    right_data: Option<usize>,
    //    done : bool, Optimization?
}
impl NodeData {
    fn new(left: NodeType, right: NodeType) -> Self {
        Self {
            left,
            right,
            left_data: None,
            right_data: None,
        }
    }
    fn left_cols<'a>(&self, files: &'a [Reader]) -> &'a TextLine {
        files[self.left_data.unwrap()].curr_line()
    }
    fn right_cols<'a>(&self, files: &'a [Reader]) -> &'a TextLine {
        files[self.right_data.unwrap()].curr_line()
    }
}
struct LeafData {
    file_num: usize,
    first: bool,
}

enum MergeTreeItem {
    Leaf(LeafData),
    Node(NodeData),
}

impl MergeTreeItem {
    fn new_tree(files: &[Reader], nums: &[usize]) -> Self {
        if nums.is_empty() {
            panic!("Can't make a MergeTreeItem from zero files")
        } else if nums.len() == 1 {
            Self::new_leaf(nums[0])
        } else {
            let mid = nums.len() / 2;
            Self::new_node(
                Box::new(Self::new_tree(files, &nums[..mid])),
                Box::new(Self::new_tree(files, &nums[mid..])),
            )
        }
    }
    fn new_node(left: NodeType, right: NodeType) -> Self {
        Self::Node(NodeData::new(left, right))
    }
    const fn new_leaf(r: usize) -> Self {
        Self::Leaf(LeafData {
            file_num: r,
            first: true,
        })
    }
    fn next(&mut self, cmp: &mut LineCompList, files: &mut [Reader]) -> Result<Option<usize>> {
        match self {
            Self::Leaf(r) => {
                if files[r.file_num].is_done() {
                    Ok(None)
                } else {
                    if r.first {
                        r.first = false;
                    } else if files[r.file_num].getline()? {
                        return Ok(None);
                    }
                    Ok(Some(r.file_num))
                }
            }
            Self::Node(n) => {
                if n.left_data.is_none() {
                    n.left_data = n.left.next(cmp, files)?;
                }
                if n.right_data.is_none() {
                    n.right_data = n.right.next(cmp, files)?;
                }
                if n.left_data.is_none() && n.right_data.is_none() {
                    Ok(None)
                } else if n.left_data.is_none() {
                    let tmp = n.right_data;
                    n.right_data = None;
                    Ok(tmp)
                } else if n.right_data.is_none() {
                    let tmp = n.left_data;
                    n.left_data = None;
                    Ok(tmp)
                } else {
                    let c = cmp.comp_cols(n.left_cols(files), n.right_cols(files));
                    if c == Ordering::Greater {
                        let tmp = n.right_data;
                        n.right_data = None;
                        Ok(tmp)
                    } else {
                        let tmp = n.left_data;
                        n.left_data = None;
                        Ok(tmp)
                    }
                }
            }
        }
    }
}

#[allow(dead_code)]
fn merge_lines(
    data: &[u8],
    dst: &mut [Item],
    mut low: &[Item],
    mut hi_start: usize,
    hi_end: usize,
    cmp: &mut LineCompList,
) {
    let mut dst_pos = 0;
    loop {
        if cmp.comp_items(data, &low[0], &dst[hi_start]) != Ordering::Greater {
            dst[dst_pos] = low[0];
            dst_pos += 1;
            low = &low[1..];
            if low.is_empty() {
                /* HI - NHI equalled T - (NLO + NHI) when this function
                began.  Therefore HI must equal T now, and there is no
                need to copy from HI to T.  */
                break;
            }
        } else {
            dst[dst_pos] = dst[hi_start];
            dst_pos += 1;
            hi_start += 1;
            if hi_start == hi_end {
                while !low.is_empty() {
                    dst[dst_pos] = low[0];
                    dst_pos += 1;
                    low = &low[1..];
                }
                break;
            }
        }
    }
}

#[allow(dead_code)]
fn sort_lines(data: &[u8], items: &mut [Item], temp: &mut [Item], cmp: &mut LineCompList) {
    if items.len() == 2 {
        if cmp.comp_items(data, &items[0], &items[1]) == Ordering::Greater {
            items.swap(0, 1);
        }
    } else {
        let low = items.len() / 2;
        sort_lines(data, &mut items[low..], temp, cmp);
        if low == 1 {
            temp[0] = items[0]
        } else {
            sort_lines_temp(data, &mut items[..low], temp, cmp);
        }
        merge_lines(data, items, &temp[..low], low, items.len(), cmp);
    }
}

// Like sort_lines but output into temp, rather than sorting in place
#[allow(dead_code)]
fn sort_lines_temp(data: &[u8], items: &mut [Item], temp: &mut [Item], cmp: &mut LineCompList) {
    if items.len() == 2 {
        if cmp.comp_items(data, &items[0], &items[1]) == Ordering::Greater {
            temp[0] = items[1];
            temp[1] = items[0];
        } else {
            temp[0] = items[0];
            temp[1] = items[1];
        }
    } else {
        let low = items.len() / 2;
        let items_len = items.len();
        sort_lines_temp(data, &mut items[low..], &mut temp[low..items_len], cmp);
        if low > 1 {
            sort_lines(data, &mut items[..low], temp, cmp);
        }
        merge_lines(data, temp, &items[..low], low, items_len, cmp);
    }
}

compare Items

Examples found in repository?
src/sort.rs (line 477)
468
469
470
471
472
473
474
475
476
477
478
479
    fn do_sort(&mut self) {
        if self.config.alt_sort {
            do_sort_lines(&self.data, &mut self.ptrs, &mut self.cmp);
        } else {
            self.ptrs
                .sort_by(|a, b| self.cmp.comp_items(&self.data, a, b));
        }
        if self.unique {
            self.ptrs
                .dedup_by(|a, b| self.cmp.equal_items(&self.data, a, b));
        }
    }

compare TextLines in the same file

Examples found in repository?
src/sort.rs (line 26)
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
    fn compare(&mut self, a: usize, b: usize) -> Ordering {
        self.cmp
            .comp_cols(self.open[a].curr_line(), self.open[b].curr_line())
            .reverse()
    }
    fn equal(&mut self, a: &TextLine, b: usize) -> bool {
        self.cmp.equal_cols(a, self.open[b].curr_line())
    }
}

/// sort configuration
#[derive(Copy, Clone, Debug, Default)]
pub struct SortConfig {
    /// use a different sort algorithm
    pub alt_sort: bool,
    /// use a different merge algorithm
    pub alt_merge: bool,
}

impl SortConfig {
    /// merge all the files into w, using tmp
    pub fn merge_t(
        &self,
        in_files: &[String],
        cmp: &mut LineCompList,
        w: impl Write,
        unique: bool,
        tmp: &TempDir,
    ) -> Result<()> {
        eprintln!("Merging");
        if self.alt_merge {
            self.merge_t1(in_files, cmp, w, unique, tmp)
        } else {
            self.merge_t2(in_files, cmp, w, unique, tmp)
        }
    }

    /// merge all the files into w, using tmp
    pub fn merge_t2(
        &self,
        in_files: &[String],
        cmp: &mut LineCompList,
        mut w: impl Write,
        unique: bool,
        _tmp: &TempDir,
    ) -> Result<()> {
        if in_files.is_empty() {
            return Ok(());
        }
        if in_files.len() == 1 && !unique {
            let r = get_reader(&in_files[0])?;
            return copy(r.0, w);
        }
        let mc = Rc::new(RefCell::new(MergeContext {
            open: Vec::with_capacity(in_files.len()),
            cmp,
        }));
        let mut heap = BinaryHeap::new_by(|a: &usize, b: &usize| mc.borrow_mut().compare(*a, *b));
        {
            let mut mcm = mc.borrow_mut();
            for x in in_files {
                mcm.open.push(Reader::new_open2(x)?);
            }
            if !mcm.cmp.need_split() {
                for x in &mut mcm.open {
                    x.do_split(false);
                }
            }
            // FIXME -- Check Header
            if mcm.open[0].has_header() {
                w.write_all(mcm.open[0].header().line.as_bytes())?;
            }
        }
        for i in 0..in_files.len() {
            if !mc.borrow().open[i].is_done() {
                heap.push(i)
            }
        }
        if unique {
            if heap.is_empty() {
                return Ok(());
            }
            let first = heap.pop().unwrap();
            let mut prev = mc.borrow().open[first].curr_line().clone();
            if !mc.borrow_mut().open[first].getline()? {
                heap.push(first);
            }
            w.write_all(prev.line())?;

            while !heap.is_empty() {
                if let Some(x) = heap.pop() {
                    let eq = mc.borrow_mut().equal(&prev, x);
                    if !eq {
                        let mcm = mc.borrow();
                        w.write_all(mcm.open[x].curr_line().line())?;
                        prev.assign(mcm.open[x].curr_line());
                    }
                    if !mc.borrow_mut().open[x].getline()? {
                        heap.push(x);
                    }
                }
            }
        } else {
            while !heap.is_empty() {
                if let Some(x) = heap.pop() {
                    w.write_all(mc.borrow_mut().open[x].curr_line().line())?;
                    if !mc.borrow_mut().open[x].getline()? {
                        heap.push(x);
                    }
                }
            }
        }
        Ok(())
    }

    /// merge all the files into w, using tmp
    pub fn merge_t1(
        &self,
        in_files: &[String],
        cmp: &mut LineCompList,
        mut w: impl Write,
        unique: bool,
        _tmp: &TempDir,
    ) -> Result<()> {
        if in_files.is_empty() {
            return Ok(());
        }
        if in_files.len() == 1 && !unique {
            let r = get_reader(&in_files[0])?;
            return copy(r.0, w);
        }
        let mut open_files: Vec<Reader> = Vec::with_capacity(in_files.len());
        for x in in_files {
            open_files.push(Reader::new_open2(x)?);
        }
        if !cmp.need_split() {
            for x in &mut open_files {
                x.do_split(false);
            }
        }
        // FIXME -- Check Header
        if open_files[0].has_header() {
            w.write_all(open_files[0].header().line.as_bytes())?;
        }

        let nums: Vec<usize> = (0..open_files.len()).collect();
        let mut mm = MergeTreeItem::new_tree(&open_files, &nums);
        if unique {
            let x = mm.next(cmp, &mut open_files)?;
            if x.is_none() {
                return Ok(());
            }
            let x = x.unwrap();
            w.write_all(open_files[x].curr_line().line())?;
            let mut prev = open_files[x].curr_line().clone();
            loop {
                let x = mm.next(cmp, &mut open_files)?;
                if x.is_none() {
                    break;
                }
                let x = x.unwrap();
                if !cmp.equal_cols(&prev, open_files[x].curr_line()) {
                    w.write_all(open_files[x].curr_line().line())?;
                }
                prev.assign(open_files[x].curr_line());
            }
        } else {
            loop {
                let x = mm.next(cmp, &mut open_files)?;
                if x.is_none() {
                    break;
                }
                let x = x.unwrap();
                w.write_all(open_files[x].curr_line().line())?;
            }
        }
        Ok(())
    }

    /// merge all the files into w
    pub fn merge(
        &self,
        files: &[String],
        cmp: &mut LineCompList,
        w: impl Write,
        unique: bool,
    ) -> Result<()> {
        let tmp = TempDir::new()?;
        if self.alt_merge {
            self.merge_t1(files, cmp, w, unique, &tmp)
        } else {
            self.merge_t2(files, cmp, w, unique, &tmp)
        }
    }
    /*
        /// given two file names, merge them into output
        pub fn merge_2(
            &self,
            left: &str,
            right: &str,
            cmp: &mut LineCompList,
            mut w: impl Write,
            unique: bool,
        ) -> Result<()> {
            let mut left_file = Reader::new2();
            let mut right_file = Reader::new2();
            left_file.open(left)?;
            right_file.open(right)?;
            left_file.do_split(false);
            right_file.do_split(false);
            cmp.lookup(&left_file.names())?;

            // FIXME -- Check Header
            if left_file.has_header() {
                w.write_all(left_file.header().line.as_bytes())?;
            }

            if unique {
                let mut prev: Vec<u8> = Vec::new();
                while !left_file.is_done() && !right_file.is_done() {
                    let ord = cmp.comp_lines(left_file.curr().line(), right_file.curr().line());
                    if ord == Ordering::Less {
                        left_file.write(&mut w)?;
                        mem::swap(&mut prev, left_file.curr_mut().raw());
                        left_file.getline()?;
                    } else if ord == Ordering::Greater {
                        right_file.write(&mut w)?;
                        mem::swap(&mut prev, left_file.curr_mut().raw());
                        right_file.getline()?;
                    } else {
                        left_file.write(&mut w)?;
                        mem::swap(&mut prev, left_file.curr_mut().raw());
                        left_file.getline()?;
                        right_file.getline()?;
                    }
                    while !left_file.is_done() && cmp.equal_lines(left_file.curr().line(), &prev) {
                        left_file.getline()?;
                    }
                    while !right_file.is_done() && cmp.equal_lines(right_file.curr().line(), &prev) {
                        right_file.getline()?;
                    }
                }
            } else {
                while !left_file.is_done() && !right_file.is_done() {
                    let ord = cmp.comp_lines(left_file.curr().line(), right_file.curr().line());
                    // if Equal, write both lines
                    if ord != Ordering::Less {
                        right_file.write(&mut w)?;
                        right_file.getline()?;
                    }
                    if ord != Ordering::Greater {
                        left_file.write(&mut w)?;
                        left_file.getline()?;
                    }
                }
            }
            while !left_file.is_done() {
                left_file.write(&mut w)?;
                left_file.getline()?;
            }
            while !right_file.is_done() {
                right_file.write(&mut w)?;
                right_file.getline()?;
            }
            Ok(())
        }
    */
    /// Sort all the files together, into w
    pub fn sort<W: Write>(
        &self,
        files: &[String],
        cmp: LineCompList,
        w: &mut W,
        unique: bool,
    ) -> Result<()> // maybe return some useful stats?
    {
        let mut s = Sorter::new(cmp, 500000000, unique);
        for fname in files {
            s.add_file(fname, w)?;
        }
        s.finalize(w)?;
        //    s.no_del();
        Ok(())
    }
}

/// Large block of text and pointers to lines therein
#[allow(missing_debug_implementations)]
pub struct Sorter {
    config: SortConfig,
    ptrs: Vec<Item>,
    cmp: LineCompList,
    tmp: TempDir,
    tmp_files: Vec<String>,
    unique: bool,
    checker: HeaderChecker,

    // raw data. never resized smaller, so use data_used for real size
    data: Vec<u8>,

    // bytes of real data in Vec
    data_used: usize,

    // bytes of data referenced by ptrs
    // a.k.a. offset of first byte not referenced by ptrs
    // assert(data_calc <= data_used)
    data_calc: usize,

    // number of btes beyond data_calc, known to be free of newlines
    // to avoid N^2 craziness with long lines
    // assert(data_calc+data_nonl <= data_used)
    data_nonl: usize,
}

const MAX_DATA: usize = 0x0ffffff00;

impl Sorter {
    /// new Sorter
    pub fn new(cmp: LineCompList, max_alloc: usize, unique: bool) -> Self {
        let mut data_size = max_alloc / 2;
        if data_size > MAX_DATA {
            data_size = MAX_DATA;
        }
        let ptr_size = max_alloc / 2 / std::mem::size_of::<Item>();
        Self {
            config: SortConfig::default(),
            ptrs: Vec::with_capacity(ptr_size),
            data: Vec::with_capacity(data_size),
            cmp,
            tmp: TempDir::new().unwrap(), // FIXME - new should return Result
            tmp_files: Vec::new(),
            unique,
            checker: HeaderChecker::new(),
            data_used: 0,
            data_calc: 0,
            data_nonl: 0,
        }
    }

    fn check(&self) -> bool {
        debug_assert!(self.data_used <= self.data.len());
        debug_assert!(self.data_calc <= self.data_used);
        debug_assert!((self.data_calc + self.data_nonl) <= self.data_used);
        true
    }

    // number of bytes available to write
    fn avail(&self) -> usize {
        self.data.len() - self.data_used
    }

    // try to make N bytes available, return amount actually available
    fn prepare(&mut self, n: usize) -> usize {
        let mut nsize = self.data_used + n;
        if nsize > self.data.capacity() {
            nsize = self.data.capacity();
        }
        if self.data.len() < nsize {
            self.data.resize(nsize, 0);
        }
        let avail = self.avail();
        if avail < n {
            avail
        } else {
            n
        }
    }

    /// add some more data to be sorted.
    /// must be integer number of lines.
    pub fn add_data(&mut self, in_data: &[u8]) -> Result<()> {
        let sz = self.prepare(in_data.len());
        if sz != in_data.len() {
            eprintln!("Failed to prepare {}, only got {}", in_data.len(), sz);
            return err!("Badness");
        }
        self.data[self.data_used..self.data_used + in_data.len()].copy_from_slice(in_data);
        self.data_used += in_data.len();
        // FIXME - add newline
        Ok(())
    }
    /// Add another file's worth of data to the stream
    /// possibly writing temporary files
    pub fn add(&mut self, mut r: impl Read) -> Result<()> {
        loop {
            debug_assert!(self.check());
            const SIZE: usize = 16 * 1024;
            let sz = self.prepare(SIZE);
            debug_assert!(sz > 0);
            let nbytes = r.read(&mut self.data[self.data_used..self.data_used + sz])?;
            if nbytes == 0 {
                if self.data_used > 0 && self.data[self.data_used - 1] != b'\n' {
                    self.data[self.data_used] = b'\n';
                    self.data_used += 1;
                }
                return Ok(());
            }
            self.data_used += nbytes;
            // calc new stuff
            if self.data_used >= self.data.capacity() {
                self.calc();
                self.do_sort();
                self.write_tmp()?;
            }
        }
    }
    /// Populate 'ptrs' from 'data'
    fn calc(&mut self) {
        self.ptrs.clear();
        let mut item = Item::new();
        let mut off: usize = 0;
        for iter in self.data[0..self.data_used].iter().enumerate() {
            if iter.1 == &b'\n' {
                item.offset = off as u32;
                item.size_plus = (iter.0 - off + 1) as u32;
                off = iter.0 + 1;
                self.cmp.fill_cache_line(&mut item, &self.data);
                self.ptrs.push(item);
            }
        }
        self.data_calc = off;
    }

    /// write ptrs to tmp file
    fn write_tmp(&mut self) -> Result<()> {
        let mut tmp_file = self.tmp.path().to_owned();
        tmp_file.push(format!("sort_{}.txt", self.tmp_files.len()));
        let tmp_name = tmp_file.to_str().unwrap();
        let mut new_w = get_writer(tmp_name)?;
        for &x in &self.ptrs {
            new_w.write_all(x.get(&self.data))?;
        }
        self.tmp_files.push(tmp_name.to_string());
        self.ptrs.clear();
        let nsize = self.data.len() - self.data_calc;
        for i in 0..nsize {
            self.data[i] = self.data[self.data_calc + i];
        }
        self.data_used = nsize;
        self.data_calc = 0;
        Ok(())
    }

    /// sort and unique self.ptrs
    fn do_sort(&mut self) {
        if self.config.alt_sort {
            do_sort_lines(&self.data, &mut self.ptrs, &mut self.cmp);
        } else {
            self.ptrs
                .sort_by(|a, b| self.cmp.comp_items(&self.data, a, b));
        }
        if self.unique {
            self.ptrs
                .dedup_by(|a, b| self.cmp.equal_items(&self.data, a, b));
        }
    }
    /// All files have been added, write final results
    pub fn finalize(&mut self, mut w: impl Write) -> Result<()> {
        self.calc();
        self.do_sort();
        if self.tmp_files.is_empty() {
            for &x in &self.ptrs {
                w.write_all(x.get(&self.data))?;
            }
        } else {
            self.write_tmp()?;
            self.config
                .merge_t(&self.tmp_files, &mut self.cmp, w, self.unique, &self.tmp)?;
        }
        Ok(())
    }

    #[allow(dead_code)]
    fn no_del(self) {
        eprintln!(
            "Not deleting {}",
            self.tmp.into_path().into_os_string().to_string_lossy()
        );
    }
    /// add another file to be sorted
    pub fn add_file<W: Write>(&mut self, fname: &str, w: &mut W) -> Result<()> {
        let mut f = get_reader(fname)?;
        let mut first_line = Vec::new();
        let n = f.read_until(b'\n', &mut first_line)?;
        if n == 0 {
            return Ok(());
        }
        if self.checker.check(&first_line, fname)? {
            let s = make_header(&first_line);
            self.cmp.lookup(&s.vec())?;
            if is_cdx(&first_line) {
                w.write_all(&first_line)?;
            } else {
                self.add_data(&first_line)?;
            }
        }
        self.add(&mut *f)
    }
}

type NodeType = Box<MergeTreeItem>;
struct NodeData {
    left: NodeType,
    right: NodeType,
    left_data: Option<usize>,
    right_data: Option<usize>,
    //    done : bool, Optimization?
}
impl NodeData {
    fn new(left: NodeType, right: NodeType) -> Self {
        Self {
            left,
            right,
            left_data: None,
            right_data: None,
        }
    }
    fn left_cols<'a>(&self, files: &'a [Reader]) -> &'a TextLine {
        files[self.left_data.unwrap()].curr_line()
    }
    fn right_cols<'a>(&self, files: &'a [Reader]) -> &'a TextLine {
        files[self.right_data.unwrap()].curr_line()
    }
}
struct LeafData {
    file_num: usize,
    first: bool,
}

enum MergeTreeItem {
    Leaf(LeafData),
    Node(NodeData),
}

impl MergeTreeItem {
    fn new_tree(files: &[Reader], nums: &[usize]) -> Self {
        if nums.is_empty() {
            panic!("Can't make a MergeTreeItem from zero files")
        } else if nums.len() == 1 {
            Self::new_leaf(nums[0])
        } else {
            let mid = nums.len() / 2;
            Self::new_node(
                Box::new(Self::new_tree(files, &nums[..mid])),
                Box::new(Self::new_tree(files, &nums[mid..])),
            )
        }
    }
    fn new_node(left: NodeType, right: NodeType) -> Self {
        Self::Node(NodeData::new(left, right))
    }
    const fn new_leaf(r: usize) -> Self {
        Self::Leaf(LeafData {
            file_num: r,
            first: true,
        })
    }
    fn next(&mut self, cmp: &mut LineCompList, files: &mut [Reader]) -> Result<Option<usize>> {
        match self {
            Self::Leaf(r) => {
                if files[r.file_num].is_done() {
                    Ok(None)
                } else {
                    if r.first {
                        r.first = false;
                    } else if files[r.file_num].getline()? {
                        return Ok(None);
                    }
                    Ok(Some(r.file_num))
                }
            }
            Self::Node(n) => {
                if n.left_data.is_none() {
                    n.left_data = n.left.next(cmp, files)?;
                }
                if n.right_data.is_none() {
                    n.right_data = n.right.next(cmp, files)?;
                }
                if n.left_data.is_none() && n.right_data.is_none() {
                    Ok(None)
                } else if n.left_data.is_none() {
                    let tmp = n.right_data;
                    n.right_data = None;
                    Ok(tmp)
                } else if n.right_data.is_none() {
                    let tmp = n.left_data;
                    n.left_data = None;
                    Ok(tmp)
                } else {
                    let c = cmp.comp_cols(n.left_cols(files), n.right_cols(files));
                    if c == Ordering::Greater {
                        let tmp = n.right_data;
                        n.right_data = None;
                        Ok(tmp)
                    } else {
                        let tmp = n.left_data;
                        n.left_data = None;
                        Ok(tmp)
                    }
                }
            }
        }
    }
More examples
Hide additional examples
src/comp.rs (line 1914)
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
pub fn comp_check(f: &Reader, cmp: &mut LineCompList, unique: bool) -> bool {
    let c = cmp.comp_cols(f.prev_line(1), f.curr_line());
    let bad = match c {
        Ordering::Less => false,
        Ordering::Equal => unique,
        Ordering::Greater => true,
    };
    if c == Ordering::Equal && unique {
        eprintln!("Lines are equal when they should be unique.");
    } else if bad {
        eprintln!("Lines are out of order");
    }
    if bad {
        eprint!("{} : ", f.line_number() - 1);
        prerr_n(&[f.prev_line(1).line()]);
        eprint!("{} : ", f.line_number());
        prerr_n(&[f.curr_line().line()]);
    }
    bad
}

compare TextLines in different files

Examples found in repository?
src/comp.rs (line 1284)
1283
1284
1285
    pub fn comp_cols(&mut self, left: &TextLine, right: &TextLine) -> Ordering {
        self.comp_cols_n(left, right, 0, 0)
    }
More examples
Hide additional examples
src/join.rs (line 255)
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
    fn join_quick(&mut self, config: &JoinConfig) -> Result<()> {
        if !self.r[0].is_done() && !self.r[1].is_done() {
            let mut cmp = self
                .comp
                .comp_cols_n(self.r[0].curr(), self.r[1].curr(), 0, 1);
            'outer: loop {
                match cmp {
                    Ordering::Equal => loop {
                        self.out_cols[0].write(&mut *self.yes_match, &self.r)?;
                        for x in &self.out_cols[1..] {
                            self.yes_match.write_all(&[config.out_delim])?;
                            x.write(&mut *self.yes_match, &self.r)?;
                        }
                        self.yes_match.write_all(&[b'\n'])?;
                        if self.r[0].getline()? {
                            self.r[1].getline()?;
                            break 'outer;
                        }
                        cmp = self
                            .comp
                            .comp_cols_n(self.r[0].curr(), self.r[1].curr(), 0, 1);
                        if cmp != Ordering::Equal {
                            if self.r[1].getline()? {
                                break 'outer;
                            }
                            cmp = self
                                .comp
                                .comp_cols_n(self.r[0].curr(), self.r[1].curr(), 0, 1);
                            break;
                        }
                    },
                    Ordering::Less => {
                        if let Some(x) = &mut self.no_match[0] {
                            self.r[0].write(&mut x.0)?;
                        }
                        if self.r[0].getline()? {
                            break;
                        }
                        cmp = self
                            .comp
                            .comp_cols_n(self.r[0].curr(), self.r[1].curr(), 0, 1);
                    }
                    Ordering::Greater => {
                        if let Some(x) = &mut self.no_match[1] {
                            self.r[1].write(&mut x.0)?;
                        }
                        if self.r[1].getline()? {
                            break;
                        }
                        cmp = self
                            .comp
                            .comp_cols_n(self.r[0].curr(), self.r[1].curr(), 0, 1);
                    }
                }
            }
        }
        while !self.r[0].is_done() {
            if let Some(x) = &mut self.no_match[0] {
                self.r[0].write(&mut x.0)?;
            }
            self.r[0].getline()?;
        }
        while !self.r[1].is_done() {
            if let Some(x) = &mut self.no_match[1] {
                self.r[1].write(&mut x.0)?;
            }
            self.r[1].getline()?;
        }
        Ok(())
    }

compare TextLines in the same file

Examples found in repository?
src/sort.rs (line 30)
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
    fn equal(&mut self, a: &TextLine, b: usize) -> bool {
        self.cmp.equal_cols(a, self.open[b].curr_line())
    }
}

/// sort configuration
#[derive(Copy, Clone, Debug, Default)]
pub struct SortConfig {
    /// use a different sort algorithm
    pub alt_sort: bool,
    /// use a different merge algorithm
    pub alt_merge: bool,
}

impl SortConfig {
    /// merge all the files into w, using tmp
    pub fn merge_t(
        &self,
        in_files: &[String],
        cmp: &mut LineCompList,
        w: impl Write,
        unique: bool,
        tmp: &TempDir,
    ) -> Result<()> {
        eprintln!("Merging");
        if self.alt_merge {
            self.merge_t1(in_files, cmp, w, unique, tmp)
        } else {
            self.merge_t2(in_files, cmp, w, unique, tmp)
        }
    }

    /// merge all the files into w, using tmp
    pub fn merge_t2(
        &self,
        in_files: &[String],
        cmp: &mut LineCompList,
        mut w: impl Write,
        unique: bool,
        _tmp: &TempDir,
    ) -> Result<()> {
        if in_files.is_empty() {
            return Ok(());
        }
        if in_files.len() == 1 && !unique {
            let r = get_reader(&in_files[0])?;
            return copy(r.0, w);
        }
        let mc = Rc::new(RefCell::new(MergeContext {
            open: Vec::with_capacity(in_files.len()),
            cmp,
        }));
        let mut heap = BinaryHeap::new_by(|a: &usize, b: &usize| mc.borrow_mut().compare(*a, *b));
        {
            let mut mcm = mc.borrow_mut();
            for x in in_files {
                mcm.open.push(Reader::new_open2(x)?);
            }
            if !mcm.cmp.need_split() {
                for x in &mut mcm.open {
                    x.do_split(false);
                }
            }
            // FIXME -- Check Header
            if mcm.open[0].has_header() {
                w.write_all(mcm.open[0].header().line.as_bytes())?;
            }
        }
        for i in 0..in_files.len() {
            if !mc.borrow().open[i].is_done() {
                heap.push(i)
            }
        }
        if unique {
            if heap.is_empty() {
                return Ok(());
            }
            let first = heap.pop().unwrap();
            let mut prev = mc.borrow().open[first].curr_line().clone();
            if !mc.borrow_mut().open[first].getline()? {
                heap.push(first);
            }
            w.write_all(prev.line())?;

            while !heap.is_empty() {
                if let Some(x) = heap.pop() {
                    let eq = mc.borrow_mut().equal(&prev, x);
                    if !eq {
                        let mcm = mc.borrow();
                        w.write_all(mcm.open[x].curr_line().line())?;
                        prev.assign(mcm.open[x].curr_line());
                    }
                    if !mc.borrow_mut().open[x].getline()? {
                        heap.push(x);
                    }
                }
            }
        } else {
            while !heap.is_empty() {
                if let Some(x) = heap.pop() {
                    w.write_all(mc.borrow_mut().open[x].curr_line().line())?;
                    if !mc.borrow_mut().open[x].getline()? {
                        heap.push(x);
                    }
                }
            }
        }
        Ok(())
    }

    /// merge all the files into w, using tmp
    pub fn merge_t1(
        &self,
        in_files: &[String],
        cmp: &mut LineCompList,
        mut w: impl Write,
        unique: bool,
        _tmp: &TempDir,
    ) -> Result<()> {
        if in_files.is_empty() {
            return Ok(());
        }
        if in_files.len() == 1 && !unique {
            let r = get_reader(&in_files[0])?;
            return copy(r.0, w);
        }
        let mut open_files: Vec<Reader> = Vec::with_capacity(in_files.len());
        for x in in_files {
            open_files.push(Reader::new_open2(x)?);
        }
        if !cmp.need_split() {
            for x in &mut open_files {
                x.do_split(false);
            }
        }
        // FIXME -- Check Header
        if open_files[0].has_header() {
            w.write_all(open_files[0].header().line.as_bytes())?;
        }

        let nums: Vec<usize> = (0..open_files.len()).collect();
        let mut mm = MergeTreeItem::new_tree(&open_files, &nums);
        if unique {
            let x = mm.next(cmp, &mut open_files)?;
            if x.is_none() {
                return Ok(());
            }
            let x = x.unwrap();
            w.write_all(open_files[x].curr_line().line())?;
            let mut prev = open_files[x].curr_line().clone();
            loop {
                let x = mm.next(cmp, &mut open_files)?;
                if x.is_none() {
                    break;
                }
                let x = x.unwrap();
                if !cmp.equal_cols(&prev, open_files[x].curr_line()) {
                    w.write_all(open_files[x].curr_line().line())?;
                }
                prev.assign(open_files[x].curr_line());
            }
        } else {
            loop {
                let x = mm.next(cmp, &mut open_files)?;
                if x.is_none() {
                    break;
                }
                let x = x.unwrap();
                w.write_all(open_files[x].curr_line().line())?;
            }
        }
        Ok(())
    }
More examples
Hide additional examples
src/bin/cdx/uniq_main.rs (line 242)
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
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Select uniq lines.", args::FileCount::One);
    const A: [ArgSpec; 7] = [
        arg! {"agg", "a", "Col,Spec", "Merge value from this column, in place."},
        arg! {"agg-pre", "", "NewCol,SrcCol,Spec", "Merge value from SrcCol into new column, before other columns."},
        arg! {"agg-post", "", "NewCol,SrcCol,Spec", "Merge value from SrcCol into new column, after other columns."},
        arg! {"key", "k", "Spec", "How to compare adjacent lines"},
        arg! {"count", "c", "ColName,Position", "Write the count of matching line."},
        arg! {"which", "w", "(First,Last,Min,Max)[,LineCompare]", "Which of the matching lines should be printed."},
        arg! {"agg-help", "", "", "Print help for aggregators"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut agg = LineAggList::new();
    let mut comp = LineCompList::new();
    let mut count = Count::default();

    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "count" {
            count.get_count(&x.value)?;
        } else if x.name == "which" {
            count.get_which(&x.value)?;
        } else if x.name == "agg" {
            agg.push_replace(&x.value)?;
        } else if x.name == "agg-post" {
            agg.push_append(&x.value)?;
        } else if x.name == "agg-pre" {
            agg.push_prefix(&x.value)?;
        } else {
            unreachable!();
        }
    }

    assert_eq!(files.len(), 1);

    let mut f = Reader::new(&settings.text_in);
    f.open(&files[0])?;
    if f.is_empty() {
        return Ok(());
    }
    comp.lookup(&f.names())?;
    count.lookup(&f.names())?;
    let mut c_write = Writer::new(settings.text_out());
    if !agg.is_empty() {
        if count.pos == CountPos::Begin {
            agg.push_first_prefix(&format!("{},1,count", count.name))?;
        }
        if count.pos == CountPos::End {
            agg.push_append(&format!("{},1,count", count.name))?;
        }
        agg.lookup(&f.names())?;
        agg.fill(&mut c_write, f.header());
        c_write.lookup(&f.names())?;
    }

    let mut w = get_writer("-")?;
    if f.has_header() {
        let mut ch = ColumnHeader::new();
        if agg.is_empty() {
            if count.pos == CountPos::Begin {
                ch.push(&count.name)?;
            }
            ch.push_all(f.header())?;
            if count.pos == CountPos::End {
                ch.push(&count.name)?;
            }
        } else {
            c_write.add_names(&mut ch, f.header())?;
        }
        w.write_all(ch.get_head(&settings.text_out()).as_bytes())?;
    }
    if f.is_done() {
        return Ok(());
    }

    f.do_split(comp.need_split());
    let mut matches = 1;
    if !agg.is_empty() {
        agg.add(f.curr_line());
        let mut tmp = f.curr_line().clone();
        loop {
            if f.getline()? {
                c_write.write(&mut w.0, &tmp)?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                count.assign(&mut tmp, f.curr_line());
                agg.add(f.curr_line());
            } else {
                c_write.write(&mut w.0, &tmp)?;
                tmp.assign(f.curr_line());
                agg.reset();
                agg.add(f.curr_line());
            }
        }
    } else if count.which == Which::Last {
        loop {
            if f.getline()? {
                count.write(&mut w.0, matches, f.prev_line(1).line(), f.delim())?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                matches += 1;
            } else {
                count.write(&mut w.0, matches, f.prev_line(1).line(), f.delim())?;
                matches = 1;
            }
        }
    } else if count.which == Which::First && count.is_plain() {
        f.write_curr(&mut w.0)?;
        loop {
            if f.getline()? {
                break;
            }
            if !comp.equal_cols(f.prev_line(1), f.curr_line()) {
                f.write_curr(&mut w.0)?;
            }
        }
    } else {
        let mut tmp = f.curr_line().clone();
        loop {
            if f.getline()? {
                count.write(&mut w.0, matches, tmp.line(), f.delim())?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                count.assign(&mut tmp, f.curr_line());
                matches += 1;
            } else {
                count.write(&mut w.0, matches, tmp.line(), f.delim())?;
                tmp.assign(f.curr_line());
                matches = 1;
            }
        }
    }
    Ok(())
}

compare TextLines in different files

Examples found in repository?
src/comp.rs (line 1304)
1303
1304
1305
    pub fn equal_cols(&mut self, left: &TextLine, right: &TextLine) -> bool {
        self.equal_cols_n(left, right, 0, 0)
    }

compare liness from the same

compare lines from different files

Examples found in repository?
src/comp.rs (line 1323)
1322
1323
1324
    pub fn comp_lines(&mut self, left: &[u8], right: &[u8]) -> Ordering {
        self.comp_lines_n(left, right, 0, 0)
    }

compare lines from the same file

compare lines from different files

Examples found in repository?
src/comp.rs (line 1343)
1342
1343
1344
    pub fn equal_lines(&mut self, left: &[u8], right: &[u8]) -> bool {
        self.equal_lines_n(left, right, 0, 0)
    }

resolve named columns

Examples found in repository?
src/sort.rs (line 513)
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
    pub fn add_file<W: Write>(&mut self, fname: &str, w: &mut W) -> Result<()> {
        let mut f = get_reader(fname)?;
        let mut first_line = Vec::new();
        let n = f.read_until(b'\n', &mut first_line)?;
        if n == 0 {
            return Ok(());
        }
        if self.checker.check(&first_line, fname)? {
            let s = make_header(&first_line);
            self.cmp.lookup(&s.vec())?;
            if is_cdx(&first_line) {
                w.write_all(&first_line)?;
            } else {
                self.add_data(&first_line)?;
            }
        }
        self.add(&mut *f)
    }
More examples
Hide additional examples
src/bin/cdx/binsearch_main.rs (line 158)
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Search sorted files.", args::FileCount::Many);
    const A: [ArgSpec; 5] = [
        arg! {"key", "k", "Spec", "How to compare value to lines"},
        arg! {"filename", "H", "ColName:Parts", "Prefix output lines with file name."},
        arg! {"context", "C", "before,after",  "print lines of context around matches"},
        arg! {"sub-delim", "s", "Char",  "Delimiter between keys for multi-column searches"},
        arg_pos! {"pattern", "search string",  "Search for this string in each file"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut filename: Option<FileNameColumn> = None;
    let mut context = Context::new();
    let mut subdelim = b',';
    let mut comp = LineCompList::new();
    let mut pattern: Option<String> = None;

    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "filename" {
            if filename.is_some() {
                return err!("You cant use --filename twice");
            }
            let mut f = FileNameColumn::new();
            f.set(&x.value)?;
            filename = Some(f);
        } else if x.name == "context" {
            context.set(&x.value)?;
        } else if x.name == "subdelim" {
            if x.value.len() != 1 {
                return err!("--sub-delim value must be a single character");
            }
            subdelim = x.value.as_bytes()[0];
        } else if x.name == "pattern" {
            pattern = Some(x.value);
        } else {
            unreachable!();
        }
    }
    if pattern.is_none() {
        return err!("The pattern is required");
    }
    let pattern = pattern.unwrap();
    if files.is_empty() {
        return err!("At least one file is required : you can't binary search stdin.");
    }
    if comp.is_empty() {
        comp.add("1")?;
    }
    comp.set(pattern.as_bytes(), subdelim)?;
    let mut w = get_writer("-")?;
    let mut not_header: Vec<u8> = Vec::new();

    for f in &files {
        let m = MemMap::new(f)?;
        not_header.clear();
        if m.has_header() {
            if filename.is_none() {
                not_header.extend(m.header());
            } else {
                not_header.extend(b" CDX\t");
                not_header.extend(filename.as_ref().unwrap().name.as_bytes());
                not_header.extend(&m.header()[4..]);
            }
        }
        if settings.checker.check(&not_header, f)? {
            w.write_all(&not_header)?;
        }
        comp.lookup(&m.names())?;
        let (mut start, mut stop) = equal_range_n(m.get(), &mut comp);
        let (before, after) = context.get(start == stop);
        for _x in 0..before {
            if start == 0 {
                break;
            }
            start = find_prev(m.get(), start);
        }
        for _x in 0..after {
            stop = find_end(m.get(), stop);
        }
        if filename.is_none() {
            write_all_nl(&mut w.0, &m.get()[start..stop])?;
        } else {
            let file: &FileNameColumn = filename.as_ref().unwrap();
            while start < stop {
                let end = find_end(m.get(), start);
                w.write_all(f.tail_path_u8(file.tail, b'/').as_bytes())?;
                w.write_all(&[b'\t'])?;
                write_all_nl(&mut w.0, &m.get()[start..end])?;
                start = end;
            }
        }
    }
    Ok(())
}
src/bin/cdx/verify_main.rs (line 84)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Verify file contents.", args::FileCount::Many);
    const A: [ArgSpec; 10] = [
        arg! {"report", "r", "Number", "How many failures to report before exit."},
        arg! {"first", "f", "Op,Value", "'FirstLine Op Value' must be true. E.g LT,a for first line is less than 'a'."},
        arg! {"last", "l", "Op,Value", "'LastLine Op Value' must be true."},
        arg! {"key", "k", "Spec", "How to compare adjacent lines"},
        arg! {"sort", "s", "", "Check that the file is sorted."},
        arg! {"unique", "u", "", "Check that the file is sorted, with unique lines."},
        arg! {"pattern", "p", "Col,Spec,Pattern", "Select line where this col matches this pattern."},
        arg! {"show-matchers", "", "", "Print available matchers"},
        arg! {"show-const", "", "", "Print available constants"},
        arg! {"show-func", "", "", "Print available functions"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut list = LineMatcherList::new_with(Combiner::And);
    let mut comp = LineCompList::new();
    let mut do_sort = false;
    let mut do_unique = false;
    let mut max_fails = 5;
    let mut first: Option<CheckLine> = None;
    let mut last: Option<CheckLine> = None;

    for x in args {
        if x.name == "pattern" {
            list.push(&x.value)?;
        } else if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "or" {
            list.multi = Combiner::Or;
        } else if x.name == "fail" {
            max_fails = x.value.to_usize_whole(x.value.as_bytes(), "max fails")?;
        } else if x.name == "sort" {
            do_sort = true;
        } else if x.name == "first" {
            first = Some(CheckLine::new(&x.value)?);
        } else if x.name == "last" {
            last = Some(CheckLine::new(&x.value)?);
        } else if x.name == "unique" {
            do_sort = true;
            do_unique = true;
        } else if x.name == "show-const" {
            expr::show_const();
            return Ok(());
        } else if x.name == "show-func" {
            expr::show_func();
            return Ok(());
        } else {
            unreachable!();
        }
    }
    if comp.is_empty() {
        comp.add("")?;
    }

    let mut fails = 0;
    for x in &files {
        let mut f = Reader::new(&settings.text_in);
        f.open(x)?;
        if f.is_empty() {
            continue;
        }
        list.lookup(&f.names())?;
        comp.lookup(&f.names())?;
        if f.is_done() {
            continue;
        }
        if first.is_some()
            && !first.as_ref().unwrap().line_ok_verbose(
                f.curr_line(),
                &mut comp,
                f.line_number(),
            )?
        {
            fails += 1;
        }
        let num_cols = f.names().len();
        loop {
            let mut did_fail = false;
            if f.curr().len() != num_cols {
                eprintln!(
                    "Expected {num_cols} columns, but line {} of {} had {}",
                    f.line_number() + 1,
                    x,
                    f.curr().len()
                );
                did_fail = true;
            }
            if !list.ok_verbose(f.curr_line(), f.line_number(), x) {
                did_fail = true;
            }
            if f.getline()? {
                if last.is_some()
                    && !last.as_ref().unwrap().line_ok_verbose(
                        f.prev_line(1),
                        &mut comp,
                        f.line_number() - 1,
                    )?
                {
                    fails += 1;
                }
                break;
            }
            if do_sort {
                did_fail = did_fail || comp_check(&f, &mut comp, do_unique);
            }
            if did_fail {
                fails += 1;
                if fails >= max_fails {
                    break;
                }
            }
        }
        if fails > 0 {
            return cdx_err(CdxError::Silent);
        }
    }
    Ok(())
}
src/bin/cdx/uniq_main.rs (line 197)
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
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Select uniq lines.", args::FileCount::One);
    const A: [ArgSpec; 7] = [
        arg! {"agg", "a", "Col,Spec", "Merge value from this column, in place."},
        arg! {"agg-pre", "", "NewCol,SrcCol,Spec", "Merge value from SrcCol into new column, before other columns."},
        arg! {"agg-post", "", "NewCol,SrcCol,Spec", "Merge value from SrcCol into new column, after other columns."},
        arg! {"key", "k", "Spec", "How to compare adjacent lines"},
        arg! {"count", "c", "ColName,Position", "Write the count of matching line."},
        arg! {"which", "w", "(First,Last,Min,Max)[,LineCompare]", "Which of the matching lines should be printed."},
        arg! {"agg-help", "", "", "Print help for aggregators"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut agg = LineAggList::new();
    let mut comp = LineCompList::new();
    let mut count = Count::default();

    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "count" {
            count.get_count(&x.value)?;
        } else if x.name == "which" {
            count.get_which(&x.value)?;
        } else if x.name == "agg" {
            agg.push_replace(&x.value)?;
        } else if x.name == "agg-post" {
            agg.push_append(&x.value)?;
        } else if x.name == "agg-pre" {
            agg.push_prefix(&x.value)?;
        } else {
            unreachable!();
        }
    }

    assert_eq!(files.len(), 1);

    let mut f = Reader::new(&settings.text_in);
    f.open(&files[0])?;
    if f.is_empty() {
        return Ok(());
    }
    comp.lookup(&f.names())?;
    count.lookup(&f.names())?;
    let mut c_write = Writer::new(settings.text_out());
    if !agg.is_empty() {
        if count.pos == CountPos::Begin {
            agg.push_first_prefix(&format!("{},1,count", count.name))?;
        }
        if count.pos == CountPos::End {
            agg.push_append(&format!("{},1,count", count.name))?;
        }
        agg.lookup(&f.names())?;
        agg.fill(&mut c_write, f.header());
        c_write.lookup(&f.names())?;
    }

    let mut w = get_writer("-")?;
    if f.has_header() {
        let mut ch = ColumnHeader::new();
        if agg.is_empty() {
            if count.pos == CountPos::Begin {
                ch.push(&count.name)?;
            }
            ch.push_all(f.header())?;
            if count.pos == CountPos::End {
                ch.push(&count.name)?;
            }
        } else {
            c_write.add_names(&mut ch, f.header())?;
        }
        w.write_all(ch.get_head(&settings.text_out()).as_bytes())?;
    }
    if f.is_done() {
        return Ok(());
    }

    f.do_split(comp.need_split());
    let mut matches = 1;
    if !agg.is_empty() {
        agg.add(f.curr_line());
        let mut tmp = f.curr_line().clone();
        loop {
            if f.getline()? {
                c_write.write(&mut w.0, &tmp)?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                count.assign(&mut tmp, f.curr_line());
                agg.add(f.curr_line());
            } else {
                c_write.write(&mut w.0, &tmp)?;
                tmp.assign(f.curr_line());
                agg.reset();
                agg.add(f.curr_line());
            }
        }
    } else if count.which == Which::Last {
        loop {
            if f.getline()? {
                count.write(&mut w.0, matches, f.prev_line(1).line(), f.delim())?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                matches += 1;
            } else {
                count.write(&mut w.0, matches, f.prev_line(1).line(), f.delim())?;
                matches = 1;
            }
        }
    } else if count.which == Which::First && count.is_plain() {
        f.write_curr(&mut w.0)?;
        loop {
            if f.getline()? {
                break;
            }
            if !comp.equal_cols(f.prev_line(1), f.curr_line()) {
                f.write_curr(&mut w.0)?;
            }
        }
    } else {
        let mut tmp = f.curr_line().clone();
        loop {
            if f.getline()? {
                count.write(&mut w.0, matches, tmp.line(), f.delim())?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                count.assign(&mut tmp, f.curr_line());
                matches += 1;
            } else {
                count.write(&mut w.0, matches, tmp.line(), f.delim())?;
                tmp.assign(f.curr_line());
                matches = 1;
            }
        }
    }
    Ok(())
}

resolve named columns in the given file

Examples found in repository?
src/comp.rs (line 1362)
1361
1362
1363
    pub fn lookup(&mut self, fieldnames: &[&str]) -> Result<()> {
        self.lookup_n(fieldnames, 0)
    }
More examples
Hide additional examples
src/join.rs (line 205)
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
    fn join(&mut self, config: &JoinConfig) -> Result<()> {
        if config.infiles.len() < 2 {
            return err!(
                "Join requires at least two input files, {} found",
                config.infiles.len()
            );
        }

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

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

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

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

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

do TextLines need their columns initialized

Examples found in repository?
src/sort.rs (line 87)
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
    pub fn merge_t2(
        &self,
        in_files: &[String],
        cmp: &mut LineCompList,
        mut w: impl Write,
        unique: bool,
        _tmp: &TempDir,
    ) -> Result<()> {
        if in_files.is_empty() {
            return Ok(());
        }
        if in_files.len() == 1 && !unique {
            let r = get_reader(&in_files[0])?;
            return copy(r.0, w);
        }
        let mc = Rc::new(RefCell::new(MergeContext {
            open: Vec::with_capacity(in_files.len()),
            cmp,
        }));
        let mut heap = BinaryHeap::new_by(|a: &usize, b: &usize| mc.borrow_mut().compare(*a, *b));
        {
            let mut mcm = mc.borrow_mut();
            for x in in_files {
                mcm.open.push(Reader::new_open2(x)?);
            }
            if !mcm.cmp.need_split() {
                for x in &mut mcm.open {
                    x.do_split(false);
                }
            }
            // FIXME -- Check Header
            if mcm.open[0].has_header() {
                w.write_all(mcm.open[0].header().line.as_bytes())?;
            }
        }
        for i in 0..in_files.len() {
            if !mc.borrow().open[i].is_done() {
                heap.push(i)
            }
        }
        if unique {
            if heap.is_empty() {
                return Ok(());
            }
            let first = heap.pop().unwrap();
            let mut prev = mc.borrow().open[first].curr_line().clone();
            if !mc.borrow_mut().open[first].getline()? {
                heap.push(first);
            }
            w.write_all(prev.line())?;

            while !heap.is_empty() {
                if let Some(x) = heap.pop() {
                    let eq = mc.borrow_mut().equal(&prev, x);
                    if !eq {
                        let mcm = mc.borrow();
                        w.write_all(mcm.open[x].curr_line().line())?;
                        prev.assign(mcm.open[x].curr_line());
                    }
                    if !mc.borrow_mut().open[x].getline()? {
                        heap.push(x);
                    }
                }
            }
        } else {
            while !heap.is_empty() {
                if let Some(x) = heap.pop() {
                    w.write_all(mc.borrow_mut().open[x].curr_line().line())?;
                    if !mc.borrow_mut().open[x].getline()? {
                        heap.push(x);
                    }
                }
            }
        }
        Ok(())
    }

    /// merge all the files into w, using tmp
    pub fn merge_t1(
        &self,
        in_files: &[String],
        cmp: &mut LineCompList,
        mut w: impl Write,
        unique: bool,
        _tmp: &TempDir,
    ) -> Result<()> {
        if in_files.is_empty() {
            return Ok(());
        }
        if in_files.len() == 1 && !unique {
            let r = get_reader(&in_files[0])?;
            return copy(r.0, w);
        }
        let mut open_files: Vec<Reader> = Vec::with_capacity(in_files.len());
        for x in in_files {
            open_files.push(Reader::new_open2(x)?);
        }
        if !cmp.need_split() {
            for x in &mut open_files {
                x.do_split(false);
            }
        }
        // FIXME -- Check Header
        if open_files[0].has_header() {
            w.write_all(open_files[0].header().line.as_bytes())?;
        }

        let nums: Vec<usize> = (0..open_files.len()).collect();
        let mut mm = MergeTreeItem::new_tree(&open_files, &nums);
        if unique {
            let x = mm.next(cmp, &mut open_files)?;
            if x.is_none() {
                return Ok(());
            }
            let x = x.unwrap();
            w.write_all(open_files[x].curr_line().line())?;
            let mut prev = open_files[x].curr_line().clone();
            loop {
                let x = mm.next(cmp, &mut open_files)?;
                if x.is_none() {
                    break;
                }
                let x = x.unwrap();
                if !cmp.equal_cols(&prev, open_files[x].curr_line()) {
                    w.write_all(open_files[x].curr_line().line())?;
                }
                prev.assign(open_files[x].curr_line());
            }
        } else {
            loop {
                let x = mm.next(cmp, &mut open_files)?;
                if x.is_none() {
                    break;
                }
                let x = x.unwrap();
                w.write_all(open_files[x].curr_line().line())?;
            }
        }
        Ok(())
    }
More examples
Hide additional examples
src/bin/cdx/uniq_main.rs (line 232)
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
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Select uniq lines.", args::FileCount::One);
    const A: [ArgSpec; 7] = [
        arg! {"agg", "a", "Col,Spec", "Merge value from this column, in place."},
        arg! {"agg-pre", "", "NewCol,SrcCol,Spec", "Merge value from SrcCol into new column, before other columns."},
        arg! {"agg-post", "", "NewCol,SrcCol,Spec", "Merge value from SrcCol into new column, after other columns."},
        arg! {"key", "k", "Spec", "How to compare adjacent lines"},
        arg! {"count", "c", "ColName,Position", "Write the count of matching line."},
        arg! {"which", "w", "(First,Last,Min,Max)[,LineCompare]", "Which of the matching lines should be printed."},
        arg! {"agg-help", "", "", "Print help for aggregators"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut agg = LineAggList::new();
    let mut comp = LineCompList::new();
    let mut count = Count::default();

    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "count" {
            count.get_count(&x.value)?;
        } else if x.name == "which" {
            count.get_which(&x.value)?;
        } else if x.name == "agg" {
            agg.push_replace(&x.value)?;
        } else if x.name == "agg-post" {
            agg.push_append(&x.value)?;
        } else if x.name == "agg-pre" {
            agg.push_prefix(&x.value)?;
        } else {
            unreachable!();
        }
    }

    assert_eq!(files.len(), 1);

    let mut f = Reader::new(&settings.text_in);
    f.open(&files[0])?;
    if f.is_empty() {
        return Ok(());
    }
    comp.lookup(&f.names())?;
    count.lookup(&f.names())?;
    let mut c_write = Writer::new(settings.text_out());
    if !agg.is_empty() {
        if count.pos == CountPos::Begin {
            agg.push_first_prefix(&format!("{},1,count", count.name))?;
        }
        if count.pos == CountPos::End {
            agg.push_append(&format!("{},1,count", count.name))?;
        }
        agg.lookup(&f.names())?;
        agg.fill(&mut c_write, f.header());
        c_write.lookup(&f.names())?;
    }

    let mut w = get_writer("-")?;
    if f.has_header() {
        let mut ch = ColumnHeader::new();
        if agg.is_empty() {
            if count.pos == CountPos::Begin {
                ch.push(&count.name)?;
            }
            ch.push_all(f.header())?;
            if count.pos == CountPos::End {
                ch.push(&count.name)?;
            }
        } else {
            c_write.add_names(&mut ch, f.header())?;
        }
        w.write_all(ch.get_head(&settings.text_out()).as_bytes())?;
    }
    if f.is_done() {
        return Ok(());
    }

    f.do_split(comp.need_split());
    let mut matches = 1;
    if !agg.is_empty() {
        agg.add(f.curr_line());
        let mut tmp = f.curr_line().clone();
        loop {
            if f.getline()? {
                c_write.write(&mut w.0, &tmp)?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                count.assign(&mut tmp, f.curr_line());
                agg.add(f.curr_line());
            } else {
                c_write.write(&mut w.0, &tmp)?;
                tmp.assign(f.curr_line());
                agg.reset();
                agg.add(f.curr_line());
            }
        }
    } else if count.which == Which::Last {
        loop {
            if f.getline()? {
                count.write(&mut w.0, matches, f.prev_line(1).line(), f.delim())?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                matches += 1;
            } else {
                count.write(&mut w.0, matches, f.prev_line(1).line(), f.delim())?;
                matches = 1;
            }
        }
    } else if count.which == Which::First && count.is_plain() {
        f.write_curr(&mut w.0)?;
        loop {
            if f.getline()? {
                break;
            }
            if !comp.equal_cols(f.prev_line(1), f.curr_line()) {
                f.write_curr(&mut w.0)?;
            }
        }
    } else {
        let mut tmp = f.curr_line().clone();
        loop {
            if f.getline()? {
                count.write(&mut w.0, matches, tmp.line(), f.delim())?;
                break;
            }
            if comp.equal_cols(f.prev_line(1), f.curr_line()) {
                count.assign(&mut tmp, f.curr_line());
                matches += 1;
            } else {
                count.write(&mut w.0, matches, tmp.line(), f.delim())?;
                tmp.assign(f.curr_line());
                matches = 1;
            }
        }
    }
    Ok(())
}

fill Item’s cache

fill Item’s cache

Examples found in repository?
src/sort.rs (line 440)
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
    fn calc(&mut self) {
        self.ptrs.clear();
        let mut item = Item::new();
        let mut off: usize = 0;
        for iter in self.data[0..self.data_used].iter().enumerate() {
            if iter.1 == &b'\n' {
                item.offset = off as u32;
                item.size_plus = (iter.0 - off + 1) as u32;
                off = iter.0 + 1;
                self.cmp.fill_cache_line(&mut item, &self.data);
                self.ptrs.push(item);
            }
        }
        self.data_calc = off;
    }

get the value previously set

Examples found in repository?
src/util.rs (line 2023)
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
    pub fn line_ok_verbose(
        &self,
        line: &TextLine,
        comp: &mut LineCompList,
        line_num: usize,
    ) -> bool {
        if !self.invert().line_ok(line, comp) {
            eprint!("Line {} : ", line_num);
            prerr_n(&[&line.line]);
            eprint!("should have been {:?} ", self);
            prerr_n(&[comp.get_value()]);
            eprintln!(" but wasn't");
            false
        } else {
            true
        }
    }

set value fo later comparison

Examples found in repository?
src/util.rs (line 2197)
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
    pub fn line_ok_verbose(
        &self,
        line: &TextLine,
        comp: &mut LineCompList,
        line_num: usize,
    ) -> Result<bool> {
        comp.set(self.val.as_bytes(), b',')?;
        Ok(self.op.line_ok_verbose(line, comp, line_num))
    }
    /// compare line OP text, return true if match
    pub fn line_ok(&self, line: &TextLine, comp: &mut LineCompList) -> Result<bool> {
        comp.set(self.val.as_bytes(), b',')?;
        let ret = self.op.line_ok(line, comp);
        if !ret {
            return Ok(false);
        }
        match self.op2 {
            None => Ok(true),
            Some(o) => {
                comp.set(self.val2.as_ref().unwrap().as_bytes(), b',')?;
                Ok(o.line_ok(line, comp))
            }
        }
    }
More examples
Hide additional examples
src/bin/cdx/binsearch_main.rs (line 139)
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
pub fn main(argv: &[String], settings: &mut Settings) -> Result<()> {
    let prog = args::ProgSpec::new("Search sorted files.", args::FileCount::Many);
    const A: [ArgSpec; 5] = [
        arg! {"key", "k", "Spec", "How to compare value to lines"},
        arg! {"filename", "H", "ColName:Parts", "Prefix output lines with file name."},
        arg! {"context", "C", "before,after",  "print lines of context around matches"},
        arg! {"sub-delim", "s", "Char",  "Delimiter between keys for multi-column searches"},
        arg_pos! {"pattern", "search string",  "Search for this string in each file"},
    ];
    let (args, files) = args::parse(&prog, &A, argv, settings)?;

    let mut filename: Option<FileNameColumn> = None;
    let mut context = Context::new();
    let mut subdelim = b',';
    let mut comp = LineCompList::new();
    let mut pattern: Option<String> = None;

    for x in args {
        if x.name == "key" {
            comp.add(&x.value)?;
        } else if x.name == "filename" {
            if filename.is_some() {
                return err!("You cant use --filename twice");
            }
            let mut f = FileNameColumn::new();
            f.set(&x.value)?;
            filename = Some(f);
        } else if x.name == "context" {
            context.set(&x.value)?;
        } else if x.name == "subdelim" {
            if x.value.len() != 1 {
                return err!("--sub-delim value must be a single character");
            }
            subdelim = x.value.as_bytes()[0];
        } else if x.name == "pattern" {
            pattern = Some(x.value);
        } else {
            unreachable!();
        }
    }
    if pattern.is_none() {
        return err!("The pattern is required");
    }
    let pattern = pattern.unwrap();
    if files.is_empty() {
        return err!("At least one file is required : you can't binary search stdin.");
    }
    if comp.is_empty() {
        comp.add("1")?;
    }
    comp.set(pattern.as_bytes(), subdelim)?;
    let mut w = get_writer("-")?;
    let mut not_header: Vec<u8> = Vec::new();

    for f in &files {
        let m = MemMap::new(f)?;
        not_header.clear();
        if m.has_header() {
            if filename.is_none() {
                not_header.extend(m.header());
            } else {
                not_header.extend(b" CDX\t");
                not_header.extend(filename.as_ref().unwrap().name.as_bytes());
                not_header.extend(&m.header()[4..]);
            }
        }
        if settings.checker.check(&not_header, f)? {
            w.write_all(&not_header)?;
        }
        comp.lookup(&m.names())?;
        let (mut start, mut stop) = equal_range_n(m.get(), &mut comp);
        let (before, after) = context.get(start == stop);
        for _x in 0..before {
            if start == 0 {
                break;
            }
            start = find_prev(m.get(), start);
        }
        for _x in 0..after {
            stop = find_end(m.get(), stop);
        }
        if filename.is_none() {
            write_all_nl(&mut w.0, &m.get()[start..stop])?;
        } else {
            let file: &FileNameColumn = filename.as_ref().unwrap();
            while start < stop {
                let end = find_end(m.get(), start);
                w.write_all(f.tail_path_u8(file.tail, b'/').as_bytes())?;
                w.write_all(&[b'\t'])?;
                write_all_nl(&mut w.0, &m.get()[start..end])?;
                start = end;
            }
        }
    }
    Ok(())
}

compare my value to this line

Examples found in repository?
src/util.rs (line 2032)
2031
2032
2033
2034
    pub fn line_ok(&self, line: &TextLine, comp: &mut LineCompList) -> bool {
        let o = comp.comp_self_cols(line);
        self.ord_ok(o)
    }

compare my value to this line

compare my value to this line

Examples found in repository?
src/binsearch.rs (line 153)
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
pub fn lower_bound_n(data: &[u8], comp: &mut LineCompList) -> (usize, usize) {
    let mut trapped = false; // to exit a possible infinite loop
    let mut begin: usize = 0; // start of range under consideration
    let mut end: usize = data.len(); // end of range under consideration
    while begin < end {
        // find start and stop of a line in the middle
        let mut start = if trapped {
            begin
        } else {
            find_end(data, (end + begin - 1) / 2)
        };

        // if we hit end of buffer, back up from middle instead
        let stop = if start == end {
            let new_stop = start;
            start = find_start(data, (end + begin - 1) / 2);
            new_stop
        } else {
            find_end(data, start)
        };
        // data[start..stop] is one whole line, roughly in the middle of data[begin..end]
        match comp.comp_self_line(&data[start..stop]) {
            Ordering::Equal => {
                if start == begin {
                    return (start, stop);
                }
                trapped = stop == end;
                end = stop;
            }
            Ordering::Less => {
                end = start;
            }
            Ordering::Greater => {
                begin = stop;
            }
        };
    }
    (begin, end)
}

/// return start of first line that is greater than comp
pub fn upper_bound_n(data: &[u8], comp: &mut LineCompList) -> usize {
    let mut begin: usize = 0; // start of range under consideration
    let mut end: usize = data.len(); // end of range under consideration
    while begin < end {
        // find start and stop of a line in the middle
        let mut start = find_end(data, (end + begin - 1) / 2);

        // if we hit end of buffer, back up from middle instead
        let stop = if start == end {
            let new_stop = start;
            start = find_start(data, (end + begin - 1) / 2);
            new_stop
        } else {
            find_end(data, start)
        };
        // data[start..stop] is one whole line, roughly in the middle of data
        if comp.comp_self_line(&data[start..stop]) == Ordering::Less {
            end = start;
        } else {
            begin = stop;
        }
    }
    debug_assert!(begin == end);
    begin
}

compare my value to this line

Trait Implementations

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

Returns the argument unchanged.

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

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

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

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

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