streampile 0.2.0

Forward-only pileups streamed from coordinate-sorted BAM records
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
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
use std::collections::VecDeque;
use std::io;
use std::mem;

use bstr::{BStr, ByteSlice};
use noodles::sam::{self, alignment::record::Cigar as _, alignment::record::Flags};

use crate::auxiliary;
use crate::error::{Error, Result};
use crate::footprint::Footprint;
use crate::pileup::{Derived, LiveRecord, Pileup, RawEntry, record_name};
use crate::source::{AlignmentRecord, RecordSource};

/// Secondary, QC-fail, duplicate, and supplementary reads, which are left out by default.
pub const DEFAULT_EXCLUDE_FLAGS: Flags = Flags::from_bits_retain(0xF00);

/// The default minimum base quality of a pileup's filtered views and template votes, as in pysam's
/// `pileup()` and `samtools mpileup`.
pub const DEFAULT_MIN_BASE_QUALITY: u8 = 13;

const UNPLACED: usize = usize::MAX;

type ReadFilter<'f, R> = Box<dyn FnMut(&R) -> io::Result<bool> + Send + 'f>;
type Tap<'f, R> = Box<dyn FnMut(R) -> io::Result<()> + Send + 'f>;

#[derive(Clone, Debug)]
struct Options {
    min_mapping_quality: u8,
    exclude_flags: Flags,
    min_base_quality: u8,
    proper_pairs_only: bool,
    aux_tags: Vec<[u8; 2]>,
}

impl Options {
    /// Whether a record passes the flag, mapping-quality, and proper-pair filters.
    fn passes(&self, flags: Flags, mapping_quality: u8) -> bool {
        let paired = flags.is_properly_segmented() || !self.proper_pairs_only;
        paired
            && passes(
                flags,
                mapping_quality,
                self.exclude_flags,
                self.min_mapping_quality,
            )
    }
}

/// Whether a read is mapped, has none of the flags excluded, and has at least the lowest mapping
/// quality allowed, as builders and tabulate filter reads. A read with no mapping quality (255)
/// passes every floor.
pub(crate) fn passes(
    flags: Flags,
    mapping_quality: u8,
    exclude_flags: Flags,
    min_mapping_quality: u8,
) -> bool {
    !(flags.is_unmapped()
        || flags.intersects(exclude_flags)
        || mapping_quality < min_mapping_quality)
}

/// Whether a record with a 0-based start, -1 for none, is piled up wherever it spans: placed on a
/// contig, passing the flag, mapping-quality, and proper-pair filters, placed with a
/// reference-consuming CIGAR operator, which fills `footprint`, and then passing the read filter.
fn admits<R: AlignmentRecord>(
    options: &Options,
    read_filter: Option<&mut ReadFilter<'_, R>>,
    record: &R,
    start: i64,
    footprint: &mut Footprint,
) -> Result<bool> {
    let bam = record.bam();
    let mapping_quality = bam.mapping_quality().map_or(255, u8::from);
    if bam.reference_sequence_id().is_none()
        || start < 0
        || !options.passes(bam.flags(), mapping_quality)
    {
        return Ok(false);
    }
    let placed = footprint
        .fill(start, bam.cigar().as_bytes(), bam.sequence().len())
        .map_err(|source| Error::InvalidRecord {
            name: record_name(bam),
            source,
        })?;
    Ok(placed
        && match read_filter {
            Some(read_filter) => read_filter(record)?,
            None => true,
        })
}

impl Default for Options {
    fn default() -> Self {
        Self {
            min_mapping_quality: 0,
            exclude_flags: DEFAULT_EXCLUDE_FLAGS,
            min_base_quality: DEFAULT_MIN_BASE_QUALITY,
            proper_pairs_only: false,
            aux_tags: Vec::new(),
        }
    }
}

/// Whether a builder takes pileups, was stopped by an error, is handing the rest of its records
/// to the tap, or is done.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Stage {
    Open,
    Stopped,
    Closing,
    Closed,
}

