whittle 1.0.0

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

use super::*;

/// Terminal classification of a hit: which end, if any, it trims.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Terminal {
    /// Trims the 5' end.
    Five,
    /// Trims the 3' end.
    Three,
    /// Covered by both end zones with a real flank on each side: excise the
    /// adapter span and keep both flanks. See `classify_terminal`.
    Excise,
    /// Trims neither end.
    None,
}

/// Emits a trace event for one adapter hit: the sequence, its span, its edit
/// cost, and the action taken (a terminal trim, an excision, or none).
pub(super) fn trace_hit(
    name: &str,
    start: usize,
    end: usize,
    cost: usize,
    action: Option<HitAction>,
) {
    tracing::trace!(
        adapter = name,
        start,
        end,
        cost,
        action = match action {
            Some(HitAction::TrimFivePrime) => "trim 5'",
            Some(HitAction::TrimThreePrime) => "trim 3'",
            Some(HitAction::Excise) => "excise and split",
            None => "no action",
        },
        "Adapter hit"
    );
}

/// What the trimmer did with an accepted adapter hit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum HitAction {
    /// Terminal hit at the 5' end: the keep-boundary moved inward past it.
    TrimFivePrime,
    /// Terminal hit at the 3' end.
    TrimThreePrime,
    /// Interior hit: the span is cut out and both flanks are kept.
    Excise,
}

/// Returns the end nearer to a hit at `[start, end)` in a length-`n` window.
pub(super) fn nearer_end(start: usize, end: usize, n: usize) -> Terminal {
    if start <= n - end {
        Terminal::Five
    } else {
        Terminal::Three
    }
}

/// Classifies a hit at window coordinates `[start, end)` in a length-`n`
/// window by geometry alone.
///
/// A hit inside one end zone trims that end. Every search is
/// reverse-complement aware and a rear adapter is the reverse complement of
/// its front adapter, so which catalog entry matched says nothing about which
/// end the hit is at. A hit covered by both end zones (`n <= end_size + hit
/// length`) trims toward an end whose outboard flank is at most `FLANK_SLACK`
/// (the nearer one when both are), and otherwise becomes `Excise`: cut out the
/// adapter, keep both flanks, as a central chimera junction needs.
pub(super) fn classify_terminal(start: usize, end: usize, n: usize, end_size: usize) -> Terminal {
    let in_head = start <= end_size;
    let in_tail = end >= n.saturating_sub(end_size);
    match (in_head, in_tail) {
        (true, true) => match (start <= FLANK_SLACK, n - end <= FLANK_SLACK) {
            (false, false) => Terminal::Excise,
            (true, false) => Terminal::Five,
            (false, true) => Terminal::Three,
            (true, true) => nearer_end(start, end, n),
        },
        (true, false) => Terminal::Five,
        (false, true) => Terminal::Three,
        (false, false) => Terminal::None,
    }
}

/// Classifies a hit for ends-only mode: splitting is disabled, so an `Excise`
/// outcome of `classify_terminal` resolves to a terminal trim toward the nearer
/// end, and every other outcome is unchanged.
pub(super) fn ends_only_terminal(start: usize, end: usize, n: usize, end_size: usize) -> Terminal {
    match classify_terminal(start, end, n, end_size) {
        Terminal::Excise => nearer_end(start, end, n),
        other => other,
    }
}

/// Where a hit was found. Each site acts on the outcomes it owns, so a hit
/// that the head and tail windows both contain (they overlap on a read shorter
/// than twice their reach) is applied and reported once.
///
/// Every 5' trim and every excision lies inside the head window and every 3'
/// trim inside the tail window: a hit reaching an end zone starts or ends within
/// `end_size` of that end and spans at most `len + k_end` bases.
#[derive(Debug, Clone, Copy)]
pub(super) enum Site {
    /// `[0, end_size + len + k_end)`: owns 5' trims and excisions.
    Head,
    /// `[n - (end_size + len + k_end), n)`: owns 3' trims. `head_end` is where
    /// the head window stopped, so hits before it are traced there only.
    Tail { head_end: usize },
    /// A candidate window searched at `k_mid`: owns interior excisions.
    Interior,
}

/// Returns the head end and tail start for a `len`-base adapter at budget
/// `k_end`. Each window covers `end_size` bases plus the longest alignment,
/// `len + k_end`, so it holds every hit that can reach its end zone.
pub(super) fn terminal_windows(
    n: usize,
    end_size: usize,
    len: usize,
    k_end: usize,
) -> (usize, usize) {
    let reach = end_size + len + k_end;
    (reach.min(n), n.saturating_sub(reach))
}

