binseq 0.9.0

A high efficiency binary format for sequencing data
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
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
//! Unified writer interface for BINSEQ formats
//!
//! This module provides a unified `BinseqWriter` enum that abstracts over the three
//! BINSEQ format writers (BQ, VBQ, CBQ), allowing format-agnostic writing of sequence data.
//!
//! # Example
//!
//! ```rust
//! use binseq::{write::{BinseqWriter, BinseqWriterBuilder, Format}, SequencingRecordBuilder};
//! use std::io::Cursor;
//!
//! // Create a VBQ writer with quality scores and headers
//! let mut writer = BinseqWriterBuilder::new(Format::Vbq)
//!     .paired(false)
//!     .quality(true)
//!     .headers(true)
//!     .build(Cursor::new(Vec::new()))
//!     .unwrap();
//!
//! // Write a record
//! let record = SequencingRecordBuilder::default()
//!     .s_seq(b"ACGTACGT")
//!     .s_qual(b"IIIIIIII")
//!     .s_header(b"seq1")
//!     .build()
//!     .unwrap();
//!
//! writer.push(record).unwrap();
//! writer.finish().unwrap();
//! ```
//!
//! # Parallel Writing
//!
//! For parallel writing scenarios, use `headless(true)` for thread-local writers
//! and `ingest()` to merge them into a global writer:
//!
//! ```rust,no_run
//! use binseq::{write::{BinseqWriter, BinseqWriterBuilder, Format}, SequencingRecordBuilder};
//! use std::fs::File;
//!
//! // Global writer (writes header)
//! let mut global = BinseqWriterBuilder::new(Format::Vbq)
//!     .paired(false)
//!     .build(File::create("output.vbq").unwrap())
//!     .unwrap();
//!
//! // Thread-local writer (headless, Vec<u8> buffer)
//! let mut local = global.new_headless_buffer().unwrap();
//!
//! // Write to local buffer
//! let record = SequencingRecordBuilder::default()
//!     .s_seq(b"ACGTACGT")
//!     .build()
//!     .unwrap();
//! local.push(record).unwrap();
//!
//! // Merge into global writer
//! global.ingest(&mut local).unwrap();
//! global.finish().unwrap();
//! ```

use std::{io::Write, str::FromStr};

use crate::{BitSize, Policy, Result, SequencingRecord, bq, cbq, error::WriteError, vbq};

/// Output format for BINSEQ files
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Format {
    /// BQ format - fixed length records, no quality scores
    Bq,
    /// VBQ format - variable length records, optional quality scores
    Vbq,
    /// CBQ format - columnar variable length records, optional quality scores
    #[default]
    Cbq,
}
impl FromStr for Format {
    type Err = String;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "bq" | "BQ" | "b" => Ok(Self::Bq),
            "vbq" | "VBQ" | "v" => Ok(Self::Vbq),
            "cbq" | "CBQ" | "c" => Ok(Self::Cbq),
            _ => Err(format!("Unknown format: {s}")),
        }
    }
}

impl Format {
    /// Returns the file extension for this format (including the dot)
    #[must_use]
    pub fn extension(&self) -> &'static str {
        match self {
            Self::Bq => ".bq",
            Self::Vbq => ".vbq",
            Self::Cbq => ".cbq",
        }
    }
}

/// Builder for creating [`BinseqWriter`] instances
///
/// This builder provides a unified interface for configuring writers across all
/// BINSEQ formats. Settings that don't apply to a particular format are silently
/// ignored.
///
/// # Format-specific behavior
///
/// | Setting | BQ | VBQ | CBQ |
/// |---------|:--:|:---:|:---:|
/// | `quality(true)` | ignored | applied | applied |
/// | `headers(true)` | ignored | applied | applied |
/// | `compression(true)` | ignored | applied | applied |
/// | `compression_level(n)` | ignored | ignored | applied |
/// | `block_size(n)` | ignored | applied | applied |
/// | `bitsize(b)` | applied | applied | ignored |
/// | `slen(n)` | **required** | ignored | ignored |
/// | `xlen(n)` | required if paired | ignored | ignored |
/// | `policy(p)` | applied | applied | ignored |
/// | `headless(true)` | applied | applied | applied |
#[derive(Debug, Clone)]
pub struct BinseqWriterBuilder {
    pub(crate) format: Format,
    pub(crate) paired: bool,
    quality: bool,
    headers: bool,
    flags: bool,
    compression: bool,
    compression_level: Option<i32>,
    block_size: Option<usize>,
    policy: Option<Policy>,
    headless: bool,
    bitsize: Option<BitSize>,
    pub(crate) slen: Option<u32>,
    pub(crate) xlen: Option<u32>,
}

impl BinseqWriterBuilder {
    /// Create a new builder for the specified format
    #[must_use]
    pub fn new(format: Format) -> Self {
        Self {
            format,
            paired: false,
            quality: false,
            headers: false,
            flags: false,
            compression: true,
            compression_level: None,
            block_size: None,
            policy: None,
            headless: false,
            bitsize: None,
            slen: None,
            xlen: None,
        }
    }

    /// Set whether records are paired-end
    #[must_use]
    pub fn paired(mut self, paired: bool) -> Self {
        self.paired = paired;
        self
    }

    /// Set whether to store quality scores (ignored for BQ)
    #[must_use]
    pub fn quality(mut self, quality: bool) -> Self {
        self.quality = quality;
        self
    }

    /// Set whether to store sequence headers (ignored for BQ)
    #[must_use]
    pub fn headers(mut self, headers: bool) -> Self {
        self.headers = headers;
        self
    }

