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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
//! FASTQ reading and writing: streaming record iterators over plain, gzip and BGZF input, and segment writers with optional SAM-style header tags.

use std::fs::File;
use std::io::{self, BufReader, BufWriter, Read, Write};

use anyhow::Context;

use flate2::bufread::MultiGzDecoder;
use noodles_sam::alignment::record_buf::data::field::Value;
use noodles_sam::alignment::record_buf::data::field::value::Array;
use seq_io::fastq::{Reader, Record};

use crate::config::Config;
use crate::record::ReadRecord;

/// Capacity of the buffer between a compressed source and its decoder, which
/// pulls the compressed stream through it in one `read` syscall per megabyte.
///
/// The parser's own buffer keeps the seq_io default: the parser fills it to
/// capacity before yielding, so an I/O error during a fill discards every
/// record in it, and a larger buffer would widen the span of records an error
/// on damaged input cannot be attributed to.
const INPUT_BUFFER_CAPACITY: usize = 1 << 20;

/// Builds a streaming FASTQ record iterator over an already-open source (e.g. a
/// peeked-and-chained stdin stream), decompressing gzip when `gz` is true, on
/// a dedicated thread when `inflate_thread` is true (see `byte_stream`).
pub fn reader_from(
    inner: Box<dyn Read + Send>,
    gz: bool,
    inflate_thread: bool,
) -> Box<dyn Iterator<Item = anyhow::Result<ReadRecord>> + Send> {
    Box::new(RecordIter::new(byte_stream(inner, gz, inflate_thread)))
}

/// Returns the decoded byte stream of a FASTQ source, inflating gzip when
/// `gz` is true. With `inflate_thread`, the gzip stream inflates on a
/// dedicated thread ahead of the parser (`InflateThread`), so decompression
/// of the single DEFLATE stream overlaps with parsing.
pub fn byte_stream(
    inner: Box<dyn Read + Send>,
    gz: bool,
    inflate_thread: bool,
) -> Box<dyn Read + Send> {
    if !gz {
        return inner;
    }
    // `bufread::MultiGzDecoder` over an explicit buffer; the `read` variant
    // wraps its source in an 8 KiB `BufReader`.
    let decoder = MultiGzDecoder::new(BufReader::with_capacity(INPUT_BUFFER_CAPACITY, inner));
    if inflate_thread {
        Box::new(InflateThread::spawn(decoder))
    } else {
        Box::new(decoder)
    }
}

/// Size of one decompressed chunk the inflate thread hands to the parser.
const INFLATE_CHUNK: usize = 1 << 20;

/// Decompressed chunks queued between the inflate thread and the parser. With
/// the chunk being filled and the chunk being parsed, at most four chunks are
/// allocated.
const INFLATE_QUEUE: usize = 2;

/// A reader over a decoder that runs on its own thread. The thread fills
/// fixed-size chunks and sends them through a bounded channel; the reader
/// returns each consumed chunk for reuse. A decoder error is delivered after
/// the bytes decoded before it, and a thread that stops without reaching the
/// end of the stream is reported as an error rather than as end of input.
struct InflateThread {
    /// Filled chunks, then an empty chunk marking the end of the stream.
    chunks: std::sync::mpsc::Receiver<io::Result<Vec<u8>>>,
    /// Consumed chunks returned to the thread.
    recycle: std::sync::mpsc::Sender<Vec<u8>>,
    /// The chunk being read.
    current: Vec<u8>,
    /// Read position in `current`.
    pos: usize,
    /// Whether the end marker has been received.
    ended: bool,
    /// Whether an error has been returned; later reads fail as well.
    failed: bool,
}

impl InflateThread {
    /// Starts the thread over `decoder`. The thread exits at the end of the
    /// stream, after a decoder error, or once the reader is dropped.
    fn spawn<D: Read + Send + 'static>(mut decoder: D) -> Self {
        let (tx, chunks) = std::sync::mpsc::sync_channel::<io::Result<Vec<u8>>>(INFLATE_QUEUE);
        let (recycle, reuse) = std::sync::mpsc::channel::<Vec<u8>>();
        std::thread::spawn(move || {
            loop {
                let mut chunk = reuse
                    .try_recv()
                    .unwrap_or_else(|_| Vec::with_capacity(INFLATE_CHUNK));
                chunk.resize(INFLATE_CHUNK, 0);
                let mut filled = 0;
                let mut failure = None;
                while filled < chunk.len() {
                    match decoder.read(&mut chunk[filled..]) {
                        Ok(0) => break,
                        Ok(n) => filled += n,
                        Err(e) if e.kind() == io::ErrorKind::Interrupted => {},
                        Err(e) => {
                            failure = Some(e);
                            break;
                        },
                    }
                }
                chunk.truncate(filled);
                let end = filled == 0;
                if (filled > 0 || failure.is_none()) && tx.send(Ok(chunk)).is_err() {
                    return;
                }
                if let Some(e) = failure {
                    let _ = tx.send(Err(e));
                    return;
                }
                if end {
                    return;
                }
            }
        });
        InflateThread {
            chunks,
            recycle,
            current: Vec::new(),
            pos: 0,
            ended: false,
            failed: false,
        }
    }
}