/// Accumulator for the accepted hits of one window: the keep boundaries and
/// interior cuts. Coordinates are those of the window, `[0, n)`.
pub(super) struct Keep<'a> {
    /// The configured adapters, for roles and names.
    pub(super) adapters: &'a [Adapter],
    /// Per-adapter edit budgets, for the anchoring of terminal hits.
    pub(super) budgets: &'a [Budget],
    /// Per-adapter `bounds_barcode`.
    panel_gates: &'a [bool],
    /// Per-adapter `CandidateIndex::split_classes`.
    split_classes: &'a [usize],
    /// Per-adapter `CandidateIndex::paired`.
    paired: &'a [bool],
    /// The read-length class of the window (`interior_class`).
    class: usize,
    /// Whether a `bounds_barcode` entry trimmed the 5' end.
    pub(super) five_bounded: bool,
    /// Whether a `bounds_barcode` entry trimmed the 3' end.
    pub(super) three_bounded: bool,
    /// Whether a bounded end skips the barcode panel search. Presence
    /// detection turns it off so every panel member is tallied.
    pub(super) gate_panels: bool,
    /// The run's error rate, which scales the budget of a partial hit.
    pub(super) error_rate: f64,
    /// Window length.
    pub(super) n: usize,
    /// Terminal zone depth, capped at `n`.
    pub(super) end_size: usize,
    /// Whether interior hits split the read.
    pub(super) split: bool,
    /// 5' keep boundary; advances inward on 5' trims.
    pub(super) lo: usize,
    /// 3' keep boundary; retreats inward on 3' trims.
    pub(super) hi: usize,
    /// Accepted excisions, merged by `into_cuts`.
    pub(super) interior: Vec<(usize, usize)>,
    /// The hit behind each excision in `interior`, for `refine`.
    excised: Vec<Applied>,
    /// The hits behind the applied 5' trims, for `refine`.
    five: Vec<Applied>,
    /// The hits behind the applied 3' trims, for `refine`.
    three: Vec<Applied>,
    /// 5' boundary set by trims that `refine` leaves as found.
    fixed_lo: usize,
    /// 3' boundary set by trims that `refine` leaves as found.
    fixed_hi: usize,
    /// The adapters whose hits trimmed or excised, for presence detection.
    pub(super) acted: Vec<usize>,
    /// Terminal trims above the `k_far` budget of their adapter, applied by
    /// `settle` once anchored.
    pub(super) deferred: Vec<Deferred>,
}

/// An applied hit, kept for `refine`: its span and the clips of its
/// alignment ends.
#[derive(Debug, Clone, Copy)]
pub(super) struct Applied {
    /// Index into the configured adapters.
    adapter_idx: usize,
    /// Hit start in window coordinates.
    start: usize,
    /// Hit end in window coordinates.
    end: usize,
    /// See `Hit::clip_start`.
    clip_start: usize,
    /// See `Hit::clip_end`.
    clip_end: usize,
    /// Whether the hit backs a `CandidateIndex::paired` excision by itself:
    /// it is one of a junction pair (`Keep::accept_pair`), or the whole
    /// marker primer of an amplicon library (`Keep::accept_standalone`).
    standalone: bool,
}

/// A terminal trim held until it is anchored at the read end or at an
/// accepted hit.
#[derive(Debug, Clone, Copy)]
pub(super) struct Deferred {
    /// Index into the configured adapters.
    pub(super) adapter_idx: usize,
    /// Hit start in window coordinates.
    pub(super) start: usize,
    /// Hit end in window coordinates.
    pub(super) end: usize,
    /// Edit cost of the hit.
    pub(super) cost: usize,
    /// See `Hit::clip_start`.
    pub(super) clip_start: usize,
    /// See `Hit::clip_end`.
    pub(super) clip_end: usize,
    /// `TrimFivePrime` or `TrimThreePrime`.
    pub(super) action: HitAction,
}