    /// Set whether to store flags
    #[must_use]
    pub fn flags(mut self, flags: bool) -> Self {
        self.flags = flags;
        self
    }

    /// Set whether to compress data (ignored for BQ)
    #[must_use]
    pub fn compression(mut self, compression: bool) -> Self {
        self.compression = compression;
        self
    }

    /// Set the compression level (only applies to CBQ)
    #[must_use]
    pub fn compression_level(mut self, level: i32) -> Self {
        self.compression_level = Some(level);
        self
    }

    /// Set the block size in bytes (ignored for BQ)
    #[must_use]
    pub fn block_size(mut self, size: usize) -> Self {
        self.block_size = Some(size);
        self
    }

    /// Set the policy for handling invalid nucleotides (ignored for CBQ)
    #[must_use]
    pub fn policy(mut self, policy: Policy) -> Self {
        self.policy = Some(policy);
        self
    }

    /// Set whether to operate in headless mode (for parallel writing)
    #[must_use]
    pub fn headless(mut self, headless: bool) -> Self {
        self.headless = headless;
        self
    }

    /// Set the bit size for nucleotide encoding (ignored for CBQ)
    #[must_use]
    pub fn bitsize(mut self, bitsize: BitSize) -> Self {
        self.bitsize = Some(bitsize);
        self
    }

    /// Set the primary sequence length (required for BQ, ignored for VBQ/CBQ)
    #[must_use]
    pub fn slen(mut self, len: u32) -> Self {
        self.slen = Some(len);
        self
    }

    /// Set the extended sequence length (required for paired BQ, ignored for VBQ/CBQ)
    #[must_use]
    pub fn xlen(mut self, len: u32) -> Self {
        self.xlen = Some(len);
        self
    }

    /// Sets the corresponding values for this builder given an existing BQ header
    #[must_use]
    pub fn from_bq_header(header: bq::FileHeader) -> Self {
        Self {
            format: Format::Bq,
            slen: Some(header.slen),
            xlen: (header.xlen > 0).then_some(header.xlen),
            bitsize: Some(header.bits),
            paired: header.is_paired(),
            flags: header.flags,
            compression: false,
            headers: false,
            quality: false,
            compression_level: None,
            block_size: None,
            headless: false,
            policy: None,
        }
    }

    /// Sets the corresponding values for this builder given an existing VBQ header
    #[must_use]
    pub fn from_vbq_header(header: vbq::FileHeader) -> Self {
        Self {
            format: Format::Vbq,
            slen: None,
            xlen: None,
            flags: header.flags,
            quality: header.qual,
            paired: header.paired,
            bitsize: Some(header.bits),
            headers: header.headers,
            compression: header.compressed,
            block_size: Some(header.block as usize),
            policy: None,
            compression_level: None,
            headless: false,
        }
    }

    /// Sets the corresponding values for this builder given an existing CBQ header
    #[must_use]
    pub fn from_cbq_header(header: cbq::FileHeader) -> Self {
        Self {
            format: Format::Cbq,
            flags: header.has_flags(),
            quality: header.has_qualities(),
            headers: header.has_headers(),
            paired: header.is_paired(),
            block_size: Some(header.block_size as usize),
            compression_level: Some(header.compression_level as i32),
            compression: false,
            slen: None,
            xlen: None,
            bitsize: None,
            policy: None,
            headless: false,
        }
    }

    /// Encode FASTX file(s) to BINSEQ format
    ///
    /// This method returns a [`FastxEncoderBuilder`] that allows you to configure
    /// the input source and threading options before executing the encoding.
    ///
    /// This is an alternative to [`build`](Self::build) that directly processes
    /// FASTX files using parallel processing.
    ///
    /// # Availability
    ///
    /// This method is only available when the `paraseq` feature is enabled.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use binseq::write::{BinseqWriterBuilder, Format};
    /// use std::fs::File;
    ///
    /// // Encode from stdin to VBQ
    /// let writer = BinseqWriterBuilder::new(Format::Vbq)
    ///     .quality(true)
    ///     .headers(true)
    ///     .encode_fastx(File::create("output.vbq")?)
    ///     .input_stdin()
    ///     .threads(8)
    ///     .run()?;
    ///
    /// // Encode paired-end reads
    /// let writer = BinseqWriterBuilder::new(Format::Vbq)
    ///     .quality(true)
    ///     .encode_fastx(File::create("output.vbq")?)
    ///     .input_paired("R1.fastq", "R2.fastq")
    ///     .run()?;
    /// # Ok::<(), binseq::Error>(())
    /// ```
    #[cfg(feature = "paraseq")]
    #[must_use]
    pub fn encode_fastx<W: Write + Send + 'static>(
        self,
        output: W,
    ) -> crate::utils::FastxEncoderBuilder {
        crate::utils::FastxEncoderBuilder::new(self, Box::new(output))
    }

    /// Build the writer
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Format is BQ and `slen` is not set
    /// - Format is BQ, `paired` is true, but `xlen` is not set
    pub fn build<W: Write>(self, writer: W) -> Result<BinseqWriter<W>> {
        match self.format {
            Format::Bq => self.build_bq(writer),
            Format::Vbq => self.build_vbq(writer),
            Format::Cbq => self.build_cbq(writer),
        }
    }

    fn build_bq<W: Write>(self, writer: W) -> Result<BinseqWriter<W>> {
        let slen = self.slen.ok_or(WriteError::MissingSequenceLength {
            exp_primary: true,
            exp_extended: self.paired,
            obs_primary: self.slen.is_some(),
            obs_extended: self.xlen.is_some(),
        })?;
        let xlen = if self.paired || self.xlen.is_some_and(|x| x > 0) {
            self.xlen.ok_or(WriteError::MissingSequenceLength {
                exp_primary: true,
                exp_extended: true,
                obs_primary: self.slen.is_some(),
                obs_extended: self.xlen.is_some(),
            })?
        } else {
            0
        };

        let mut header_builder = bq::FileHeaderBuilder::new().slen(slen).xlen(xlen);

        if let Some(bitsize) = self.bitsize {
            header_builder = header_builder.bitsize(bitsize);
        }

        header_builder = header_builder.flags(self.flags);

        let header = header_builder.build()?;

        let inner = bq::WriterBuilder::default()
            .header(header)
            .policy(self.policy.unwrap_or_default())
            .headless(self.headless)
            .build(writer)?;

        Ok(BinseqWriter::Bq(inner))
    }

    fn build_vbq<W: Write>(self, writer: W) -> Result<BinseqWriter<W>> {
        let mut header_builder = vbq::FileHeaderBuilder::new()
            .paired(self.paired)
            .qual(self.quality)
            .headers(self.headers)
            .flags(self.flags)
            .compressed(self.compression);

        if let Some(block_size) = self.block_size {
            header_builder = header_builder.block(block_size as u64);
        }

        if let Some(bitsize) = self.bitsize {
            header_builder = header_builder.bitsize(bitsize);
        }

        let header = header_builder.build();

        let inner = vbq::WriterBuilder::default()
            .header(header)
            .policy(self.policy.unwrap_or_default())
            .headless(self.headless)
            .build(writer)?;

        Ok(BinseqWriter::Vbq(inner))
    }

    fn build_cbq<W: Write>(self, writer: W) -> Result<BinseqWriter<W>> {
        let header = cbq::FileHeaderBuilder::default()
            .is_paired(self.paired)
            .with_qualities(self.quality)
            .with_headers(self.headers)
            .with_flags(self.flags)
            .with_optional_block_size(self.block_size)
            .with_optional_compression_level(self.compression_level.map(|level| level as usize))
            .build();

        let inner = if self.headless {
            cbq::ColumnarBlockWriter::new_headless(writer, header)?
        } else {
            cbq::ColumnarBlockWriter::new(writer, header)?
        };

        Ok(BinseqWriter::Cbq(inner))
    }
}