/// Builds pileups from coordinate-sorted records in one forward pass.
///
/// Ask for pileups at positions that never move backwards: the same position again returns the
/// pileup already built, and an earlier one is an [`Error::Backwards`]. Positions are 0-based.
///
/// The builder holds a window of the records that span the position asked for, each with its
/// CIGAR decoded once into a footprint, and drops a record as soon as the builder has moved past
/// it. Pileups borrow the records in the window, and building one allocates nothing per entry.
///
/// Every record, filtered or not, is handed to a [`tap`](StreamingPileupBuilder::tap) exactly
/// once and in input order, as soon as the builder has moved past it and every record before it,
/// or when the builder closes. Keeping input order means a record is held until every record
/// before it has been passed, so a long record, such as one with a long reference skip, holds back
/// every record that starts within it. Without a tap, a record is dropped, and its buffers reused,
/// as soon as the builder has moved past it.
///
/// An error while advancing to a position, from the source, a malformed record, the read filter,
/// or the tap, stops the builder, so a pileup never misses a record: every later pileup is an
/// [`Error::Stopped`], and closing still hands every record not yet handed over to the tap.
///
/// ```no_run
/// use noodles::bam;
/// use streampile::StreamingPileupBuilder;
///
/// let mut reader = bam::io::reader::Builder::default().build_from_path("reads.bam")?;
/// let header = reader.read_header()?;
/// let mut builder = StreamingPileupBuilder::new(reader, &header)?.min_mapping_quality(20);
///
/// let pileup = builder.pileup("chr1", 100)?;
/// println!("{} reads, {} at Q13 or more", pileup.unfiltered_depth(), pileup.filtered_depth());
///
/// let mut columns = builder.columns("chr1", 200, 300)?;
/// while let Some(pileup) = columns.next_pileup() {
///     let pileup = pileup?;
///     println!("{}\t{}", pileup.position(), pileup.bases().count());
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct StreamingPileupBuilder<'f, S: RecordSource> {
    source: S,
    header: sam::Header,
    options: Options,
    read_filter: Option<ReadFilter<'f, S::Record>>,
    tap: Option<Tap<'f, S::Record>>,
    pub(crate) slots: Vec<LiveRecord<S::Record>>,
    pub(crate) free: Vec<u32>,
    pub(crate) active: Vec<u32>,
    pub(crate) waiting: VecDeque<u32>,
    pub(crate) next: Option<u32>,
    exhausted: bool,
    active_reference_id: usize,
    min_active_end: i64,
    last_key: (usize, i64),
    at: Option<(usize, usize)>,
    built: bool,
    entries: Vec<RawEntry>,
    stage: Stage,
}

impl<'f, S: RecordSource> StreamingPileupBuilder<'f, S> {
    /// Starts a builder over the records of a source whose header declares coordinate order.
    ///
    /// No record is read until the first pileup is asked for.
    pub fn new(source: S, header: &sam::Header) -> Result<Self> {
        use sam::header::record::value::map::header::tag::SORT_ORDER;
        let sort_order = header
            .header()
            .and_then(|map| map.other_fields().get(&SORT_ORDER));
        if sort_order.is_none_or(|order| order.as_bytes() != b"coordinate") {
            return Err(Error::NotCoordinateSorted {
                found: sort_order.map(|order| order.to_str_lossy().into_owned()),
            });
        }
        Ok(Self {
            source,
            header: header.clone(),
            options: Options::default(),
            read_filter: None,
            tap: None,
            slots: Vec::new(),
            free: Vec::new(),
            active: Vec::new(),
            waiting: VecDeque::new(),
            next: None,
            exhausted: false,
            active_reference_id: UNPLACED,
            min_active_end: i64::MAX,
            last_key: (0, i64::MIN),
            at: None,
            built: false,
            entries: Vec::new(),
            stage: Stage::Open,
        })
    }