impl<'a> Keep<'a> {
    /// Creates an accumulator that keeps the whole `[0, n)` window. `split`
    /// selects the classification: with it, a hit covered by both end zones
    /// may excise; without it, every hit trims an end.
    pub(super) fn new(
        cfg: &'a AdapterConfig,
        index: &'a CandidateIndex,
        n: usize,
        split: bool,
    ) -> Self {
        Self {
            adapters: &cfg.adapters,
            budgets: &index.budgets,
            panel_gates: &index.panel_gates,
            split_classes: &index.split_classes,
            paired: &index.paired,
            class: interior_class(n),
            five_bounded: false,
            three_bounded: false,
            gate_panels: true,
            error_rate: cfg.error_rate,
            n,
            end_size: cfg.end_size.min(n),
            split,
            lo: 0,
            hi: n,
            interior: Vec::new(),
            excised: Vec::new(),
            five: Vec::new(),
            three: Vec::new(),
            fixed_lo: 0,
            fixed_hi: n,
            acted: Vec::new(),
            deferred: Vec::new(),
        }
    }

    /// Returns whether a partial hit is acceptable: enough of the pattern
    /// aligned, flush with the window end it hangs off, and within the edit
    /// budget of the aligned part alone. A whole-pattern hit always passes.
    pub(super) fn partial_hit_is_valid(&self, adapter_idx: usize, hit: Hit) -> bool {
        let overhang = hit.left_overhang + hit.right_overhang;
        if overhang == 0 {
            return true;
        }
        let overlap = self.adapters[adapter_idx].seq.len() - overhang;
        overlap >= MIN_OVERLAP
            && (hit.left_overhang == 0 || hit.start == 0)
            && (hit.right_overhang == 0 || hit.end == self.n)
            && self.residue_within_budget(hit, overlap)
    }

    /// Returns whether a hit whose `overlap` bases lie in the text is within
    /// the partial budget of that overlap, once the cost of the pattern bases
    /// beyond the text end is discounted.
    pub(super) fn residue_within_budget(&self, hit: Hit, overlap: usize) -> bool {
        let charged = overhang_cost(
            self.error_rate as f32,
            hit.left_overhang,
            hit.right_overhang,
        );
        hit.cost.saturating_sub(charged) <= partial_budget(self.error_rate, overlap)
    }

    /// Classifies one hit and applies it when `site` owns the outcome.
    pub(super) fn accept(&mut self, site: Site, adapter_idx: usize, hit: Hit) {
        let adapter = &self.adapters[adapter_idx];
        let Hit {
            start, end, cost, ..
        } = hit;
        if !self.partial_hit_is_valid(adapter_idx, hit) {
            return;
        }
        let terminal = if self.split {
            classify_terminal(start, end, self.n, self.end_size)
        } else {
            ends_only_terminal(start, end, self.n, self.end_size)
        };
        let action = match (site, terminal) {
            (Site::Head, Terminal::Five) => HitAction::TrimFivePrime,
            (Site::Head, Terminal::Excise) if self.splits(adapter_idx) => HitAction::Excise,
            (Site::Head, Terminal::Excise) => match nearer_end(start, end, self.n) {
                Terminal::Five => HitAction::TrimFivePrime,
                _ => HitAction::TrimThreePrime,
            },
            (Site::Tail { .. }, Terminal::Three) => HitAction::TrimThreePrime,
            // An interior hit within the flank slack of an end is residue of
            // that end rather than a junction.
            (Site::Interior, _) if start <= FLANK_SLACK => HitAction::TrimFivePrime,
            (Site::Interior, _) if self.n - end <= FLANK_SLACK => HitAction::TrimThreePrime,
            (Site::Interior, Terminal::None) if self.splits(adapter_idx) => HitAction::Excise,
            (Site::Interior, Terminal::None) => {
                trace_hit(&adapter.name, start, end, cost, None);
                return;
            },
            (Site::Head, Terminal::None) => {
                trace_hit(&adapter.name, start, end, cost, None);
                return;
            },
            (Site::Tail { head_end }, Terminal::None) => {
                if start >= head_end {
                    trace_hit(&adapter.name, start, end, cost, None);
                }
                return;
            },
            _ => return,
        };
        // A junction holds the whole adapter. An excision whose alignment
        // leaves `MIN_OVERLAP` or more bases to clip matched only part of the
        // pattern, as a genomic site of a primer inside a longer layer does.
        if action == HitAction::Excise && hit.clip_start + hit.clip_end >= MIN_OVERLAP {
            trace_hit(&adapter.name, start, end, cost, None);
            return;
        }
        let whole = hit.left_overhang + hit.right_overhang == 0;
        let terminal = matches!(site, Site::Head | Site::Tail { .. })
            && matches!(action, HitAction::TrimFivePrime | HitAction::TrimThreePrime);
        if whole && terminal && cost > self.budgets[adapter_idx].k_far {
            self.deferred.push(Deferred {
                adapter_idx,
                start,
                end,
                cost,
                clip_start: hit.clip_start,
                clip_end: hit.clip_end,
                action,
            });
            return;
        }
        self.apply(
            adapter_idx,
            start,
            end,
            cost,
            (hit.clip_start, hit.clip_end),
            action,
        );
    }