/// Unified writer for BINSEQ formats
///
/// This enum wraps the three format-specific writers (BQ, VBQ, CBQ) and provides
/// a unified interface for writing sequence data.
pub enum BinseqWriter<W: Write> {
    /// BQ format writer
    Bq(bq::Writer<W>),
    /// VBQ format writer
    Vbq(vbq::Writer<W>),
    /// CBQ format writer
    Cbq(cbq::ColumnarBlockWriter<W>),
}

impl<W: Write> BinseqWriter<W> {
    /// Push a record to the writer
    ///
    /// Returns `Ok(true)` if the record was written successfully, or `Ok(false)`
    /// if the record was skipped due to invalid nucleotides (based on the configured
    /// policy). CBQ always returns `Ok(true)` as it handles N's explicitly.
    ///
    /// # Errors
    ///
    /// Returns an error if there's an I/O error or if the record doesn't match
    /// the writer's configuration (e.g., paired record to unpaired writer).
    pub fn push(&mut self, record: SequencingRecord) -> Result<bool> {
        match self {
            Self::Bq(w) => w.push(record),
            Self::Vbq(w) => w.push(record),
            Self::Cbq(w) => w.push(record),
        }
    }

    /// Finish writing and flush any remaining data
    ///
    /// For VBQ and CBQ formats, this writes the embedded index. For BQ, this
    /// is equivalent to `flush()`.
    ///
    /// # Errors
    ///
    /// Returns an error if there's an I/O error writing the final data.
    pub fn finish(&mut self) -> Result<()> {
        match self {
            Self::Bq(w) => w.flush(),
            Self::Vbq(w) => w.finish(),
            Self::Cbq(w) => w.finish(),
        }
    }

    /// Returns the format of this writer
    #[must_use]
    pub fn format(&self) -> Format {
        match self {
            Self::Bq(_) => Format::Bq,
            Self::Vbq(_) => Format::Vbq,
            Self::Cbq(_) => Format::Cbq,
        }
    }

    /// Returns whether this writer is configured for paired-end records
    #[must_use]
    pub fn is_paired(&self) -> bool {
        match self {
            Self::Bq(w) => w.is_paired(),
            Self::Vbq(w) => w.is_paired(),
            Self::Cbq(w) => w.header().is_paired(),
        }
    }

    /// Returns whether this writer stores quality scores
    ///
    /// Always returns `false` for BQ format.
    #[must_use]
    pub fn has_quality(&self) -> bool {
        match self {
            Self::Bq(_) => false,
            Self::Vbq(w) => w.has_quality(),
            Self::Cbq(w) => w.header().has_qualities(),
        }
    }

    /// Returns whether this writer stores sequence headers
    ///
    /// Always returns `false` for BQ format.
    #[must_use]
    pub fn has_headers(&self) -> bool {
        match self {
            Self::Bq(_) => false,
            Self::Vbq(w) => w.has_headers(),
            Self::Cbq(w) => w.header().has_headers(),
        }
    }
}

impl<W: Write + Clone> Clone for BinseqWriter<W> {
    fn clone(&self) -> Self {
        match self {
            Self::Bq(w) => Self::Bq(w.clone()),
            Self::Vbq(w) => Self::Vbq(w.clone()),
            Self::Cbq(w) => Self::Cbq(w.clone()),
        }
    }
}