    /// Piles up only records with at least this mapping quality: 0 by default. A record with no
    /// mapping quality (255) passes every floor.
    #[must_use]
    pub fn min_mapping_quality(mut self, min_mapping_quality: u8) -> Self {
        self.options.min_mapping_quality = min_mapping_quality;
        self
    }

    /// Leaves out records with any of these flags: by default, secondary, QC-fail, duplicate,
    /// and supplementary records, [`DEFAULT_EXCLUDE_FLAGS`].
    #[must_use]
    pub fn exclude_flags(mut self, exclude_flags: Flags) -> Self {
        self.options.exclude_flags = exclude_flags;
        self
    }

    /// Sets the quality floor of each pileup's filtered views and of the votes of its templates:
    /// [`DEFAULT_MIN_BASE_QUALITY`] by default. Entries under it are kept, and only the views and
    /// the votes leave them out.
    #[must_use]
    pub fn min_base_quality(mut self, min_base_quality: u8) -> Self {
        self.options.min_base_quality = min_base_quality;
        self
    }

    /// Piles up only records flagged as in a proper pair.
    #[must_use]
    pub fn proper_pairs_only(mut self, proper_pairs_only: bool) -> Self {
        self.options.proper_pairs_only = proper_pairs_only;
        self
    }

    /// Finds these auxiliary fields once, when each record is read, so entries reach them without
    /// a search, as for per-base tags read at every position of a deep pileup.
    #[must_use]
    pub fn index_aux_tags(mut self, tags: impl IntoIterator<Item = [u8; 2]>) -> Self {
        self.options.aux_tags = tags.into_iter().collect();
        self
    }

    /// Keeps a record for pileups only when this returns `true`. It is asked only of records that
    /// pass the other filters and align to the contig piled up, and a record it rejects still
    /// goes to the tap.
    #[must_use]
    pub fn read_filter(self, mut read_filter: impl FnMut(&S::Record) -> bool + Send + 'f) -> Self {
        self.try_read_filter(move |record| Ok(read_filter(record)))
    }

    /// Keeps a record for pileups only when this returns `Ok(true)`, as
    /// [`read_filter`](StreamingPileupBuilder::read_filter) does, and stops at an error.
    #[must_use]
    pub(crate) fn try_read_filter(
        mut self,
        read_filter: impl FnMut(&S::Record) -> io::Result<bool> + Send + 'f,
    ) -> Self {
        self.read_filter = Some(Box::new(read_filter));
        self
    }

    /// Hands every record to `tap` once the builder has moved past it, in input order.
    ///
    /// With a tap, [`close`](StreamingPileupBuilder::close) reads the rest of the input, so an
    /// output written by the tap is complete.
    #[must_use]
    pub fn tap(mut self, tap: impl FnMut(S::Record) -> io::Result<()> + Send + 'f) -> Self {
        self.tap = Some(Box::new(tap));
        self
    }

    /// The header the records were read with.
    pub fn header(&self) -> &sam::Header {
        &self.header
    }

    /// Whether a record passes the flag, mapping-quality, and proper-pair filters, is placed
    /// with a reference-consuming CIGAR operator, and then passes the read filter, so that it is
    /// piled up wherever it spans.
    pub fn accepts(&mut self, record: &S::Record) -> Result<bool> {
        let bam = record.bam();
        let start = bam
            .alignment_start()
            .transpose()
            .map_err(|source| Error::InvalidRecord {
                name: record_name(bam),
                source,
            })?
            .map_or(-1, |start| usize::from(start) as i64 - 1);
        let read_filter = self.read_filter.as_mut();
        admits(
            &self.options,
            read_filter,
            record,
            start,
            &mut Footprint::default(),
        )
    }