    /// Applies an accepted hit to the keep boundaries or the excisions.
    pub(super) fn apply(
        &mut self,
        adapter_idx: usize,
        start: usize,
        end: usize,
        cost: usize,
        (clip_start, clip_end): (usize, usize),
        action: HitAction,
    ) {
        trace_hit(
            &self.adapters[adapter_idx].name,
            start,
            end,
            cost,
            Some(action),
        );
        self.acted.push(adapter_idx);
        let applied = Applied {
            adapter_idx,
            start,
            end,
            clip_start,
            clip_end,
            standalone: false,
        };
        match action {
            HitAction::TrimFivePrime => {
                self.lo = self.lo.max(end);
                self.five.push(applied);
                self.five_bounded |= self.panel_gates[adapter_idx];
            },
            HitAction::TrimThreePrime => {
                self.hi = self.hi.min(start);
                self.three.push(applied);
                self.three_bounded |= self.panel_gates[adapter_idx];
            },
            HitAction::Excise => {
                self.interior.push((start, end));
                self.excised.push(applied);
            },
        }
    }

    /// Excises both hits of a junction pair: `closing`, of the entry at
    /// `closing_idx`, reads out of the insert before it, and `opening`, of the
    /// entry at `opening_idx`, reads into the insert after it; see
    /// `search_pairs`. A pair splits only when both hits lie outside both end
    /// zones and the flank slack of either read end, and when each aligns
    /// whole, leaving fewer than `MIN_OVERLAP` bases to clip.
    pub(super) fn accept_pair(
        &mut self,
        (closing_idx, closing): (usize, Hit),
        (opening_idx, opening): (usize, Hit),
    ) {
        let interior = |hit: &Hit| {
            hit.start > FLANK_SLACK
                && self.n - hit.end > FLANK_SLACK
                && classify_terminal(hit.start, hit.end, self.n, self.end_size) == Terminal::None
                && hit.clip_start + hit.clip_end < MIN_OVERLAP
        };
        if !self.split || !interior(&closing) || !interior(&opening) {
            return;
        }
        for (adapter_idx, hit) in [(closing_idx, closing), (opening_idx, opening)] {
            self.apply(
                adapter_idx,
                hit.start,
                hit.end,
                hit.cost,
                (hit.clip_start, hit.clip_end),
                HitAction::Excise,
            );
            if let Some(applied) = self.excised.last_mut() {
                applied.standalone = true;
            }
        }
    }

    /// Classifies an interior hit of the `CandidateIndex::paired` entry at
    /// `adapter_idx` over which the whole marker primer of an amplicon
    /// library aligns (`CandidateIndex::whole_primers`), as `accept` does,
    /// and lets an excision it makes split the window without a junction
    /// partner.
    pub(super) fn accept_standalone(&mut self, adapter_idx: usize, hit: Hit) {
        let excisions = self.excised.len();
        self.accept(Site::Interior, adapter_idx, hit);
        if self.excised.len() > excisions
            && let Some(applied) = self.excised.last_mut()
        {
            applied.standalone = true;
        }
    }

    /// Whether an interior hit of `adapter_idx` splits this window.
    pub(super) fn splits(&self, adapter_idx: usize) -> bool {
        self.split_classes[adapter_idx] > self.class
    }

    /// Trims the 5' end to `end` at a boundary `refine` keeps as found, for
    /// hits aligned against a masked copy of the window.
    pub(super) fn trim_five_fixed(&mut self, end: usize) {
        self.lo = self.lo.max(end);
        self.fixed_lo = self.fixed_lo.max(end);
    }

    /// Trims the 3' end to `start` at a boundary `refine` keeps as found.
    pub(super) fn trim_three_fixed(&mut self, start: usize) {
        self.hi = self.hi.min(start);
        self.fixed_hi = self.fixed_hi.min(start);
    }