impl Read for InflateThread {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        while self.pos == self.current.len() {
            if self.failed {
                return Err(io::Error::other("the gzip stream failed to decode"));
            }
            if self.ended {
                return Ok(0);
            }
            let used = std::mem::take(&mut self.current);
            if used.capacity() > 0 {
                // The thread is gone once the stream has ended; the chunk is
                // then dropped.
                let _ = self.recycle.send(used);
            }
            self.pos = 0;
            match self.chunks.recv() {
                Ok(Ok(chunk)) if chunk.is_empty() => self.ended = true,
                Ok(Ok(chunk)) => self.current = chunk,
                Ok(Err(e)) => {
                    self.failed = true;
                    return Err(e);
                },
                Err(_) => {
                    self.failed = true;
                    return Err(io::Error::other(
                        "the gzip decoder thread stopped before the end of the stream",
                    ));
                },
            }
        }
        let n = buf.len().min(self.current.len() - self.pos);
        buf[..n].copy_from_slice(&self.current[self.pos..self.pos + n]);
        self.pos += n;
        Ok(n)
    }
}

/// Builds a FASTQ iterator over BGZF-compressed input. Unlike ordinary gzip,
/// BGZF is independently framed, so blocks inflate on a private pool of
/// `workers` threads while the parser consumes completed blocks in order.
pub fn reader_from_bgzf(
    inner: Box<dyn Read + Send>,
    workers: usize,
) -> anyhow::Result<Box<dyn Iterator<Item = anyhow::Result<ReadRecord>> + Send>> {
    // The block reader issues a `read` per frame part (header, payload,
    // trailer); the buffer in front of the source coalesces them.
    let inner = BufReader::with_capacity(INPUT_BUFFER_CAPACITY, inner);
    let inner: Box<dyn Read + Send> = if workers > 1 {
        Box::new(noodles_bgzf::io::MultithreadedReader::with_worker_count(
            std::num::NonZero::new(workers).unwrap_or(std::num::NonZero::<usize>::MIN),
            inner,
        ))
    } else {
        Box::new(noodles_bgzf::io::Reader::new(inner))
    };
    Ok(Box::new(RecordIter::new(inner)))
}

/// Highest raw Phred score a Phred+33 quality byte encodes (`~`, ASCII 126).
pub(crate) const MAX_PHRED33: u8 = 126 - 33;

struct RecordIter<R: Read> {
    reader: Reader<R>,
    /// Records yielded so far.
    count: u64,
    /// Id of the last record yielded, kept for error context.
    last_id: Vec<u8>,
}

impl<R: Read> RecordIter<R> {
    fn new(inner: R) -> Self {
        RecordIter {
            reader: Reader::new(inner),
            count: 0,
            last_id: Vec::new(),
        }
    }

    /// Converts a reader error. An `Io` error is unwrapped to the inner
    /// `io::Error` and given stream-position context: seq_io's wrapper both
    /// displays and sources the same error, which prints its message twice
    /// under anyhow's alternate formatting. Parse errors already carry their
    /// record and line.
    fn describe(&self, e: seq_io::fastq::Error) -> anyhow::Error {
        match e {
            seq_io::fastq::Error::Io(e) => {
                let context = if self.count == 0 {
                    "reading the first FASTQ record".to_string()
                } else {
                    format!(
                        "reading FASTQ record after {}",
                        String::from_utf8_lossy(&self.last_id)
                    )
                };
                anyhow::Error::new(e).context(context)
            },
            other => anyhow::Error::new(other),
        }
    }
}

/// Names the first quality byte outside the Phred+33 range. `qual` holds at
/// least one such byte.
pub(crate) fn invalid_quality(id: &[u8], qual: &[u8]) -> anyhow::Error {
    let (pos, &byte) = qual
        .iter()
        .enumerate()
        .find(|&(_, &b)| b.wrapping_sub(33) > MAX_PHRED33)
        .expect("The caller found a quality byte outside the Phred+33 range");
    anyhow::anyhow!(
        "record {}: quality byte 0x{byte:02x} at position {} is outside the Phred+33 range \
         (ASCII 33..=126)",
        String::from_utf8_lossy(id),
        pos + 1
    )
}

impl<R: Read> Iterator for RecordIter<R> {
    type Item = anyhow::Result<ReadRecord>;
    fn next(&mut self) -> Option<Self::Item> {
        let rec = match self.reader.next()? {
            Ok(rec) => rec,
            Err(e) => return Some(Err(self.describe(e))),
        };
        // One pass converts and validates: a byte below 33 wraps above the
        // maximum, so a single compare per byte flags both ends of the range.
        let raw = rec.qual();
        let mut out_of_range = false;
        let qual: Vec<u8> = raw
            .iter()
            .map(|&b| {
                let q = b.wrapping_sub(33);
                out_of_range |= q > MAX_PHRED33;
                q
            })
            .collect();
        if out_of_range {
            return Some(Err(invalid_quality(rec.id_bytes(), raw)));
        }
        self.count += 1;
        self.last_id.clear();
        self.last_id.extend_from_slice(rec.id_bytes());
        Some(Ok(ReadRecord {
            name: rec.head().to_vec(),
            seq: rec.seq().to_vec(),
            qual,
        }))
    }
}

/// Writes the `@`-prefixed header id for a segment (no trailing newline, no tags).
/// On splits (`total_segments > 1`) the id gets a `_segment_N` suffix inserted
/// before any space-separated description.
pub(crate) fn write_head<W: Write>(
    w: &mut W,
    name: &[u8],
    total_segments: usize,
    segment_idx: usize,
) -> io::Result<()> {
    w.write_all(b"@")?;
    if total_segments > 1 {
        // The suffix follows the read ID, preserving the original delimiter,
        // description, and tab-delimited tags.
        match name.iter().position(|&b| b == b' ' || b == b'\t') {
            Some(i) => {
                w.write_all(&name[..i])?;
                write!(w, "_segment_{}", segment_idx + 1)?;
                w.write_all(&name[i..])?;
            },
            None => {
                w.write_all(name)?;
                write!(w, "_segment_{}", segment_idx + 1)?;
            },
        }
    } else {
        w.write_all(name)?;
    }
    Ok(())
}

