tuc 1.3.0

When cut doesn't cut it
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use crate::bounds::{BoundOrFiller, Side, UserBounds, UserBoundsTrait};
use anyhow::{Result, bail};
use std::ops::Deref;
use std::str::FromStr;

#[derive(Debug, Clone)]
pub struct UserBoundsList {
    pub list: Vec<BoundOrFiller>,
    /// Optimization that we can use to stop searching for fields.
    /// It's available only when every bound uses positive indexes.
    /// When conditions do not apply, its value is `Side::Continue`.
    pub last_interesting_field: Side,
}

impl Deref for UserBoundsList {
    type Target = Vec<BoundOrFiller>;

    fn deref(&self) -> &Self::Target {
        &self.list
    }
}

impl From<Vec<BoundOrFiller>> for UserBoundsList {
    fn from(list: Vec<BoundOrFiller>) -> Self {
        let mut ubl = UserBoundsList {
            list,
            last_interesting_field: Side::with_pos_inf(),
        };

        let mut rightmost_bound: Option<Side> = None;
        let mut last_bound: Option<&mut UserBounds> = None;

        let is_sortable = ubl.is_sortable();

        ubl.list.iter_mut().for_each(|bof| {
            if let BoundOrFiller::Bound(b) = bof {
                if rightmost_bound.is_none() || *b.r() > rightmost_bound.unwrap() {
                    rightmost_bound = Some(*b.r());
                }

                last_bound = Some(b);
            }
        });

        if !is_sortable {
            rightmost_bound = None;
        }

        last_bound
            .expect("UserBoundsList must contain at least one UserBounds")
            .set_is_last(true);

        ubl.last_interesting_field = rightmost_bound
            .and_then(|x| if x.is_negative() { None } else { Some(x) })
            .unwrap_or(Side::with_pos_inf());
        ubl
    }
}

impl FromStr for UserBoundsList {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.trim().is_empty() {
            bail!("UserBoundsList must contain at least one UserBounds");
        }
        Ok(parse_bounds_list(s)?.into())
    }
}

impl UserBoundsList {
    /// Detect whether the list can be sorted.
    /// It can be sorted only if every bound
    /// has the same sign (all positive or all negative).
    pub fn is_sortable(&self) -> bool {
        let mut has_positive_idx = false;
        let mut has_negative_idx = false;
        self.get_userbounds_only().for_each(|b| {
            if b.l().is_negative() {
                has_negative_idx = true;
            } else {
                has_positive_idx = true;
            }

            if b.r().is_negative() {
                has_negative_idx = true;
            } else {
                has_positive_idx = true;
            }
        });

        !(has_negative_idx && has_positive_idx)
    }

    fn get_userbounds_only(&self) -> impl Iterator<Item = &UserBounds> + '_ {
        self.list.iter().flat_map(|b| match b {
            BoundOrFiller::Bound(x) => Some(x),
            _ => None,
        })
    }

    fn is_sorted(&self) -> bool {
        let mut prev_b: Option<&UserBounds> = None;
        for b in self.get_userbounds_only() {
            if prev_b.is_none() || prev_b <= Some(b) {
                prev_b = Some(b);
            } else {
                return false;
            }
        }

        true
    }

    fn has_negative_indices(&self) -> bool {
        self.get_userbounds_only()
            .any(|b| b.l().is_negative() || b.r().is_negative())
    }

    /// Check if the bounds in the list match the following conditions:
    /// - they are in ascending order
    /// - they use solely positive indices
    /// - they don't overlap (but they can be adjacent, e.g. 1:2,2,3)
    pub fn is_forward_only(&self) -> bool {
        self.is_sortable() && self.is_sorted() && !self.has_negative_indices()
    }

    /// Create a new UserBoundsList with every ranged bound converted
    /// into single-field bounds.
    ///
    /// ```rust
    /// # use tuc::bounds::{UserBoundsList, UserBoundsTrait};
    /// # use std::ops::Range;
    /// # use tuc::bounds::Side;
    /// # use std::str::FromStr;
    ///
    /// assert_eq!(
    ///   UserBoundsList::from_str("1:3,4,-2:").unwrap().unpack(6).list,
    ///   UserBoundsList::from_str("1,2,3,4,5,6").unwrap().list,
    /// );
    /// ```
    pub fn unpack(&self, num_fields: usize) -> UserBoundsList {
        let list: Vec<BoundOrFiller> = self
            .list
            .iter()
            .flat_map(|bof| match bof {
                // XXX how to do it using only iterators, no collect?
                BoundOrFiller::Bound(b) => b
                    .unpack(num_fields)
                    .into_iter()
                    .map(BoundOrFiller::Bound)
                    .collect(),
                BoundOrFiller::Filler(f) => vec![BoundOrFiller::Filler(f.clone())],
            })
            .collect();

        list.into()
    }

    /// Create a new UserBoundsList with every range complemented (inverted).
    pub fn complement(&self, num_fields: usize) -> Result<UserBoundsList> {
        let list: Vec<BoundOrFiller> = self
            .list
            .iter()
            .flat_map(|bof| match bof {
                // XXX how to do it using only iterators, no collect?
                BoundOrFiller::Bound(b) => anyhow::Ok(
                    b.complement(num_fields)?
                        .into_iter()
                        .map(BoundOrFiller::Bound)
                        .collect(),
                ),
                BoundOrFiller::Filler(f) => Ok(vec![BoundOrFiller::Filler(f.clone())]),
            })
            .flatten()
            .collect();

        if list.is_empty() {
            bail!("the complement is empty");
        }

        Ok(list.into())
    }
}