    /// Moves every boundary to the inner end of the alignment that set it,
    /// dropping the clipped bases of the hit behind it; see `refine`. A
    /// boundary never moves outward. The 5' trims are visited in decreasing end
    /// order until a raw end falls at or below the best clipped one, and the 3'
    /// trims likewise.
    pub(super) fn refine(&mut self) {
        if !self.five.is_empty() {
            self.five.sort_unstable_by_key(|a| std::cmp::Reverse(a.end));
            let mut lo = self.fixed_lo;
            for a in &self.five {
                if a.end <= lo {
                    break;
                }
                lo = lo.max(a.end - a.clip_end);
            }
            self.lo = lo;
        }
        if !self.three.is_empty() {
            self.three.sort_unstable_by_key(|a| a.start);
            let mut hi = self.fixed_hi;
            for a in &self.three {
                if a.start >= hi {
                    break;
                }
                hi = hi.min(a.start + a.clip_start);
            }
            self.hi = hi;
        }
        for (cut, a) in self.interior.iter_mut().zip(&self.excised) {
            *cut = (a.start + a.clip_start, a.end - a.clip_end);
        }
    }

    /// Applies each deferred trim that is anchored: a 5' hit starting within
    /// `FLANK_SLACK` of the 5' keep boundary, or a 3' hit ending within
    /// `FLANK_SLACK` of the 3' boundary. An applied trim moves the boundary,
    /// which may anchor further deferred trims behind it.
    pub(super) fn settle(&mut self) {
        loop {
            let (lo, hi) = (self.lo, self.hi);
            let anchored = self.deferred.iter().position(|d| match d.action {
                HitAction::TrimFivePrime => d.start <= lo + FLANK_SLACK && d.end > lo,
                HitAction::TrimThreePrime => d.end + FLANK_SLACK >= hi && d.start < hi,
                HitAction::Excise => false,
            });
            let Some(i) = anchored else {
                return;
            };
            let d = self.deferred.swap_remove(i);
            self.apply(
                d.adapter_idx,
                d.start,
                d.end,
                d.cost,
                (d.clip_start, d.clip_end),
                d.action,
            );
        }
    }

    /// Whether the rest of a junction stack lies beside the
    /// `CandidateIndex::paired` excision `(s, e)`: an excision of another
    /// adapter that extends it by at least `MIN_OVERLAP` bases, within
    /// `FLANK_SLACK` of it, or within `end_size` for another paired entry. A
    /// junction holds the primers of both ends across the layers between
    /// them, where a genome holds no two such sites.
    fn backs(&self, (s, e): (usize, usize), adapter_idx: usize) -> bool {
        self.interior.iter().zip(&self.excised).any(|(&(t, u), b)| {
            let reach = if self.paired[b.adapter_idx] {
                self.end_size.max(FLANK_SLACK)
            } else {
                FLANK_SLACK
            };
            b.adapter_idx != adapter_idx
                && t <= e + reach
                && u + reach >= s
                && s.saturating_sub(t) + u.saturating_sub(e) >= MIN_OVERLAP
        })
    }

    /// Returns the keep boundaries and the excisions, refined and clipped to
    /// the boundaries, merged: two excisions overlapping, touching, or
    /// separated by at most `FLANK_SLACK` bases or fewer than `min_piece` bases
    /// become one, since the bases between them are junction residue or a
    /// piece the length filter would discard.
    pub(super) fn into_cuts(mut self, min_piece: usize) -> (usize, usize, Vec<(usize, usize)>) {
        self.settle();
        self.refine();
        for d in &self.deferred {
            trace_hit(
                &self.adapters[d.adapter_idx].name,
                d.start,
                d.end,
                d.cost,
                None,
            );
        }
        let backed: Vec<bool> = self
            .interior
            .iter()
            .zip(&self.excised)
            .map(|(&cut, a)| {
                !self.paired[a.adapter_idx] || a.standalone || self.backs(cut, a.adapter_idx)
            })
            .collect();
        let Keep {
            lo, hi, interior, ..
        } = self;
        if lo >= hi {
            return (lo, hi, Vec::new());
        }
        let mut cuts: Vec<(usize, usize)> = interior
            .into_iter()
            .zip(backed)
            .filter(|&(_, backed)| backed)
            .filter_map(|((s, e), _)| {
                let s = s.max(lo);
                let e = e.min(hi);
                (s < e).then_some((s, e))
            })
            .collect();
        cuts.sort_unstable();
        let mut merged: Vec<(usize, usize)> = Vec::new();
        for (s, e) in cuts {
            if let Some(last) = merged.last_mut() {
                let gap = s.saturating_sub(last.1);
                if s <= last.1 || gap <= FLANK_SLACK || gap < min_piece {
                    last.1 = last.1.max(e);
                    continue;
                }
            }
            merged.push((s, e));
        }
        (lo, hi, merged)
    }
}