/// Writes one output segment as a plain FASTQ record. `phred` is raw; ASCII is
/// emitted by adding 33.
pub fn write_segment<W: Write>(
    w: &mut W,
    name: &[u8],
    seq: &[u8],
    phred: &[u8],
    total_segments: usize,
    segment_idx: usize,
) -> io::Result<()> {
    write_head(w, name, total_segments, segment_idx)?;
    write_body(w, seq, phred)
}

/// Appends the rest of a record after its header id and tags to `out`: the
/// newline, the sequence, the `+` line and the Phred+33 qualities. The `Vec`
/// counterpart of `write_body` for callers that assemble the header in place.
pub(crate) fn push_record_body(out: &mut Vec<u8>, seq: &[u8], phred: &[u8]) {
    write_body(out, seq, phred).expect("Writing to a Vec cannot fail");
}

/// Writes the rest of a record after its header line: the newline, the
/// sequence, the `+` line and the Phred+33 qualities. A quality above 93,
/// which BAM records may carry, is written as 93 (`~`), the highest value
/// Phred+33 FASTQ represents.
pub(crate) fn write_body<W: Write>(w: &mut W, seq: &[u8], phred: &[u8]) -> io::Result<()> {
    w.write_all(b"\n")?;
    w.write_all(seq)?;
    w.write_all(b"\n+\n")?;
    // Phred to ASCII in fixed stack chunks, avoiding a per-segment heap
    // allocation.
    let mut ascii = [0u8; 1024];
    for chunk in phred.chunks(ascii.len()) {
        for (dst, &q) in ascii.iter_mut().zip(chunk) {
            *dst = q.min(MAX_PHRED33) + 33;
        }
        w.write_all(&ascii[..chunk.len()])?;
    }
    w.write_all(b"\n")
}

/// The decimal text of `0..=99` as digit pairs, for the two-digit fast path of
/// [`push_u64`]: `MM` skip counts are mostly one or two digits.
const DIGIT_PAIRS: [[u8; 2]; 100] = {
    let mut t = [[0u8; 2]; 100];
    let mut i = 0;
    while i < 100 {
        t[i] = [b'0' + (i / 10) as u8, b'0' + (i % 10) as u8];
        i += 1;
    }
    t
};

/// Appends `n` as ASCII decimal without invoking `core::fmt`. The aux `B` arrays
/// (notably `ML` and the per-base kinetics tags) can hold tens of thousands of
/// integers per record; a stack buffer and a digit loop avoid the per-call
/// overhead of `write!` on a `Vec` at that volume.
#[inline]
pub(crate) fn push_u64(out: &mut Vec<u8>, mut n: u64) {
    if n < 10 {
        out.push(b'0' + n as u8);
        return;
    }
    if n < 100 {
        out.extend_from_slice(&DIGIT_PAIRS[n as usize]);
        return;
    }
    let mut buf = [0u8; 20];
    let mut i = buf.len();
    loop {
        i -= 1;
        buf[i] = b'0' + (n % 10) as u8;
        n /= 10;
        if n == 0 {
            break;
        }
    }
    out.extend_from_slice(&buf[i..]);
}

/// Appends `n` as signed ASCII decimal, the counterpart of [`push_u64`].
/// `unsigned_abs` yields the correct magnitude even for `i64::MIN`, where `-n`
/// would overflow.
#[inline]
pub(crate) fn push_i64(out: &mut Vec<u8>, n: i64) {
    if n < 0 {
        out.push(b'-');
    }
    push_u64(out, n.unsigned_abs());
}

/// Appends one SAM aux field as text `XX:T:VALUE` (no leading TAB) to `out`.
/// Integers of any source width serialize with SAM type code `i`; `B` arrays
/// keep their subtype.
pub fn push_aux_field(out: &mut Vec<u8>, tag: [u8; 2], value: &Value) {
    out.extend_from_slice(&tag);
    out.push(b':');
    match value {
        Value::Character(c) => {
            out.extend_from_slice(b"A:");
            out.push(*c);
        },
        Value::Int8(n) => {
            out.extend_from_slice(b"i:");
            push_i64(out, i64::from(*n));
        },
        Value::UInt8(n) => {
            out.extend_from_slice(b"i:");
            push_u64(out, u64::from(*n));
        },
        Value::Int16(n) => {
            out.extend_from_slice(b"i:");
            push_i64(out, i64::from(*n));
        },
        Value::UInt16(n) => {
            out.extend_from_slice(b"i:");
            push_u64(out, u64::from(*n));
        },
        Value::Int32(n) => {
            out.extend_from_slice(b"i:");
            push_i64(out, i64::from(*n));
        },
        Value::UInt32(n) => {
            out.extend_from_slice(b"i:");
            push_u64(out, u64::from(*n));
        },
        Value::Float(x) => write!(out, "f:{x}").unwrap(),
        Value::String(s) => {
            out.extend_from_slice(b"Z:");
            out.extend_from_slice(AsRef::<[u8]>::as_ref(s));
        },
        Value::Hex(s) => {
            out.extend_from_slice(b"H:");
            out.extend_from_slice(AsRef::<[u8]>::as_ref(s));
        },
        Value::Array(a) => {
            out.extend_from_slice(b"B:");
            write_array(out, a);
        },
    }
}