/**
 * Parse bound string. It can contain formatting elements or not.
 *
 * Valid bounds formats are e.g. 1 / -1 / 1:3 / :3 / 1: / 1,4
 * If '{' is present, the string is considered to be a format string:
 * in that case everything inside {} is considered a bound, and the rest
 * just some text to display when the bounds are found.
 * e.g. "Hello {1}, found {1:3} and {2,4}"
 */
pub fn parse_bounds_list(s: &str) -> Result<Vec<BoundOrFiller>> {
    if s.is_empty() {
        return Ok(Vec::new());
    }

    if s.contains(['{', '}']) {
        let mut bof: Vec<BoundOrFiller> = Vec::new();
        let mut inside_bound = false;
        let mut part_start = 0;

        let mut iter = s.char_indices().peekable();
        while let Some((idx, w0)) = iter.next() {
            let w1 = iter.peek().unwrap_or(&(0, 'x')).1;

            if w0 == w1 && (w0 == '{' || w0 == '}') {
                // escaped bracket, ignore it, we will replace it later
                iter.next();
            } else if w0 == '}' && !inside_bound {
                bail!("Field format error: missing opening parenthesis",);
            } else if w0 == '{' {
                // starting a new bound
                inside_bound = true;

                if idx - part_start > 0 {
                    bof.push(BoundOrFiller::Filler(
                        s[part_start..idx]
                            .replace("{{", "{")
                            .replace("}}", "}")
                            .replace("\\n", "\n")
                            .replace("\\t", "\t")
                            .into_bytes(),
                    ));
                }

                part_start = idx + 1;
            } else if w0 == '}' {
                // ending a bound
                inside_bound = false;

                // consider also comma separated bounds
                for maybe_bounds in s[part_start..idx].split(',') {
                    bof.push(BoundOrFiller::Bound(UserBounds::from_str(maybe_bounds)?));
                }

                part_start = idx + 1;
            }
        }

        if inside_bound {
            bail!("Field format error: missing closing parenthesis");
        } else if s.len() - part_start > 0 {
            bof.push(BoundOrFiller::Filler(
                s[part_start..]
                    .replace("{{", "{")
                    .replace("}}", "}")
                    .replace("\\n", "\n")
                    .replace("\\t", "\t")
                    .into_bytes(),
            ));
        }

        Ok(bof)
    } else {
        let k: Result<Vec<BoundOrFiller>, _> = s
            .split(',')
            .map(|x| UserBounds::from_str(x).map(BoundOrFiller::Bound))
            .collect();
        Ok(k?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn side_pos(l: usize) -> Side {
        Side::with_pos_value(l)
    }

    fn side_neg(l: usize) -> Side {
        Side::with_neg_value(l)
    }

    #[test]
    fn test_parse_bounds_list() {
        // do not replicate tests from test_user_bounds_from_str, focus on
        // multiple bounds, bounds with format, and special cases (empty/one)

        assert_eq!(parse_bounds_list("").unwrap(), Vec::new());

        assert_eq!(
            &parse_bounds_list(",").unwrap_err().to_string(),
            "Field format error: empty field"
        );

        assert_eq!(
            &parse_bounds_list("{").unwrap_err().to_string(),
            "Field format error: missing closing parenthesis"
        );

        assert_eq!(
            &parse_bounds_list("}").unwrap_err().to_string(),
            "Field format error: missing opening parenthesis"
        );

        assert_eq!(
            &parse_bounds_list("{1}{").unwrap_err().to_string(),
            "Field format error: missing closing parenthesis"
        );

        assert_eq!(
            &parse_bounds_list("{1}}").unwrap_err().to_string(),
            "Field format error: missing closing parenthesis"
        );

        assert_eq!(
            &parse_bounds_list("{{1}").unwrap_err().to_string(),
            "Field format error: missing opening parenthesis"
        );

        assert_eq!(
            parse_bounds_list("1").unwrap(),
            vec![BoundOrFiller::Bound(UserBounds::new(
                side_pos(0),
                side_pos(0)
            ))],
        );

        assert_eq!(
            parse_bounds_list("1:").unwrap(),
            vec![BoundOrFiller::Bound(UserBounds::default())],
        );

        assert_eq!(
            parse_bounds_list("1,2").unwrap(),
            vec![
                BoundOrFiller::Bound(UserBounds::new(side_pos(0), side_pos(0))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(1), side_pos(1))),
            ],
        );

        assert_eq!(
            parse_bounds_list("-1,1").unwrap(),
            vec![
                BoundOrFiller::Bound(UserBounds::new(side_neg(0), side_neg(0))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(0), side_pos(0))),
            ],
        );

        assert_eq!(
            parse_bounds_list("{1}").unwrap(),
            vec![BoundOrFiller::Bound(UserBounds::new(
                side_pos(0),
                side_pos(0)
            ))],
        );

        assert_eq!(
            parse_bounds_list("{1:2}").unwrap(),
            vec![BoundOrFiller::Bound(UserBounds::new(
                side_pos(0),
                side_pos(1)
            ))],
        );

        assert_eq!(
            parse_bounds_list("{1,2}").unwrap(),
            vec![
                BoundOrFiller::Bound(UserBounds::new(side_pos(0), side_pos(0))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(1), side_pos(1)))
            ],
        );

        assert_eq!(
            parse_bounds_list("hello {1,2} {{world}}").unwrap(),
            vec![
                BoundOrFiller::Filler("hello ".into()),
                BoundOrFiller::Bound(UserBounds::new(side_pos(0), side_pos(0))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(1), side_pos(1))),
                BoundOrFiller::Filler(" {world}".into()),
            ],
        );

        assert_eq!(
            parse_bounds_list("{1}😎{2}").unwrap(),
            vec![
                BoundOrFiller::Bound(UserBounds::new(side_pos(0), side_pos(0))),
                BoundOrFiller::Filler("😎".into()),
                BoundOrFiller::Bound(UserBounds::new(side_pos(1), side_pos(1)))
            ],
        );

        assert_eq!(
            parse_bounds_list("\\n\\t{{}}{1,2}\\n\\t{{}}").unwrap(),
            vec![
                BoundOrFiller::Filler("\n\t{}".into()),
                BoundOrFiller::Bound(UserBounds::new(side_pos(0), side_pos(0))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(1), side_pos(1))),
                BoundOrFiller::Filler("\n\t{}".into()),
            ],
        );
    }

    #[test]
    fn test_user_bounds_cannot_be_empty() {
        assert!(UserBoundsList::from_str("").is_err());
    }

    #[test]
    fn test_user_bounds_is_sortable() {
        assert!(UserBoundsList::from_str("1").unwrap().is_sortable());

        assert!(UserBoundsList::from_str("1,2").unwrap().is_sortable());

        assert!(UserBoundsList::from_str("3,2").unwrap().is_sortable());

        assert!(!UserBoundsList::from_str("-1,1").unwrap().is_sortable());

        assert!(UserBoundsList::from_str("-1,-2").unwrap().is_sortable());

        assert!(!UserBoundsList::from_str("-1:,:1").unwrap().is_sortable());
    }

    #[test]
    fn test_vec_of_bounds_is_sorted() {
        assert!(UserBoundsList::from_str("1").unwrap().is_sorted());

        assert!(UserBoundsList::from_str("1,2").unwrap().is_sorted());

        assert!(UserBoundsList::from_str("-2,-1").unwrap().is_sorted());

        assert!(UserBoundsList::from_str(":1,2:4,5:").unwrap().is_sorted());

        assert!(UserBoundsList::from_str("1,1:2").unwrap().is_sorted());

        assert!(UserBoundsList::from_str("1,1,2").unwrap().is_sorted());

        assert!(!UserBoundsList::from_str("1,2,1").unwrap().is_sorted());
    }

    #[test]
    fn test_vec_of_bounds_is_forward_only() {
        assert!(
            UserBoundsList::from_str("{1}foo{2}")
                .unwrap()
                .is_forward_only()
        );

        assert!(
            !UserBoundsList::from_str("{2}foo{1}")
                .unwrap()
                .is_forward_only()
        );
    }

    #[test]
    fn test_vec_of_bounds_can_unpack() {
        assert_eq!(
            UserBoundsList::from_str("1,:1,2:3,4:")
                .unwrap()
                .unpack(4)
                .list,
            vec![
                BoundOrFiller::Bound(UserBounds::new(side_pos(0), side_pos(0))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(0), side_pos(0))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(1), side_pos(1))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(2), side_pos(2))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(3), side_pos(3))),
            ]
        );

        assert_eq!(
            UserBoundsList::from_str("a{1:2}b").unwrap().unpack(4).list,
            vec![
                BoundOrFiller::Filler("a".into()),
                BoundOrFiller::Bound(UserBounds::new(side_pos(0), side_pos(0))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(1), side_pos(1))),
                BoundOrFiller::Filler("b".into()),
            ]
        );
    }

    #[test]
    fn test_vec_of_bounds_can_complement() {
        assert_eq!(
            UserBoundsList::from_str("1:2,2:3,5,-2")
                .unwrap()
                .complement(6)
                .unwrap()
                .list,
            vec![
                BoundOrFiller::Bound(UserBounds::new(side_pos(2), side_pos(5))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(0), side_pos(0))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(3), side_pos(5))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(0), side_pos(3))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(5), side_pos(5))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(0), side_pos(3))),
                BoundOrFiller::Bound(UserBounds::new(side_pos(5), side_pos(5))),
            ]
        );

        assert_eq!(
            UserBoundsList::from_str("1:")
                .unwrap()
                .complement(6)
                .err()
                .map(|x| x.to_string()),
            Some("the complement is empty".to_owned())
        );
    }
}