    /// Advances to a position on a contig, at or after the last one, and piles up the records
    /// there.
    pub fn pileup(&mut self, contig: &str, position: usize) -> Result<Pileup<'_, S::Record>> {
        self.check_open()?;
        let reference_sequence_id = self.reference_sequence_id(contig)?;
        self.pileup_at(reference_sequence_id, position)
    }

    /// Advances to a position on the contig with this index in the header, at or after the last
    /// one, and piles up the records there.
    pub fn pileup_at(
        &mut self,
        reference_sequence_id: usize,
        position: usize,
    ) -> Result<Pileup<'_, S::Record>> {
        self.check_open()?;
        if self.built && self.at == Some((reference_sequence_id, position)) {
            return Ok(self.view(reference_sequence_id, position));
        }
        if reference_sequence_id >= self.header.reference_sequences().len() {
            return Err(Error::UnknownReferenceSequenceId(reference_sequence_id));
        }
        if let Some((from_id, from_position)) = self.at
            && (reference_sequence_id, position) < (from_id, from_position)
        {
            return Err(Error::Backwards {
                contig: self.name_of(reference_sequence_id).to_string(),
                position,
                from_contig: self.name_of(from_id).to_string(),
                from_position,
            });
        }
        self.at = Some((reference_sequence_id, position));
        self.built = false;
        if let Err(error) = self.advance(reference_sequence_id, position as i64) {
            self.stage = Stage::Stopped;
            return Err(error);
        }
        self.collect(position as i64);
        self.built = true;
        Ok(self.view(reference_sequence_id, position))
    }

    /// Sweeps the pileup at every position of a span of a contig, covered or not.
    pub fn columns(
        &mut self,
        contig: &str,
        start: usize,
        end: usize,
    ) -> Result<Columns<'_, 'f, S>> {
        let reference_sequence_id = self.reference_sequence_id(contig)?;
        self.columns_at(reference_sequence_id, start, end)
    }

    /// Sweeps the pileup at every position of a span of the contig with this index in the
    /// header, covered or not.
    pub fn columns_at(
        &mut self,
        reference_sequence_id: usize,
        start: usize,
        end: usize,
    ) -> Result<Columns<'_, 'f, S>> {
        if end < start {
            return Err(Error::InvalidSpan { start, end });
        }
        Ok(Columns {
            builder: self,
            reference_sequence_id,
            next: start,
            end,
        })
    }

    /// Stops, first handing every record not yet handed to the tap to it, in input order.
    ///
    /// With a tap, the rest of the input is read to the end, so an output written by the tap is
    /// complete. Without one, no more of the input is read. A record goes to the tap once even
    /// when the tap fails, and closing again after an error hands over the records after it.
    /// Dropping a builder closes it too, but ignores any error, so close it to see one.
    pub fn close(&mut self) -> Result<()> {
        if self.stage == Stage::Closed {
            return Ok(());
        }
        self.stage = Stage::Closing;
        self.built = false;
        self.active.clear();
        self.entries.clear();
        if let Some(tap) = self.tap.as_mut() {
            while let Some(index) = self.waiting.pop_front() {
                tap(mem::take(&mut self.slots[index as usize].record))?;
            }
            if let Some(index) = self.next.take() {
                tap(mem::take(&mut self.slots[index as usize].record))?;
            }
            if !self.exhausted {
                let mut record = S::Record::default();
                while self.source.read_record(&mut record)? {
                    tap(mem::take(&mut record))?;
                }
                self.exhausted = true;
            }
        }
        self.slots.clear();
        self.free.clear();
        self.waiting.clear();
        self.next = None;
        self.stage = Stage::Closed;
        Ok(())
    }

    /// Stops without handing any more records to the tap, so dropping the builder runs no tap.
    #[cfg(feature = "python")]
    pub(crate) fn abandon(&mut self) {
        self.stage = Stage::Closed;
        self.built = false;
        self.active.clear();
        self.entries.clear();
        self.slots.clear();
        self.free.clear();
        self.waiting.clear();
        self.next = None;
    }

    fn check_open(&self) -> Result<()> {
        match self.stage {
            Stage::Open => Ok(()),
            Stage::Stopped => Err(Error::Stopped),
            Stage::Closing | Stage::Closed => Err(Error::Closed),
        }
    }

    fn reference_sequence_id(&self, contig: &str) -> Result<usize> {
        self.header
            .reference_sequences()
            .get_index_of(contig.as_bytes().as_bstr())
            .ok_or_else(|| Error::UnknownContig(contig.to_owned()))
    }

    fn name_of(&self, reference_sequence_id: usize) -> &BStr {
        self.header
            .reference_sequences()
            .get_index(reference_sequence_id)
            .map_or(b"".as_bstr(), |(name, _)| name.as_bstr())
    }

    fn view(&self, reference_sequence_id: usize, position: usize) -> Pileup<'_, S::Record> {
        Pileup {
            reference_sequence_id,
            reference_sequence_name: self.name_of(reference_sequence_id),
            position,
            min_base_quality: self.options.min_base_quality,
            entries: &self.entries,
            slots: &self.slots,
            aux_tags: &self.options.aux_tags,
        }
    }

    fn free(&mut self, index: u32) {
        self.slots[index as usize].record.release();
        self.free.push(index);
    }

    fn advance(&mut self, reference_sequence_id: usize, pos: i64) -> Result<()> {
        if reference_sequence_id != self.active_reference_id {
            self.evict(None);
            self.active_reference_id = reference_sequence_id;
        } else if self.min_active_end <= pos {
            self.evict(Some(pos));
        }
        let target = (reference_sequence_id, pos + 1);
        while let Some(index) = self.peek()? {
            let live = &self.slots[index as usize];
            let key = (live.reference_id, live.start);
            if key > target {
                break;
            }
            if key < self.last_key {
                return Err(Error::OutOfOrder {
                    name: record_name(live.record.bam()),
                });
            }
            self.last_key = key;
            self.next = None;
            let accepted = if key.0 == reference_sequence_id {
                self.accept(index, pos)
            } else {
                Ok(false)
            };
            if self.tap.is_some() {
                self.waiting.push_back(index);
            }
            if let Ok(true) = accepted {
                self.activate(index);
            } else if self.tap.is_none() {
                self.free(index);
            }
            accepted?;
        }
        self.release(reference_sequence_id, pos)
    }

    fn peek(&mut self) -> Result<Option<u32>> {
        if self.next.is_some() || self.exhausted {
            return Ok(self.next);
        }
        let index = if let Some(index) = self.free.pop() {
            index
        } else {
            self.slots.push(LiveRecord::default());
            u32::try_from(self.slots.len() - 1)
                .map_err(|_| io::Error::other("more than 4,294,967,295 records are held"))?
        };
        let tapped = self.tap.is_some();
        let live = &mut self.slots[index as usize];
        match self.source.read_record(&mut live.record) {
            Ok(true) => {
                if let Err(error) = describe(live, tapped) {
                    live.reference_id = UNPLACED;
                    if tapped {
                        self.waiting.push_back(index);
                    } else {
                        self.free(index);
                    }
                    return Err(error.into());
                }
                self.next = Some(index);
            }
            read => {
                self.free(index);
                read?;
                self.exhausted = true;
            }
        }
        Ok(self.next)
    }

    fn accept(&mut self, index: u32, pos: i64) -> Result<bool> {
        let live = &mut self.slots[index as usize];
        let read_filter = self.read_filter.as_mut();
        let admitted = admits(
            &self.options,
            read_filter,
            &live.record,
            live.start,
            &mut live.footprint,
        )?;
        if !admitted || live.footprint.end <= pos {
            return Ok(false);
        }
        live.derived = Derived::default();
        index_fields(live, &self.options.aux_tags).map_err(|error| match error {
            Error::Io(source) => Error::InvalidRecord {
                name: record_name(live.record.bam()),
                source,
            },
            error => error,
        })?;
        Ok(true)
    }

    fn activate(&mut self, index: u32) {
        let end = self.slots[index as usize].footprint.end;
        self.min_active_end = self.min_active_end.min(end);
        self.active.push(index);
    }

    fn evict(&mut self, before: Option<i64>) {
        let mut active = mem::take(&mut self.active);
        let mut kept = 0;
        let mut min_end = i64::MAX;
        for at in 0..active.len() {
            let index = active[at];
            let end = self.slots[index as usize].footprint.end;
            if before.is_some_and(|pos| end > pos) {
                active[kept] = index;
                kept += 1;
                min_end = min_end.min(end);
            } else if self.tap.is_none() {
                self.free(index);
            }
        }
        active.truncate(kept);
        self.active = active;
        self.min_active_end = min_end;
    }

    fn release(&mut self, reference_sequence_id: usize, pos: i64) -> Result<()> {
        let Some(tap) = self.tap.as_mut() else {
            return Ok(());
        };
        while let Some(&index) = self.waiting.front() {
            let live = &mut self.slots[index as usize];
            let passed = live.reference_id < reference_sequence_id
                || (live.reference_id == reference_sequence_id && live.end <= pos);
            if !passed {
                break;
            }
            self.waiting.pop_front();
            let record = mem::take(&mut live.record);
            self.free.push(index);
            tap(record)?;
        }
        Ok(())
    }

    fn collect(&mut self, pos: i64) {
        self.entries.clear();
        let entries = &mut self.entries;
        for &index in &self.active {
            self.slots[index as usize]
                .footprint
                .entries_at(pos, |kind, offset, length| {
                    entries.push(RawEntry {
                        slot: index,
                        kind,
                        offset,
                        length,
                    });
                });
        }
    }
}