/// One `B:C` array element as text: `,` and the decimal digits of the value,
/// with the length of the used prefix. Indexed by value. `ML` and the
/// per-base kinetics arrays hold tens of thousands of elements per record, so
/// each element is a fixed-width table copy rather than a digit loop.
const COMMA_U8: [([u8; 4], usize); 256] = {
    let mut t = [([0u8; 4], 0usize); 256];
    let mut i = 0;
    while i < 256 {
        let n = i as u8;
        let mut b = [b',', 0, 0, 0];
        let len = if n >= 100 {
            b[1] = b'0' + n / 100;
            b[2] = b'0' + (n / 10) % 10;
            b[3] = b'0' + n % 10;
            4
        } else if n >= 10 {
            b[1] = b'0' + n / 10;
            b[2] = b'0' + n % 10;
            3
        } else {
            b[1] = b'0' + n;
            2
        };
        t[i] = (b, len);
        i += 1;
    }
    t
};

/// One `B:c` array element as text, the signed counterpart of [`COMMA_U8`],
/// indexed by the value's bit pattern (`x as u8`). The move table `mv` is a
/// `B:c` array with one element per signal stride.
const COMMA_I8: [([u8; 5], usize); 256] = {
    let mut t = [([0u8; 5], 0usize); 256];
    let mut i = 0;
    while i < 256 {
        let x = i as u8 as i8;
        let m = x.unsigned_abs();
        let mut b = [b',', 0, 0, 0, 0];
        let mut len = 1;
        if x < 0 {
            b[len] = b'-';
            len += 1;
        }
        if m >= 100 {
            b[len] = b'0' + m / 100;
            b[len + 1] = b'0' + (m / 10) % 10;
            b[len + 2] = b'0' + m % 10;
            len += 3;
        } else if m >= 10 {
            b[len] = b'0' + m / 10;
            b[len + 1] = b'0' + m % 10;
            len += 2;
        } else {
            b[len] = b'0' + m;
            len += 1;
        }
        t[i] = (b, len);
        i += 1;
    }
    t
};

/// Appends `,` and the decimal text of every element of a `B:C` array. The
/// capacity is reserved once for the widest element, so each element is a
/// fixed four-byte copy followed by a truncate rather than a variable-length
/// copy.
fn push_comma_u8s(out: &mut Vec<u8>, v: &[u8]) {
    out.reserve(v.len() * 4);
    for &x in v {
        let (bytes, len) = COMMA_U8[usize::from(x)];
        out.extend_from_slice(&bytes);
        out.truncate(out.len() - (4 - len));
    }
}

/// Appends `,` and the decimal text of every element of a `B:c` array; see
/// [`push_comma_u8s`].
fn push_comma_i8s(out: &mut Vec<u8>, v: &[i8]) {
    out.reserve(v.len() * 5);
    for &x in v {
        let (bytes, len) = COMMA_I8[usize::from(x as u8)];
        out.extend_from_slice(&bytes);
        out.truncate(out.len() - (5 - len));
    }
}

/// Appends `,` and the decimal text of every element of a wider unsigned `B`
/// array. The capacity is reserved at two bytes per element, the shortest text
/// an element can take.
fn push_comma_u64s(out: &mut Vec<u8>, v: impl ExactSizeIterator<Item = u64>) {
    out.reserve(v.len() * 2);
    for x in v {
        out.push(b',');
        push_u64(out, x);
    }
}

/// Appends `,` and the decimal text of every element of a wider signed `B`
/// array; see [`push_comma_u64s`].
fn push_comma_i64s(out: &mut Vec<u8>, v: impl ExactSizeIterator<Item = i64>) {
    out.reserve(v.len() * 2);
    for x in v {
        out.push(b',');
        push_i64(out, x);
    }
}

/// Appends a `B` array's subtype code and comma-prefixed elements.
fn write_array(out: &mut Vec<u8>, a: &Array) {
    match a {
        Array::Int8(v) => {
            out.push(b'c');
            push_comma_i8s(out, v);
        },
        Array::UInt8(v) => {
            out.push(b'C');
            push_comma_u8s(out, v);
        },
        Array::Int16(v) => {
            out.push(b's');
            push_comma_i64s(out, v.iter().map(|&x| i64::from(x)));
        },
        Array::UInt16(v) => {
            out.push(b'S');
            push_comma_u64s(out, v.iter().map(|&x| u64::from(x)));
        },
        Array::Int32(v) => {
            out.push(b'i');
            push_comma_i64s(out, v.iter().map(|&x| i64::from(x)));
        },
        Array::UInt32(v) => {
            out.push(b'I');
            push_comma_u64s(out, v.iter().map(|&x| u64::from(x)));
        },
        Array::Float(v) => {
            out.push(b'f');
            out.reserve(v.len() * 2);
            for x in v {
                write!(out, ",{x}").unwrap();
            }
        },
    }
}