impl<W: Write> BinseqWriter<W> {
    /// Ingest records from a headless `Vec<u8>` writer into this writer
    ///
    /// This is used in parallel writing scenarios where thread-local writers
    /// buffer to `Vec<u8>` and then get merged into a global writer.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The source and destination writers have different formats
    /// - The source and destination writers have incompatible headers
    /// - There's an I/O error during ingestion
    pub fn ingest(&mut self, other: &mut BinseqWriter<Vec<u8>>) -> Result<()> {
        match (self, other) {
            (Self::Bq(dst), BinseqWriter::Bq(src)) => dst.ingest(src),
            (Self::Vbq(dst), BinseqWriter::Vbq(src)) => dst.ingest(src),
            (Self::Cbq(dst), BinseqWriter::Cbq(src)) => dst.ingest(src),
            _ => Err(WriteError::FormatMismatch.into()),
        }
    }
}

impl<W: Write> BinseqWriter<W> {
    /// Create a new headless writer with the same configuration, using a `Vec<u8>` buffer
    ///
    /// This is useful for parallel writing scenarios where each thread has its own
    /// buffer that gets merged into a global writer via `ingest()`.
    ///
    /// # Errors
    ///
    /// Returns an error if the writer cannot be created.
    pub fn new_headless_buffer(&self) -> Result<BinseqWriter<Vec<u8>>> {
        match self {
            Self::Bq(w) => {
                let inner = bq::WriterBuilder::default()
                    .header(w.header())
                    .policy(w.policy())
                    .headless(true)
                    .build(Vec::new())?;
                Ok(BinseqWriter::Bq(inner))
            }
            Self::Vbq(w) => {
                let inner = vbq::WriterBuilder::default()
                    .header(w.header())
                    .policy(w.policy())
                    .headless(true)
                    .build(Vec::new())?;
                Ok(BinseqWriter::Vbq(inner))
            }
            Self::Cbq(w) => {
                let inner = cbq::ColumnarBlockWriter::new_headless(Vec::new(), w.header())?;
                Ok(BinseqWriter::Cbq(inner))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::SequencingRecordBuilder;
    use std::io::Cursor;

    #[test]
    fn test_format_extension() {
        assert_eq!(Format::Bq.extension(), ".bq");
        assert_eq!(Format::Vbq.extension(), ".vbq");
        assert_eq!(Format::Cbq.extension(), ".cbq");
    }

    #[test]
    fn test_build_bq_writer() -> Result<()> {
        let writer = BinseqWriterBuilder::new(Format::Bq)
            .slen(100)
            .paired(false)
            .build(Cursor::new(Vec::new()))?;

        assert_eq!(writer.format(), Format::Bq);
        assert!(!writer.is_paired());
        assert!(!writer.has_quality());
        assert!(!writer.has_headers());
        Ok(())
    }

    #[test]
    fn test_build_bq_writer_paired() -> Result<()> {
        let writer = BinseqWriterBuilder::new(Format::Bq)
            .slen(100)
            .xlen(150)
            .paired(true)
            .build(Cursor::new(Vec::new()))?;

        assert_eq!(writer.format(), Format::Bq);
        assert!(writer.is_paired());
        Ok(())
    }

    #[test]
    fn test_build_bq_missing_slen() {
        let result = BinseqWriterBuilder::new(Format::Bq)
            .paired(false)
            .build(Cursor::new(Vec::new()));

        assert!(result.is_err());
    }

    #[test]
    fn test_build_bq_paired_missing_xlen() {
        let result = BinseqWriterBuilder::new(Format::Bq)
            .slen(100)
            .paired(true)
            .build(Cursor::new(Vec::new()));

        assert!(result.is_err());
    }

    #[test]
    fn test_build_vbq_writer() -> Result<()> {
        let writer = BinseqWriterBuilder::new(Format::Vbq)
            .paired(true)
            .quality(true)
            .headers(true)
            .build(Cursor::new(Vec::new()))?;

        assert_eq!(writer.format(), Format::Vbq);
        assert!(writer.is_paired());
        assert!(writer.has_quality());
        assert!(writer.has_headers());
        Ok(())
    }

    #[test]
    fn test_build_cbq_writer() -> Result<()> {
        let writer = BinseqWriterBuilder::new(Format::Cbq)
            .paired(false)
            .quality(true)
            .headers(true)
            .compression_level(3)
            .build(Cursor::new(Vec::new()))?;

        assert_eq!(writer.format(), Format::Cbq);
        assert!(!writer.is_paired());
        assert!(writer.has_quality());
        assert!(writer.has_headers());
        Ok(())
    }

    #[test]
    fn test_push_and_finish_vbq() -> Result<()> {
        let mut writer = BinseqWriterBuilder::new(Format::Vbq)
            .paired(false)
            .quality(false)
            .headers(false)
            .build(Cursor::new(Vec::new()))?;

        let record = SequencingRecordBuilder::default()
            .s_seq(b"ACGTACGTACGT")
            .build()?;

        let written = writer.push(record)?;
        assert!(written);

        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_push_and_finish_cbq() -> Result<()> {
        let mut writer = BinseqWriterBuilder::new(Format::Cbq)
            .paired(false)
            .quality(false)
            .headers(false)
            .build(Cursor::new(Vec::new()))?;

        let record = SequencingRecordBuilder::default()
            .s_seq(b"ACGTACGTACGT")
            .build()?;

        let written = writer.push(record)?;
        assert!(written);

        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_push_and_finish_bq() -> Result<()> {
        let mut writer = BinseqWriterBuilder::new(Format::Bq)
            .slen(12)
            .paired(false)
            .build(Cursor::new(Vec::new()))?;

        let record = SequencingRecordBuilder::default()
            .s_seq(b"ACGTACGTACGT")
            .build()?;

        let written = writer.push(record)?;
        assert!(written);

        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_new_headless_buffer_vbq() -> Result<()> {
        let global = BinseqWriterBuilder::new(Format::Vbq)
            .paired(true)
            .quality(true)
            .headers(true)
            .build(Cursor::new(Vec::new()))?;

        let local = global.new_headless_buffer()?;

        assert_eq!(local.format(), Format::Vbq);
        assert!(local.is_paired());
        assert!(local.has_quality());
        assert!(local.has_headers());
        Ok(())
    }

    #[test]
    fn test_new_headless_buffer_cbq() -> Result<()> {
        let global = BinseqWriterBuilder::new(Format::Cbq)
            .paired(false)
            .quality(true)
            .build(Cursor::new(Vec::new()))?;

        let local = global.new_headless_buffer()?;

        assert_eq!(local.format(), Format::Cbq);
        assert!(!local.is_paired());
        assert!(local.has_quality());
        Ok(())
    }

    #[test]
    fn test_new_headless_buffer_bq() -> Result<()> {
        let global = BinseqWriterBuilder::new(Format::Bq)
            .slen(100)
            .xlen(150)
            .paired(true)
            .build(Cursor::new(Vec::new()))?;

        let local = global.new_headless_buffer()?;

        assert_eq!(local.format(), Format::Bq);
        assert!(local.is_paired());
        Ok(())
    }

    #[test]
    fn test_ingest_vbq() -> Result<()> {
        let mut global = BinseqWriterBuilder::new(Format::Vbq)
            .paired(false)
            .quality(false)
            .headers(false)
            .build(Cursor::new(Vec::new()))?;

        let mut local = global.new_headless_buffer()?;

        // Write to local
        let record = SequencingRecordBuilder::default()
            .s_seq(b"ACGTACGTACGT")
            .build()?;
        local.push(record)?;

        // Ingest into global
        global.ingest(&mut local)?;
        global.finish()?;

        Ok(())
    }

    #[test]
    fn test_ingest_cbq() -> Result<()> {
        let mut global = BinseqWriterBuilder::new(Format::Cbq)
            .paired(false)
            .quality(false)
            .headers(false)
            .build(Cursor::new(Vec::new()))?;

        let mut local = global.new_headless_buffer()?;

        // Write to local
        let record = SequencingRecordBuilder::default()
            .s_seq(b"ACGTACGTACGT")
            .build()?;
        local.push(record)?;

        // Ingest into global
        global.ingest(&mut local)?;
        global.finish()?;

        Ok(())
    }

    #[test]
    fn test_ingest_bq() -> Result<()> {
        let mut global = BinseqWriterBuilder::new(Format::Bq)
            .slen(12)
            .paired(false)
            .build(Cursor::new(Vec::new()))?;

        let mut local = global.new_headless_buffer()?;

        // Write to local
        let record = SequencingRecordBuilder::default()
            .s_seq(b"ACGTACGTACGT")
            .build()?;
        local.push(record)?;

        // Ingest into global
        global.ingest(&mut local)?;
        global.finish()?;

        Ok(())
    }

    #[test]
    fn test_ingest_format_mismatch() -> Result<()> {
        let mut global = BinseqWriterBuilder::new(Format::Vbq)
            .paired(false)
            .build(Cursor::new(Vec::new()))?;

        let mut local = BinseqWriterBuilder::new(Format::Cbq)
            .paired(false)
            .headless(true)
            .build(Vec::new())?;

        let result = global.ingest(&mut local);
        assert!(result.is_err());

        Ok(())
    }

    // ==================== Record Specification Tests ====================
    //
    // These tests verify that writers correctly handle records with different
    // levels of specification relative to the writer's configuration:
    // - Under-specified: record is missing data the writer needs (should error)
    // - Over-specified: record has extra data the writer ignores (should succeed)
    // - Correctly-specified: record matches writer config exactly (should succeed)

    /// Helper to create a minimal single-end record (sequence only)
    fn minimal_single_record() -> SequencingRecord<'static> {
        SequencingRecordBuilder::default()
            .s_seq(b"ACGTACGTACGTACGTACGTACGTACGTACGT")
            .build()
            .unwrap()
    }

    /// Helper to create a minimal paired record (sequences only)
    fn minimal_paired_record() -> SequencingRecord<'static> {
        SequencingRecordBuilder::default()
            .s_seq(b"ACGTACGTACGTACGTACGTACGTACGTACGT")
            .x_seq(b"TGCATGCATGCATGCATGCATGCATGCATGCA")
            .build()
            .unwrap()
    }

    /// Helper to create a fully-specified single-end record
    fn full_single_record() -> SequencingRecord<'static> {
        SequencingRecordBuilder::default()
            .s_seq(b"ACGTACGTACGTACGTACGTACGTACGTACGT")
            .s_qual(b"IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII")
            .s_header(b"read1")
            .flag(42u64)
            .build()
            .unwrap()
    }

    /// Helper to create a fully-specified paired record
    fn full_paired_record() -> SequencingRecord<'static> {
        SequencingRecordBuilder::default()
            .s_seq(b"ACGTACGTACGTACGTACGTACGTACGTACGT")
            .s_qual(b"IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII")
            .s_header(b"read1")
            .x_seq(b"TGCATGCATGCATGCATGCATGCATGCATGCA")
            .x_qual(b"JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ")
            .x_header(b"read2")
            .flag(42u64)
            .build()
            .unwrap()
    }

    // ==================== VBQ Tests ====================

    #[test]
    fn test_vbq_single_minimal_writer_minimal_record() -> Result<()> {
        // Writer: single-end, no quality, no headers, no flags
        // Record: single-end, no quality, no headers, no flags
        // Expected: success (correctly specified)
        let mut writer = BinseqWriterBuilder::new(Format::Vbq)
            .paired(false)
            .quality(false)
            .headers(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        let record = minimal_single_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_vbq_single_minimal_writer_full_record() -> Result<()> {
        // Writer: single-end, no quality, no headers, no flags
        // Record: single-end, with quality, headers, flags
        // Expected: success (over-specified - extra data ignored)
        let mut writer = BinseqWriterBuilder::new(Format::Vbq)
            .paired(false)
            .quality(false)
            .headers(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        let record = full_single_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_vbq_single_full_writer_minimal_record() -> Result<()> {
        // Writer: single-end, with quality, headers, flags
        // Record: single-end, no quality, no headers, no flags
        // Expected: error (under-specified)
        let mut writer = BinseqWriterBuilder::new(Format::Vbq)
            .paired(false)
            .quality(true)
            .headers(true)
            .flags(true)
            .build(Cursor::new(Vec::new()))?;

        let record = minimal_single_record();
        let result = writer.push(record);
        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn test_vbq_single_full_writer_full_record() -> Result<()> {
        // Writer: single-end, with quality, headers, flags
        // Record: single-end, with quality, headers, flags
        // Expected: success (correctly specified)
        let mut writer = BinseqWriterBuilder::new(Format::Vbq)
            .paired(false)
            .quality(true)
            .headers(true)
            .flags(true)
            .build(Cursor::new(Vec::new()))?;

        let record = full_single_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_vbq_paired_writer_single_record() -> Result<()> {
        // Writer: paired
        // Record: single-end
        // Expected: error (under-specified - missing R2)
        let mut writer = BinseqWriterBuilder::new(Format::Vbq)
            .paired(true)
            .quality(false)
            .headers(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        let record = minimal_single_record();
        let result = writer.push(record);
        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn test_vbq_single_writer_paired_record() -> Result<()> {
        // Writer: single-end
        // Record: paired
        // Expected: success (over-specified - R2 ignored)
        let mut writer = BinseqWriterBuilder::new(Format::Vbq)
            .paired(false)
            .quality(false)
            .headers(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        let record = minimal_paired_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_vbq_paired_minimal_writer_paired_full_record() -> Result<()> {
        // Writer: paired, no quality, no headers, no flags
        // Record: paired, with quality, headers, flags
        // Expected: success (over-specified)
        let mut writer = BinseqWriterBuilder::new(Format::Vbq)
            .paired(true)
            .quality(false)
            .headers(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        let record = full_paired_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_vbq_paired_full_writer_paired_full_record() -> Result<()> {
        // Writer: paired, with quality, headers, flags
        // Record: paired, with quality, headers, flags
        // Expected: success (correctly specified)
        let mut writer = BinseqWriterBuilder::new(Format::Vbq)
            .paired(true)
            .quality(true)
            .headers(true)
            .flags(true)
            .build(Cursor::new(Vec::new()))?;

        let record = full_paired_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    // ==================== CBQ Tests ====================

    #[test]
    fn test_cbq_single_minimal_writer_minimal_record() -> Result<()> {
        // Writer: single-end, no quality, no headers, no flags
        // Record: single-end, no quality, no headers, no flags
        // Expected: success (correctly specified)
        let mut writer = BinseqWriterBuilder::new(Format::Cbq)
            .paired(false)
            .quality(false)
            .headers(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        let record = minimal_single_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_cbq_single_minimal_writer_full_record() -> Result<()> {
        // Writer: single-end, no quality, no headers, no flags
        // Record: single-end, with quality, headers, flags
        // Expected: success (over-specified - extra data ignored)
        let mut writer = BinseqWriterBuilder::new(Format::Cbq)
            .paired(false)
            .quality(false)
            .headers(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        let record = full_single_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_cbq_single_full_writer_minimal_record() -> Result<()> {
        // Writer: single-end, with quality, headers, flags
        // Record: single-end, no quality, no headers, no flags
        // Expected: error (under-specified)
        let mut writer = BinseqWriterBuilder::new(Format::Cbq)
            .paired(false)
            .quality(true)
            .headers(true)
            .flags(true)
            .build(Cursor::new(Vec::new()))?;

        let record = minimal_single_record();
        let result = writer.push(record);
        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn test_cbq_single_full_writer_full_record() -> Result<()> {
        // Writer: single-end, with quality, headers, flags
        // Record: single-end, with quality, headers, flags
        // Expected: success (correctly specified)
        let mut writer = BinseqWriterBuilder::new(Format::Cbq)
            .paired(false)
            .quality(true)
            .headers(true)
            .flags(true)
            .build(Cursor::new(Vec::new()))?;

        let record = full_single_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_cbq_paired_writer_single_record() -> Result<()> {
        // Writer: paired
        // Record: single-end
        // Expected: error (under-specified - missing R2)
        let mut writer = BinseqWriterBuilder::new(Format::Cbq)
            .paired(true)
            .quality(false)
            .headers(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        let record = minimal_single_record();
        let result = writer.push(record);
        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn test_cbq_single_writer_paired_record() -> Result<()> {
        // Writer: single-end
        // Record: paired
        // Expected: success (over-specified - R2 ignored)
        let mut writer = BinseqWriterBuilder::new(Format::Cbq)
            .paired(false)
            .quality(false)
            .headers(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        let record = minimal_paired_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_cbq_paired_minimal_writer_paired_full_record() -> Result<()> {
        // Writer: paired, no quality, no headers, no flags
        // Record: paired, with quality, headers, flags
        // Expected: success (over-specified)
        let mut writer = BinseqWriterBuilder::new(Format::Cbq)
            .paired(true)
            .quality(false)
            .headers(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        let record = full_paired_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_cbq_paired_full_writer_paired_full_record() -> Result<()> {
        // Writer: paired, with quality, headers, flags
        // Record: paired, with quality, headers, flags
        // Expected: success (correctly specified)
        let mut writer = BinseqWriterBuilder::new(Format::Cbq)
            .paired(true)
            .quality(true)
            .headers(true)
            .flags(true)
            .build(Cursor::new(Vec::new()))?;

        let record = full_paired_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    // ==================== BQ Tests ====================
    // Note: BQ format has fixed-length sequences and doesn't support headers

    #[test]
    fn test_bq_single_minimal_writer_minimal_record() -> Result<()> {
        // Writer: single-end, no quality, no flags
        // Record: single-end, no quality, no flags
        // Expected: success (correctly specified)
        let mut writer = BinseqWriterBuilder::new(Format::Bq)
            .slen(32)
            .paired(false)
            .quality(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        let record = minimal_single_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_bq_single_minimal_writer_full_record() -> Result<()> {
        // Writer: single-end, no quality, no flags
        // Record: single-end, with quality, headers, flags
        // Expected: success (over-specified - extra data ignored)
        let mut writer = BinseqWriterBuilder::new(Format::Bq)
            .slen(32)
            .paired(false)
            .quality(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        let record = full_single_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_bq_single_with_quality_writer_minimal_record() -> Result<()> {
        // Writer: single-end, with quality (note: BQ ignores quality setting)
        // Record: single-end, no quality
        // Expected: success (BQ format doesn't support quality scores, setting is ignored)
        let mut writer = BinseqWriterBuilder::new(Format::Bq)
            .slen(32)
            .paired(false)
            .quality(true) // This is ignored for BQ format
            .build(Cursor::new(Vec::new()))?;

        // BQ always reports has_quality as false
        assert!(!writer.has_quality());

        let record = minimal_single_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_bq_single_with_quality_writer_full_record() -> Result<()> {
        // Writer: single-end, with quality
        // Record: single-end, with quality
        // Expected: success (correctly specified)
        let mut writer = BinseqWriterBuilder::new(Format::Bq)
            .slen(32)
            .paired(false)
            .quality(true)
            .build(Cursor::new(Vec::new()))?;

        let record = full_single_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_bq_paired_writer_single_record() -> Result<()> {
        // Writer: paired
        // Record: single-end
        // Expected: error (under-specified - missing R2)
        let mut writer = BinseqWriterBuilder::new(Format::Bq)
            .slen(32)
            .xlen(32)
            .paired(true)
            .quality(false)
            .build(Cursor::new(Vec::new()))?;

        let record = minimal_single_record();
        let result = writer.push(record);
        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn test_bq_single_writer_paired_record() -> Result<()> {
        // Writer: single-end
        // Record: paired
        // Expected: success (over-specified - R2 ignored)
        let mut writer = BinseqWriterBuilder::new(Format::Bq)
            .slen(32)
            .paired(false)
            .quality(false)
            .build(Cursor::new(Vec::new()))?;

        let record = minimal_paired_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_bq_paired_minimal_writer_paired_full_record() -> Result<()> {
        // Writer: paired, no quality, no flags
        // Record: paired, with quality, headers, flags
        // Expected: success (over-specified)
        let mut writer = BinseqWriterBuilder::new(Format::Bq)
            .slen(32)
            .xlen(32)
            .paired(true)
            .quality(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        let record = full_paired_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_bq_paired_full_writer_paired_full_record() -> Result<()> {
        // Writer: paired, with quality, flags
        // Record: paired, with quality, headers, flags
        // Expected: success (correctly specified, headers ignored for BQ)
        let mut writer = BinseqWriterBuilder::new(Format::Bq)
            .slen(32)
            .xlen(32)
            .paired(true)
            .quality(true)
            .flags(true)
            .build(Cursor::new(Vec::new()))?;

        let record = full_paired_record();
        assert!(writer.push(record)?);
        writer.finish()?;
        Ok(())
    }

    // ==================== Configured Size Calculation Tests ====================

    #[test]
    fn test_configured_size_cbq_single_minimal() {
        let record = minimal_single_record();
        // 32 nucleotides = 1 u64 word = 8 bytes
        let size = record.configured_size_cbq(false, false, false, false);
        assert_eq!(size, 8);
    }

    #[test]
    fn test_configured_size_cbq_single_with_flags() {
        let record = full_single_record();
        // 32 nucleotides = 8 bytes + 8 bytes flag
        let size = record.configured_size_cbq(false, true, false, false);
        assert_eq!(size, 16);
    }

    #[test]
    fn test_configured_size_cbq_single_with_all() {
        let record = full_single_record();
        // 32 nucleotides = 8 bytes
        // + 8 bytes flag
        // + 5 bytes header ("read1")
        // + 32 bytes quality
        let size = record.configured_size_cbq(false, true, true, true);
        assert_eq!(size, 8 + 8 + 5 + 32);
    }

    #[test]
    fn test_configured_size_cbq_paired_minimal() {
        let record = full_paired_record();
        // s_seq: 32 nucleotides = 8 bytes
        // x_seq: 32 nucleotides = 8 bytes
        let size = record.configured_size_cbq(true, false, false, false);
        assert_eq!(size, 16);
    }

    #[test]
    fn test_configured_size_cbq_paired_with_all() {
        let record = full_paired_record();
        // s_seq: 32 nucleotides = 8 bytes
        // x_seq: 32 nucleotides = 8 bytes
        // flag: 8 bytes
        // s_header: 5 bytes ("read1")
        // x_header: 5 bytes ("read2")
        // s_qual: 32 bytes
        // x_qual: 32 bytes
        let size = record.configured_size_cbq(true, true, true, true);
        assert_eq!(size, 8 + 8 + 8 + 5 + 5 + 32 + 32);
    }

    #[test]
    fn test_configured_size_cbq_paired_record_single_writer() {
        // A paired record being written to a single-end writer
        // should only count R1 data
        let record = full_paired_record();
        let size = record.configured_size_cbq(false, true, true, true);
        // Only s_seq (8) + flag (8) + s_header (5) + s_qual (32)
        assert_eq!(size, 8 + 8 + 5 + 32);
    }

    #[test]
    fn test_configured_size_vbq_single_minimal() {
        use bitnuc::BitSize;
        let record = minimal_single_record();
        // s_len (8) + x_len (8) + s_seq (32 nucs = 1 word = 8 bytes)
        let size = record.configured_size_vbq(false, false, false, false, BitSize::Two);
        assert_eq!(size, 16 + 8);
    }

    #[test]
    fn test_configured_size_vbq_single_with_flags() {
        use bitnuc::BitSize;
        let record = full_single_record();
        // s_len (8) + x_len (8) + flag (8) + s_seq (8)
        let size = record.configured_size_vbq(false, true, false, false, BitSize::Two);
        assert_eq!(size, 16 + 8 + 8);
    }

    #[test]
    fn test_configured_size_vbq_single_with_all() {
        use bitnuc::BitSize;
        let record = full_single_record();
        // s_len (8) + x_len (8) + flag (8) + s_seq (8) + s_qual (32) + s_header_len (8) + s_header (5)
        let size = record.configured_size_vbq(false, true, true, true, BitSize::Two);
        assert_eq!(size, 16 + 8 + 8 + 32 + 8 + 5);
    }

    #[test]
    fn test_configured_size_vbq_paired_minimal() {
        use bitnuc::BitSize;
        let record = full_paired_record();
        // s_len (8) + x_len (8) + s_seq (8) + x_seq (8)
        let size = record.configured_size_vbq(true, false, false, false, BitSize::Two);
        assert_eq!(size, 16 + 8 + 8);
    }

    #[test]
    fn test_configured_size_vbq_paired_with_all() {
        use bitnuc::BitSize;
        let record = full_paired_record();
        // s_len (8) + x_len (8) + flag (8) + s_seq (8) + x_seq (8)
        // + s_qual (32) + x_qual (32)
        // + s_header_len (8) + s_header (5) + x_header_len (8) + x_header (5)
        let size = record.configured_size_vbq(true, true, true, true, BitSize::Two);
        assert_eq!(size, 16 + 8 + 8 + 8 + 32 + 32 + 8 + 5 + 8 + 5);
    }

    #[test]
    fn test_configured_size_vbq_paired_record_single_writer() {
        use bitnuc::BitSize;
        // A paired record being written to a single-end writer
        // should only count R1 data
        let record = full_paired_record();
        let size = record.configured_size_vbq(false, true, true, true, BitSize::Two);
        // s_len (8) + x_len (8) + flag (8) + s_seq (8) + s_qual (32) + s_header_len (8) + s_header (5)
        assert_eq!(size, 16 + 8 + 8 + 32 + 8 + 5);
    }

    #[test]
    fn test_configured_size_vbq_four_bit_encoding() {
        use bitnuc::BitSize;
        let record = minimal_single_record();
        // With 4-bit encoding: 2 nucleotides per byte, 16 per word
        // 32 nucleotides = 2 words = 16 bytes
        // s_len (8) + x_len (8) + s_seq (16)
        let size = record.configured_size_vbq(false, false, false, false, BitSize::Four);
        assert_eq!(size, 16 + 16);
    }

    // ==================== Multiple Records Tests ====================

    #[test]
    fn test_vbq_multiple_records_mixed_specification() -> Result<()> {
        // Writer configured minimally, records over-specified
        let mut writer = BinseqWriterBuilder::new(Format::Vbq)
            .paired(false)
            .quality(false)
            .headers(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        // Push minimal record
        assert!(writer.push(minimal_single_record())?);
        // Push full record (over-specified, should work)
        assert!(writer.push(full_single_record())?);
        // Push paired record (over-specified, R2 ignored)
        assert!(writer.push(full_paired_record())?);

        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_cbq_multiple_records_mixed_specification() -> Result<()> {
        // Writer configured minimally, records over-specified
        let mut writer = BinseqWriterBuilder::new(Format::Cbq)
            .paired(false)
            .quality(false)
            .headers(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        // Push minimal record
        assert!(writer.push(minimal_single_record())?);
        // Push full record (over-specified, should work)
        assert!(writer.push(full_single_record())?);
        // Push paired record (over-specified, R2 ignored)
        assert!(writer.push(full_paired_record())?);

        writer.finish()?;
        Ok(())
    }

    #[test]
    fn test_bq_multiple_records_mixed_specification() -> Result<()> {
        // Writer configured minimally, records over-specified
        let mut writer = BinseqWriterBuilder::new(Format::Bq)
            .slen(32)
            .paired(false)
            .quality(false)
            .flags(false)
            .build(Cursor::new(Vec::new()))?;

        // Push minimal record
        assert!(writer.push(minimal_single_record())?);
        // Push full record (over-specified, should work)
        assert!(writer.push(full_single_record())?);
        // Push paired record (over-specified, R2 ignored)
        assert!(writer.push(full_paired_record())?);

        writer.finish()?;
        Ok(())
    }
}