impl<S: RecordSource> Drop for StreamingPileupBuilder<'_, S> {
    fn drop(&mut self) {
        if !std::thread::panicking() {
            let _ = self.close();
        }
    }
}

/// A forward sweep of the pileup at every position of a span, from
/// [`columns`](StreamingPileupBuilder::columns).
pub struct Columns<'b, 'f, S: RecordSource> {
    builder: &'b mut StreamingPileupBuilder<'f, S>,
    reference_sequence_id: usize,
    next: usize,
    end: usize,
}

impl<S: RecordSource> Columns<'_, '_, S> {
    /// The pileup at the next position of the span, or `None` past its end.
    pub fn next_pileup(&mut self) -> Option<Result<Pileup<'_, S::Record>>> {
        if self.next >= self.end {
            return None;
        }
        let position = self.next;
        self.next += 1;
        Some(self.builder.pileup_at(self.reference_sequence_id, position))
    }
}

/// Reads a record's contig, start, and flags, and with a tap, where the builder is past it.
fn describe<R: AlignmentRecord>(live: &mut LiveRecord<R>, tapped: bool) -> io::Result<()> {
    let record = live.record.bam();
    live.reference_id = record
        .reference_sequence_id()
        .transpose()?
        .unwrap_or(UNPLACED);
    live.start = record
        .alignment_start()
        .transpose()?
        .map_or(-1, |start| usize::from(start) as i64 - 1);
    live.flags = record.flags();
    if tapped {
        let cigar = record.cigar();
        let length = if live.flags.is_unmapped() || cigar.is_empty() {
            1
        } else {
            cigar.alignment_span()?.max(1) as i64
        };
        live.end = live.start + length;
    }
    Ok(())
}

/// Finds the indexed auxiliary fields of an accepted record.
fn index_fields<R: AlignmentRecord>(live: &mut LiveRecord<R>, tags: &[[u8; 2]]) -> Result<()> {
    live.fields.clear();
    live.fields.resize(tags.len(), None);
    if tags.is_empty() {
        return Ok(());
    }
    let fields = &mut live.fields;
    auxiliary::walk(live.record.bam().data().as_bytes(), |tag, field| {
        if let Some(index) = tags.iter().position(|wanted| *wanted == tag)
            && fields[index].is_none()
        {
            fields[index] = Some(field);
        }
    })?;
    Ok(())
}