/// Appends the reconstructed MM/ML/MN block as SAM aux text to `out`, each
/// field TAB-prefixed: `\tMM:Z:<mm>\tML:B:C,<ml...>\tMN:i:<mn>`. `ml` is
/// `None` for an MM-only source record (ML is optional per the SAM spec), in
/// which case the `ML:B:C` field is omitted rather than emitted empty.
///
/// A field named by `remove` is left out and the others still emitted, which is
/// what BAM output does with the same setting. Every field TAB-prefixed rather
/// than TAB-separated is what lets any one of them be omitted.
pub fn push_mods_aux(
    out: &mut Vec<u8>,
    mm: &[u8],
    ml: Option<&[u8]>,
    mn: usize,
    remove: &crate::config::TagRemoval,
) {
    out.reserve(mm.len() + 40);
    if !remove.contains(b"MM") {
        out.extend_from_slice(b"\tMM:Z:");
        out.extend_from_slice(mm);
    }
    if let Some(ml) = ml
        && !remove.contains(b"ML")
    {
        out.extend_from_slice(b"\tML:B:C");
        push_comma_u8s(out, ml);
    }
    if !remove.contains(b"MN") {
        out.extend_from_slice(b"\tMN:i:");
        push_u64(out, mn as u64);
    }
}

/// Capacity of the buffer in front of the output file or stdout. Plain output
/// is written record by record and the compressed encoders emit one write per
/// block; the buffer coalesces either into one `write` syscall per megabyte.
const OUTPUT_BUFFER_CAPACITY: usize = 1 << 20;

/// The buffered destination of a FASTQ writer.
type BufferedOutput = BufWriter<Box<dyn Write + Send>>;

/// FASTQ output writer: a plain buffered writer, or BGZF for the compressed
/// formats. `FastqGz` and `FastqBgzf` share the BGZF framing: BGZF is a valid
/// multi-member gzip stream, so `.fastq.gz` output decodes with every gzip
/// tool and `MultiGzDecoder`, and also inflates block-parallel when read
/// back. `Bgzf` compresses in the writing thread for a sequential run;
/// `Blocks` takes blocks the render workers compressed (see
/// `workflow::run_parallel`).
pub(crate) enum FastqOut {
    /// Plain buffered output.
    Plain(BufferedOutput),
    /// BGZF output compressed in the writing thread.
    Bgzf(crate::io::bgzf::Writer<BufferedOutput>),
    /// Pre-compressed BGZF blocks.
    Blocks {
        /// The output.
        inner: BufferedOutput,
        /// The BGZF DEFLATE level the render workers compress at.
        level: u8,
    },
}

impl Write for FastqOut {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        match self {
            FastqOut::Plain(w) | FastqOut::Blocks { inner: w, .. } => w.write(buf),
            FastqOut::Bgzf(w) => w.write(buf),
        }
    }
    fn flush(&mut self) -> std::io::Result<()> {
        match self {
            FastqOut::Plain(w) | FastqOut::Blocks { inner: w, .. } => w.flush(),
            FastqOut::Bgzf(w) => w.flush(),
        }
    }
}

impl FastqOut {
    /// The BGZF level the render workers compress at, for a `Blocks` sink.
    pub(crate) fn block_level(&self) -> Option<u8> {
        match self {
            FastqOut::Blocks { level, .. } => Some(*level),
            FastqOut::Plain(_) | FastqOut::Bgzf(_) => None,
        }
    }

    /// Finalizes the writer: the BGZF variants write their last block and the
    /// BGZF EOF block, and every variant then flushes the output buffer, whose
    /// write error surfaces here. Must be called before returning success;
    /// the encoder's `Drop` swallows errors.
    pub(crate) fn finish(self) -> anyhow::Result<()> {
        let mut inner = match self {
            FastqOut::Plain(w) => w,
            FastqOut::Bgzf(w) => w.finish()?,
            FastqOut::Blocks { mut inner, .. } => {
                inner.write_all(&crate::io::bgzf::EOF_BLOCK)?;
                inner
            },
        };
        inner.flush()?;
        Ok(())
    }
}

/// Compresses `data` into BGZF blocks at `level`: the bytes of a BGZF stream
/// fragment with complete blocks and no EOF block, which a `FastqOut::Blocks`
/// writes through.
pub(crate) fn encode_blocks(level: u8, data: &[u8]) -> std::io::Result<Vec<u8>> {
    let mut blocks = Vec::new();
    crate::io::bgzf::encode(level, data, &mut blocks)?;
    Ok(blocks)
}

/// Builds the FASTQ output writer over a file or stdout: for `FastqGz` and
/// `FastqBgzf`, a BGZF writer at `cfg.compression_level` compressing in the
/// writing thread, or a `Blocks` sink when `parallel`; a plain buffered
/// writer for `Fastq`.
pub(crate) fn writer(
    cfg: &Config,
    out_fmt: crate::io::Format,
    parallel: bool,
) -> anyhow::Result<FastqOut> {
    writer_to(
        cfg.io.output.as_deref(),
        out_fmt,
        cfg.compression_level,
        parallel,
    )
}

/// Builds a FASTQ output writer over `path`, or stdout when `None`, at
/// `level` for the compressed formats; see `writer`.
pub(crate) fn writer_to(
    path: Option<&std::path::Path>,
    out_fmt: crate::io::Format,
    level: u8,
    parallel: bool,
) -> anyhow::Result<FastqOut> {
    let inner: Box<dyn Write + Send> = match path {
        Some(p) => {
            Box::new(File::create(p).with_context(|| format!("creating output {}", p.display()))?)
        },
        None => Box::new(io::stdout()),
    };
    let base = BufWriter::with_capacity(OUTPUT_BUFFER_CAPACITY, inner);
    match out_fmt {
        crate::io::Format::FastqGz | crate::io::Format::FastqBgzf => {
            crate::io::bgzf::compression_level(level)?;
            if parallel {
                return Ok(FastqOut::Blocks { inner: base, level });
            }
            Ok(FastqOut::Bgzf(crate::io::bgzf::Writer::new(base, level)))
        },
        crate::io::Format::Fastq => Ok(FastqOut::Plain(base)),
        crate::io::Format::Bam => unreachable!("BAM output is written by `io::bam::writer`"),
    }
}

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

    #[test]
    fn qualities_above_the_fastq_range_are_clamped() {
        let mut out = Vec::new();
        write_body(&mut out, b"ACGT", &[0, 93, 94, 255]).unwrap();
        assert_eq!(out, b"\nACGT\n+\n!~~~\n");
    }

    #[test]
    fn writes_single_segment_verbatim_header() {
        let mut out = Vec::new();
        write_segment(&mut out, b"read1 desc", b"ACGT", &[40, 40, 40, 40], 1, 0).unwrap();
        assert_eq!(out, b"@read1 desc\nACGT\n+\nIIII\n");
    }

    #[test]
    fn split_segment_suffixes_id_before_desc() {
        let mut out = Vec::new();
        write_segment(&mut out, b"read1 desc", b"AC", &[40, 40], 2, 1).unwrap();
        assert_eq!(out, b"@read1_segment_2 desc\nAC\n+\nII\n");
    }

    /// A `samtools fastq -T`-style header carries SAM tags after a TAB. The
    /// `_segment_N` suffix lands directly after the read id, keeping the TAB
    /// and the tag value intact.
    #[test]
    fn split_segment_preserves_tab_delimited_tags() {
        let mut out = Vec::new();
        write_segment(&mut out, b"r1\tRG:Z:grp", b"AC", &[40, 40], 2, 0).unwrap();
        assert_eq!(out, b"@r1_segment_1\tRG:Z:grp\nAC\n+\nII\n");
    }

    #[test]
    fn roundtrip_reader_writer() {
        let fq = b"@r1\nACGT\n+\nIIII\n@r2 x\nTT\n+\n!!\n";
        let recs: Vec<ReadRecord> = RecordIter::new(&fq[..]).map(|r| r.unwrap()).collect();
        assert_eq!(recs.len(), 2);
        assert_eq!(recs[0].name, b"r1");
        assert_eq!(recs[0].seq, b"ACGT");
        assert_eq!(recs[0].qual, vec![40, 40, 40, 40]); // 'I' = 73 - 33
        assert_eq!(recs[1].qual, vec![0, 0]); // '!' = 33 - 33
    }

    #[test]
    fn quality_range_bounds_are_accepted() {
        let fq = b"@r1\nAC\n+\n!~\n";
        let recs: Vec<ReadRecord> = RecordIter::new(&fq[..]).map(|r| r.unwrap()).collect();
        assert_eq!(recs[0].qual, vec![0, 93]);
    }

    #[test]
    fn quality_byte_outside_phred33_range_is_an_error() {
        let fq = b"@r1 desc\nACGTACGT\n+\nII I\x01III\n";
        let err = RecordIter::new(&fq[..])
            .next()
            .unwrap()
            .unwrap_err()
            .to_string();
        assert!(err.contains("record r1"), "Names the record id: {err}");
        assert!(
            err.contains("0x20"),
            "Names the first offending byte: {err}"
        );
        assert!(err.contains("Phred+33"), "Names the expected range: {err}");

        let fq = b"@r2\nAC\n+\nI\x7f\n";
        let err = RecordIter::new(&fq[..])
            .next()
            .unwrap()
            .unwrap_err()
            .to_string();
        assert!(err.contains("record r2") && err.contains("0x7f"), "{err}");
    }

    /// Serves `data` and fails every read past its end with `msg`.
    struct FailAfter {
        data: Vec<u8>,
        pos: usize,
        msg: &'static str,
    }

    impl Read for FailAfter {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            if self.pos == self.data.len() {
                return Err(io::Error::other(self.msg));
            }
            let n = (self.data.len() - self.pos).min(buf.len());
            buf[..n].copy_from_slice(&self.data[self.pos..self.pos + n]);
            self.pos += n;
            Ok(n)
        }
    }

    #[test]
    fn io_error_carries_record_context_and_prints_the_cause_once() {
        // More than one parser buffer of records, so the failing read follows
        // records that were yielded.
        let mut data = Vec::new();
        for i in 0..8000 {
            data.extend_from_slice(format!("@r{i} desc\nACGT\n+\nIIII\n").as_bytes());
        }
        let mut it = RecordIter::new(FailAfter {
            data,
            pos: 0,
            msg: "incomplete deflate stream",
        });
        let mut last_id = None;
        let err = loop {
            match it.next().unwrap() {
                Ok(rec) => last_id = Some(rec.name[..rec.name.len() - 5].to_vec()),
                Err(e) => break e,
            }
        };
        let last_id = String::from_utf8(last_id.expect("Records precede the error")).unwrap();
        assert_eq!(
            format!("{err:#}"),
            format!("reading FASTQ record after {last_id}: incomplete deflate stream")
        );

        let mut it = RecordIter::new(FailAfter {
            data: Vec::new(),
            pos: 0,
            msg: "boom",
        });
        let err = it.next().unwrap().unwrap_err();
        assert_eq!(format!("{err:#}"), "reading the first FASTQ record: boom");
    }

    /// `text` as a single-member gzip stream.
    fn gzip(text: &[u8]) -> Vec<u8> {
        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        enc.write_all(text).unwrap();
        enc.finish().unwrap()
    }

    /// `n` FASTQ records named from `prefix`, spanning several inflate chunks
    /// for large `n`.
    fn fastq_records(prefix: &str, n: usize) -> Vec<u8> {
        let mut text = Vec::new();
        for i in 0..n {
            text.extend_from_slice(format!("@{prefix}{i}\nACGTACGTAC\n+\nIIIIIIIIII\n").as_bytes());
        }
        text
    }

    /// Record names from a gzip byte stream, inflated on the calling thread or
    /// on the inflate thread.
    fn gz_names(gz: Vec<u8>, inflate_thread: bool) -> anyhow::Result<Vec<Vec<u8>>> {
        reader_from(Box::new(io::Cursor::new(gz)), true, inflate_thread)
            .map(|r| r.map(|r| r.name))
            .collect()
    }

    /// Every member of a multi-member stream is read, across chunk boundaries,
    /// and the inflate thread yields what inline inflation yields.
    #[test]
    fn inflate_thread_reads_every_gzip_member() {
        let mut gz = gzip(&fastq_records("a", 60_000));
        gz.extend(gzip(b""));
        gz.extend(gzip(&fastq_records("b", 3)));
        let names = gz_names(gz.clone(), true).unwrap();
        assert_eq!(names.len(), 60_003);
        assert_eq!(names[60_000], b"b0");
        assert_eq!(names, gz_names(gz, false).unwrap());
    }

    /// A damaged stream fails on the inflate thread as it does inline: the
    /// records before the damage are yielded, then the decoder's error rather
    /// than the end of the stream.
    #[test]
    fn inflate_thread_reports_damaged_gzip() {
        let gz = gzip(&fastq_records("r", 60_000));
        let truncated = gz[..gz.len() / 2].to_vec();
        for inflate_thread in [false, true] {
            let mut it = reader_from(
                Box::new(io::Cursor::new(truncated.clone())),
                true,
                inflate_thread,
            );
            let mut read = 0;
            let err = loop {
                match it.next().expect("The stream ends with an error") {
                    Ok(_) => read += 1,
                    Err(e) => break e,
                }
            };
            assert!(read > 0);
            assert!(
                format!("{err:#}").starts_with("reading FASTQ record after r"),
                "{err:#}"
            );
        }

        let mut corrupt = gzip(&fastq_records("r", 10));
        corrupt[12..20].copy_from_slice(b"\xff\xff\xff\xff\xff\xff\xff\xff");
        let inline = gz_names(corrupt.clone(), false).unwrap_err();
        let threaded = gz_names(corrupt, true).unwrap_err();
        assert_eq!(format!("{threaded:#}"), format!("{inline:#}"));
        assert!(
            format!("{threaded:#}").starts_with("reading the first FASTQ record: "),
            "{threaded:#}"
        );
    }

    #[test]
    fn parse_error_message_is_not_duplicated() {
        let fq = b"@r1\nACGT\n+\nII\n";
        let err = RecordIter::new(&fq[..]).next().unwrap().unwrap_err();
        let msg = format!("{err:#}");
        assert_eq!(msg.matches("FASTQ parse error").count(), 1, "{msg}");
    }

    /// The sequential `.fastq.gz` writer emits BGZF-framed gzip that a plain
    /// gzip decoder reads back.
    #[test]
    fn gz_writer_clamps_zero_workers_and_writes_bgzf() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("o.fastq.gz");
        let mut cfg = crate::cli::config_for_test(&path, &path, 0, 0);
        cfg.io.output = Some(path.clone());
        let mut w = writer(&cfg, crate::io::Format::FastqGz, false).unwrap();
        w.write_all(b"@r1\nACGT\n+\nIIII\n").unwrap();
        w.finish().unwrap();

        assert!(crate::io::is_bgzf_file(&path));
        let mut text = String::new();
        MultiGzDecoder::new(BufReader::new(std::fs::File::open(&path).unwrap()))
            .read_to_string(&mut text)
            .unwrap();
        assert_eq!(text, "@r1\nACGT\n+\nIIII\n");
    }

    #[test]
    fn bgzf_reader_roundtrips_fastq() {
        let fq = b"@r1\nACGT\n+\nIIII\n@r2 x\nTT\n+\n!!\n";
        let mut writer = noodles_bgzf::io::Writer::new(Vec::new());
        writer.write_all(fq).unwrap();
        let compressed = writer.finish().unwrap();

        let records: Vec<_> = reader_from_bgzf(Box::new(std::io::Cursor::new(compressed)), 1)
            .unwrap()
            .map(Result::unwrap)
            .collect();
        assert_eq!(records.len(), 2);
        assert_eq!(records[0].name, b"r1");
        assert_eq!(records[0].seq, b"ACGT");
        assert_eq!(records[1].name, b"r2 x");
    }

    use noodles_sam::alignment::record_buf::data::field::Value;
    use noodles_sam::alignment::record_buf::data::field::value::Array;

    /// One aux field in a buffer of its own, so an expectation reads as the
    /// field text rather than as the state of a shared buffer.
    fn aux(tag: [u8; 2], value: &Value) -> Vec<u8> {
        let mut out = Vec::new();
        push_aux_field(&mut out, tag, value);
        out
    }

    /// The MM/ML/MN block in a buffer of its own, for the same reason.
    fn mods_aux(
        mm: &[u8],
        ml: Option<&[u8]>,
        mn: usize,
        remove: &crate::config::TagRemoval,
    ) -> Vec<u8> {
        let mut out = Vec::new();
        push_mods_aux(&mut out, mm, ml, mn, remove);
        out
    }

    #[test]
    fn aux_scalar_types() {
        assert_eq!(
            aux(*b"RG", &Value::String(b"grp1".as_slice().into())),
            b"RG:Z:grp1"
        );
        assert_eq!(aux(*b"NM", &Value::Int32(-3)), b"NM:i:-3");
        assert_eq!(aux(*b"Uq", &Value::UInt8(200)), b"Uq:i:200");
        assert_eq!(aux(*b"pa", &Value::Float(0.5)), b"pa:f:0.5");
        assert_eq!(aux(*b"bc", &Value::Character(b'K')), b"bc:A:K");
        assert_eq!(
            aux(*b"H2", &Value::Hex(b"1AE3".as_slice().into())),
            b"H2:H:1AE3"
        );
        // Every integer width serializes with SAM type code `i`, regardless of
        // signedness or size.
        assert_eq!(aux(*b"i1", &Value::Int8(-5)), b"i1:i:-5");
        assert_eq!(aux(*b"i2", &Value::Int16(-300)), b"i2:i:-300");
        assert_eq!(aux(*b"i3", &Value::UInt16(400)), b"i3:i:400");
        assert_eq!(aux(*b"i4", &Value::UInt32(70000)), b"i4:i:70000");
    }

    #[test]
    fn aux_array_subtypes() {
        assert_eq!(
            aux(*b"a1", &Value::Array(Array::UInt8(vec![1, 2, 3]))),
            b"a1:B:C,1,2,3"
        );
        assert_eq!(
            aux(*b"a2", &Value::Array(Array::Int8(vec![-1, 2]))),
            b"a2:B:c,-1,2"
        );
        assert_eq!(
            aux(*b"a3", &Value::Array(Array::Int16(vec![-5]))),
            b"a3:B:s,-5"
        );
        assert_eq!(
            aux(*b"a4", &Value::Array(Array::UInt16(vec![5]))),
            b"a4:B:S,5"
        );
        assert_eq!(
            aux(*b"a5", &Value::Array(Array::Int32(vec![7]))),
            b"a5:B:i,7"
        );
        assert_eq!(
            aux(*b"a6", &Value::Array(Array::UInt32(vec![8]))),
            b"a6:B:I,8"
        );
        assert_eq!(
            aux(*b"a7", &Value::Array(Array::Float(vec![1.5]))),
            b"a7:B:f,1.5"
        );
    }

    /// `push_u64` agrees with `core::fmt` across the fast paths and the loop.
    /// The byte-element tables print every value as the digit loop does.
    #[test]
    fn comma_element_tables_match_the_digit_loop() {
        let all: Vec<u8> = (0..=255).collect();
        let mut fast = Vec::new();
        push_comma_u8s(&mut fast, &all);
        let mut slow = Vec::new();
        push_comma_u64s(&mut slow, all.iter().map(|&x| u64::from(x)));
        assert_eq!(fast, slow);

        let all: Vec<i8> = (-128..=127).collect();
        let mut fast = Vec::new();
        push_comma_i8s(&mut fast, &all);
        let mut slow = Vec::new();
        push_comma_i64s(&mut slow, all.iter().map(|&x| i64::from(x)));
        assert_eq!(fast, slow);
    }

    #[test]
    fn push_u64_matches_fmt() {
        for n in (0..1200).chain([9_999, 10_000, u64::from(u32::MAX), u64::MAX]) {
            let mut out = Vec::new();
            push_u64(&mut out, n);
            assert_eq!(out, n.to_string().as_bytes(), "{n}");
        }
        let mut out = Vec::new();
        push_i64(&mut out, i64::MIN);
        assert_eq!(out, i64::MIN.to_string().as_bytes());
    }

    #[test]
    fn mods_aux_layout() {
        let keep = crate::config::TagRemoval::default();
        assert_eq!(
            mods_aux(b"C+m,0;", Some(&[10, 20]), 6, &keep),
            b"\tMM:Z:C+m,0;\tML:B:C,10,20\tMN:i:6"
        );
        // ML present but empty (e.g. all mods sliced away yet MM retained) yields
        // a zero-length `B:C` array.
        assert_eq!(
            mods_aux(b"C+m;", Some(&[]), 4, &keep),
            b"\tMM:Z:C+m;\tML:B:C\tMN:i:4"
        );
        // ML absent (MM-only source record): the ML field is omitted rather than
        // emitted empty, so the record stays valid.
        assert_eq!(
            mods_aux(b"C+m,0;", None, 4, &keep),
            b"\tMM:Z:C+m,0;\tMN:i:4"
        );
        // Each removed field goes on its own, leaving the rest of the block.
        let removal = |tag: &str| crate::config::TagRemoval::parse(&[tag.to_string()]).unwrap();
        assert_eq!(
            mods_aux(b"C+m,0;", Some(&[10]), 6, &removal("ML")),
            b"\tMM:Z:C+m,0;\tMN:i:6"
        );
        assert_eq!(
            mods_aux(b"C+m,0;", Some(&[10]), 6, &removal("MN")),
            b"\tMM:Z:C+m,0;\tML:B:C,10"
        );
        assert_eq!(
            mods_aux(b"C+m,0;", Some(&[10]), 6, &removal("MM")),
            b"\tML:B:C,10\tMN:i:6"
        );
    }
}