seqair 0.1.0

Pure-Rust BAM/SAM/CRAM/FASTA reader and pileup engine
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
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
//! Walk a record's CIGAR operations, yielding typed [`AlignedPair`] variants.
//!
//! This is the record-walking complement to [`CigarMapping::pos_info_at`](super::cigar::CigarMapping::pos_info_at),
//! which looks up query positions by reference position (column-at-a-time for the pileup engine).
//! `AlignedPairs` iterates per-CIGAR-op — useful for recomputing NM/MD tags, per-position
//! annotations, motif inference, and any per-record walk that needs both `qpos` and `rpos`.
//!
//! Default mode yields only position-bearing ops (`Match`, `Insertion`, `Deletion`, `RefSkip`).
//! Opt in to `SoftClip` via [`.with_soft_clips()`](AlignedPairs::with_soft_clips) or
//! all ops via [`.full()`](AlignedPairs::full).
//!
//! # Layered views
//!
//! [`AlignedPairs::with_read`] attaches the read's seq/qual to the events;
//! `.with_reference(&ref_seq)` further attaches reference base lookups.
//! See [`super::aligned_pairs_view`] for the layered API and the
//! `aligned_pairs_walk` example crate-side for an end-to-end walk over a real
//! BAM/FASTA pair (`cargo run --example aligned_pairs_walk -- --help`).
//!
//! # Quick reference
//!
//! | Need | API |
//! |---|---|
//! | Positions only (cheapest) | `slim.aligned_pairs(store)?` |
//! | Positions + read base/qual | `slim.aligned_pairs_with_read(store)?` |
//! | Positions + read + ref base | `…aligned_pairs_with_read(store)?.with_reference(&ref_seq)` |
//! | M-vs-=-vs-X distinction | `AlignedPair::Match { kind, .. }` (`MatchKind` enum) |
//! | Soft clips visible | `.with_soft_clips()` on any layer |
//! | Padding/Unknown visible | `.full()` on any layer |

use super::cigar::{CigarOp, CigarOpType};
use super::record_store::{RecordAccessError, RecordStore, SlimRecord};
use seqair_types::Pos0;
use thiserror::Error;

// ── Errors ─────────────────────────────────────────────────────────────────

/// Errors raised by `aligned_pairs*` constructors.
///
/// Iteration itself is infallible — once the iterator is constructed it does
/// not return errors. All validation happens up front.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum AlignedPairsError {
    /// Failed to read CIGAR / seq / qual bytes from the [`RecordStore`].
    #[error("record access error")]
    Access {
        #[from]
        source: RecordAccessError,
    },

    /// An unmapped record (`pos = None`) carries CIGAR operations.
    /// Per [SAM1] §1.4, unmapped reads must have an empty CIGAR. Walking
    /// CIGAR ops without a base reference position would produce nonsense
    /// `rpos` values, so we refuse rather than silently anchor to position 0.
    #[error(
        "unmapped record (pos = None) has {cigar_ops} CIGAR op(s); only an empty CIGAR is valid \
         for unmapped records — check flags and CIGAR consistency before constructing the walk"
    )]
    UnmappedWithCigar { cigar_ops: usize },

    /// CIGAR's query-consuming length disagrees with `seq.len()`. The walk
    /// would slice past the end of the sequence and silently substitute
    /// [`Base::Unknown`](seqair_types::Base::Unknown), which is
    /// indistinguishable from a legitimate `N` in the read.
    #[error(
        "CIGAR query-consuming length {cigar_qlen} != seq length {seq_len} — record's seq slab \
         and CIGAR are out of sync"
    )]
    CigarSeqLengthMismatch { cigar_qlen: u64, seq_len: usize },

    /// Quality slab length disagrees with `seq.len()`. BAM allows missing
    /// qual (filled with `0xFF`), in which case `qual.len() == 0` is
    /// accepted; any other length is a structural mismatch.
    #[error(
        "qual length {qual_len} != seq length {seq_len} — qual slab must be either empty (BAM \
         missing-qual sentinel) or match seq length exactly"
    )]
    SeqQualLengthMismatch { seq_len: usize, qual_len: usize },
}

// ── MatchKind ──────────────────────────────────────────────────────────────

// r[impl cigar.aligned_pairs.match_kind]
/// Distinguishes the three aligner-emitted "matched-base" CIGAR ops.
///
/// htslib's `aligned_pairs_full` collapses M/=/X into a single tuple shape,
/// losing the per-op distinction. [`AlignedPair::Match`] preserves it via this
/// field so callers that care (e.g. NM/MD recompute, variant calling against
/// `=`/`X` CIGARs) don't have to re-walk the CIGAR.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MatchKind {
    /// `M` (BAM op 0) — alignment match, ambiguous between sequence match and
    /// mismatch. The aligner did not commit either way.
    Match,
    /// `=` (BAM op 7) — explicit sequence match.
    SeqMatch,
    /// `X` (BAM op 8) — explicit sequence mismatch.
    SeqMismatch,
}

// ── AlignedPair ────────────────────────────────────────────────────────────

// r[impl cigar.aligned_pairs.types]
/// A typed aligned pair — one event from walking a record's CIGAR.
///
/// Unlike htslib's `(Option<i64>, Option<i64>)`, this enum uses typed variants:
/// `Match` carries both positions plus a [`MatchKind`] tag, `Insertion`
/// carries `qpos`+len, `Deletion` carries `rpos`+len, `RefSkip` carries
/// `rpos`+len. Match ops expand per-position; I/D/N/S ops yield once per op
/// (summary form).
///
/// # Example
/// ```ignore
/// for pair in record.aligned_pairs(store)? {
///     match pair {
///         AlignedPair::Match { qpos, rpos, kind } => { /* M, =, or X */ }
///         AlignedPair::Insertion { qpos, insert_len } => { /* I */ }
///         AlignedPair::Deletion { rpos, del_len } => { /* D */ }
///         AlignedPair::RefSkip { rpos, skip_len } => { /* N */ }
///         _ => {}
///     }
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlignedPair {
    /// M / = / X op — read base aligned to a reference base.
    /// Yields one variant per consumed position. Use `kind` to distinguish
    /// `M` (ambiguous) from `=` (explicit match) and `X` (explicit mismatch).
    Match { qpos: u32, rpos: Pos0, kind: MatchKind },

    /// I op — `insert_len` query bases follow `qpos`, no reference span.
    /// `qpos` is the position of the first inserted base.
    Insertion { qpos: u32, insert_len: u32 },

    /// D op — `del_len` reference bases starting at `rpos`, no query span.
    Deletion { rpos: Pos0, del_len: u32 },

    /// N op — reference skip (e.g. intron).
    RefSkip { rpos: Pos0, skip_len: u32 },

    /// S op — soft clip. `qpos` is the start of the clipped run.
    /// Hidden by default; opt in via [`.with_soft_clips()`](AlignedPairs::with_soft_clips) or [`.full()`](AlignedPairs::full).
    SoftClip { qpos: u32, len: u32 },

    /// P op — padding. `len` is the op length (typically small — most aligners
    /// emit `1P` or `0P`). Hidden by default; opt in via [`.full()`](AlignedPairs::full).
    Padding { len: u32 },

    /// Reserved op code (9..=15) we tolerate on read. `code` is the raw 4-bit op.
    /// Yielded by [`.full()`](AlignedPairs::full) only.
    Unknown { code: u8, len: u32 },
}

// Compile-time size guard: enum stays small enough for a hot-path iterator.
// Match { u32, u32, MatchKind(u8) } = 9 bytes payload, padded to 12. Plus a
// 1-byte discriminant rounded up by alignment → 16 bytes total.
const _: () = assert!(
    std::mem::size_of::<AlignedPair>() <= 16,
    "AlignedPair grew past 16 bytes — revisit before accepting the hit"
);

// ── MatchPosition ──────────────────────────────────────────────────────────

// r[impl cigar.aligned_pairs.matches_only.types]
/// A position from a `Match` event, stripped of the enum and indel variants.
///
/// Returned by [`AlignedPairs::matches_only`] when the caller only wants
/// matched query/reference positions and doesn't care about indels. This is
/// the seqair equivalent of pysam's `aligned_pairs(matches_only=True)` and
/// rust-htslib's `BamRecordExtensions::aligned_pairs()`.
///
/// `kind` is preserved so callers can distinguish `M` (ambiguous) from `=`
/// (explicit match) and `X` (explicit mismatch); htslib's variant collapses
/// these.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MatchPosition {
    pub qpos: u32,
    pub rpos: Pos0,
    pub kind: MatchKind,
}

// ── AlignedPairsOptions ────────────────────────────────────────────────────

// r[impl cigar.aligned_pairs.options]
/// Controls which [`AlignedPair`] variants the iterator yields.
#[derive(Debug, Clone, Copy, Default)]
pub struct AlignedPairsOptions {
    /// Yield [`AlignedPair::SoftClip`] variants. Default `false`.
    pub soft_clips: bool,
    /// Yield [`AlignedPair::Padding`] and [`AlignedPair::Unknown`].
    /// Default `false` — most consumers are confused by P ops.
    pub padding_and_unknown: bool,
}

// ── AlignedPairs iterator ─────────────────────────────────────────────────

// r[impl cigar.aligned_pairs.iterator]
// r[impl cigar.aligned_pairs.default_mode]
/// Iterator over a record's CIGAR operations, yielding typed [`AlignedPair`]s.
///
/// # Default mode
///
/// Only `Match`, `Insertion`, `Deletion`, and `RefSkip` are yielded.
/// Soft clips, padding, and unknown ops are silently skipped.
///
/// # Builder methods
///
/// - `.with_soft_clips()` — also yield `SoftClip` variants
/// - `.full()` — yield everything including `Padding` and `Unknown`
///
/// # Example
///
/// ```ignore
/// for pair in record.aligned_pairs(store)?.full() {
///     match pair {
///         AlignedPair::Match { qpos, rpos } => { /* ... */ }
///         AlignedPair::Insertion { qpos, insert_len } => { /* ... */ }
///         // ...
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct AlignedPairs<'a> {
    /// Remaining CIGAR ops to process.
    ops: &'a [CigarOp],
    /// Current 0-based query position (includes soft clips).
    qpos: u32,
    /// Current 0-based reference position.
    rpos: Pos0,
    /// Which variants to yield.
    options: AlignedPairsOptions,
    /// Multi-base expansion state for M/=/X ops.
    expanding: ExpandingState,
}

#[derive(Debug, Clone, Copy)]
enum ExpandingState {
    None,
    /// Yield one Match per remaining base. `kind` is fixed for the run
    /// (all expanded yields of an M op are M, not interleaved with =/X).
    PerBase {
        remaining: u32,
        kind: MatchKind,
    },
}

impl<'a> AlignedPairs<'a> {
    // r[impl cigar.aligned_pairs.default_mode]
    /// Create a new iterator over `cigar` starting at reference position `rec_pos`.
    ///
    /// Default mode yields `Match`, `Insertion`, `Deletion`, `RefSkip` only.
    pub fn new(rec_pos: Pos0, cigar: &'a [CigarOp]) -> Self {
        Self {
            ops: cigar,
            qpos: 0,
            rpos: rec_pos,
            options: AlignedPairsOptions::default(),
            expanding: ExpandingState::None,
        }
    }

    // r[impl cigar.aligned_pairs.options]
    /// Also yield [`AlignedPair::SoftClip`] variants.
    pub fn with_soft_clips(mut self) -> Self {
        self.options.soft_clips = true;
        self
    }

    // r[impl cigar.aligned_pairs.options]
    /// Yield all variants including [`AlignedPair::SoftClip`],
    /// [`AlignedPair::Padding`], and [`AlignedPair::Unknown`].
    pub fn full(mut self) -> Self {
        self.options.soft_clips = true;
        self.options.padding_and_unknown = true;
        self
    }

    // r[impl cigar.aligned_pairs.with_read.iterator]
    /// Attach the read's sequence and quality slabs, producing an
    /// [`AlignedPairsWithRead`](super::aligned_pairs_view::AlignedPairsWithRead)
    /// that yields events enriched with the per-position read base and qual,
    /// and pre-sliced inserted/clipped runs.
    ///
    /// Validates up front:
    /// - the iterator's remaining query-consuming CIGAR length fits inside
    ///   `seq[qpos..]` — otherwise returns
    ///   [`AlignedPairsError::CigarSeqLengthMismatch`];
    /// - `qual.len()` equals `seq.len()` or is zero (BAM missing-qual
    ///   sentinel) — otherwise returns
    ///   [`AlignedPairsError::SeqQualLengthMismatch`].
    ///
    /// Once construction succeeds, iteration is infallible — every yielded
    /// `Match`/`Insertion`/`SoftClip` index is provably in-bounds.
    ///
    /// Lifetimes are split: `'cigar` ties to the CIGAR slice, `'read` ties to
    /// the seq/qual slabs. They may differ, allowing callers to compose
    /// borrows from different stores or buffers.
    ///
    /// # Example
    /// ```ignore
    /// for ev in slim.aligned_pairs(&store)?.with_read(seq, qual)? {
    ///     // ...
    /// }
    /// ```
    // r[impl cigar.aligned_pairs.matches_only.bare]
    /// Filter to `Match` events only, yielding flat [`MatchPosition`] values.
    ///
    /// Equivalent to filtering `AlignedPair::Match` and stripping the enum,
    /// but the named adapter makes intent visible at the call site and gives
    /// callers a clean type for function signatures. Indels and clips are
    /// dropped silently.
    ///
    /// # Example
    /// ```ignore
    /// for m in slim.aligned_pairs(&store)?.matches_only() {
    ///     // m.qpos, m.rpos, m.kind — no enum dispatch needed
    /// }
    /// ```
    pub fn matches_only(self) -> MatchesOnly<'a> {
        MatchesOnly { inner: self }
    }

    pub fn with_read<'read>(
        self,
        seq: &'read [seqair_types::Base],
        qual: &'read [seqair_types::BaseQuality],
    ) -> Result<super::aligned_pairs_view::AlignedPairsWithRead<'a, 'read>, AlignedPairsError> {
        // Compute the remaining query-consuming CIGAR length and compare to
        // `seq[qpos..]`. We work in u64 so a runaway 32-bit CIGAR can't
        // wrap; real-world records are far below this.
        let cigar_remaining_qlen: u64 =
            self.ops.iter().filter(|op| op.consumes_query()).map(|op| u64::from(op.len())).sum();
        let qpos_consumed = u64::from(self.qpos);
        let total_qlen = cigar_remaining_qlen.saturating_add(qpos_consumed);
        // total_qlen represents the total query-consuming length the iterator
        // expects across the *full* CIGAR (already-consumed + remaining). The
        // seq slab must cover all of it. Strict equality lets us also catch
        // the inverse mismatch (seq longer than CIGAR claims).
        if total_qlen != seq.len() as u64 {
            return Err(AlignedPairsError::CigarSeqLengthMismatch {
                cigar_qlen: total_qlen,
                seq_len: seq.len(),
            });
        }
        if !qual.is_empty() && qual.len() != seq.len() {
            return Err(AlignedPairsError::SeqQualLengthMismatch {
                seq_len: seq.len(),
                qual_len: qual.len(),
            });
        }
        Ok(super::aligned_pairs_view::AlignedPairsWithRead::new(self, seq, qual))
    }
}

impl Iterator for AlignedPairs<'_> {
    type Item = AlignedPair;

    fn size_hint(&self) -> (usize, Option<usize>) {
        // We can compute the exact remaining count by walking the unprocessed
        // CIGAR ops with the current options + expansion state. Each call is
        // O(n_ops) which is fine: n_ops is small (single-digit on Illumina,
        // tens on long-read) and `size_hint` is not in the inner loop.
        let mut count: usize = 0;
        if let ExpandingState::PerBase { remaining, .. } = self.expanding {
            count = count.saturating_add(remaining as usize);
        }
        for op in self.ops {
            let len = op.len();
            if len == 0 {
                continue;
            }
            match op.op_type() {
                CigarOpType::Match | CigarOpType::SeqMatch | CigarOpType::SeqMismatch => {
                    count = count.saturating_add(len as usize);
                }
                CigarOpType::Insertion | CigarOpType::Deletion | CigarOpType::RefSkip => {
                    count = count.saturating_add(1);
                }
                CigarOpType::SoftClip => {
                    if self.options.soft_clips {
                        count = count.saturating_add(1);
                    }
                }
                CigarOpType::HardClip => {}
                CigarOpType::Padding | CigarOpType::Unknown(_) => {
                    if self.options.padding_and_unknown {
                        count = count.saturating_add(1);
                    }
                }
            }
        }
        (count, Some(count))
    }

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            // ── Expand multi-base ops (M/=/X) ──
            match std::mem::replace(&mut self.expanding, ExpandingState::None) {
                ExpandingState::PerBase { remaining, kind } if remaining > 0 => {
                    self.expanding =
                        ExpandingState::PerBase { remaining: remaining.saturating_sub(1), kind };
                    let qpos = self.qpos;
                    let rpos = self.rpos;
                    self.qpos = self.qpos.saturating_add(1);
                    self.rpos = advance_rpos(self.rpos, 1);
                    return Some(AlignedPair::Match { qpos, rpos, kind });
                }
                ExpandingState::PerBase { .. } => {
                    // Remaining was 0 — already replaced with None, loop to next op.
                    continue;
                }
                ExpandingState::None => {}
            }

            // ── Next CIGAR op ──
            let (op, rest) = self.ops.split_first()?;
            self.ops = rest;

            let len = op.len();
            let op_type = op.op_type();
            // r[impl cigar.aligned_pairs.zero_length_ops]
            // Zero-length ops are degenerate — htslib's CIGAR walker skips them
            // (its for-loops simply don't iterate). We mirror that for every op
            // kind so callers never see a `len: 0` summary.
            // HardClip/Padding/Unknown still need to be considered for advancing
            // qpos/rpos but those don't move when len == 0 anyway.
            if len == 0 && !matches!(op_type, CigarOpType::HardClip) {
                continue;
            }
            match op_type {
                CigarOpType::Match => {
                    self.expanding =
                        ExpandingState::PerBase { remaining: len, kind: MatchKind::Match };
                    continue;
                }
                CigarOpType::SeqMatch => {
                    self.expanding =
                        ExpandingState::PerBase { remaining: len, kind: MatchKind::SeqMatch };
                    continue;
                }
                CigarOpType::SeqMismatch => {
                    self.expanding =
                        ExpandingState::PerBase { remaining: len, kind: MatchKind::SeqMismatch };
                    continue;
                }

                // r[impl cigar.aligned_pairs.insertion_qpos]
                CigarOpType::Insertion => {
                    let qpos = self.qpos;
                    self.qpos = self.qpos.saturating_add(len);
                    return Some(AlignedPair::Insertion { qpos, insert_len: len });
                }

                // r[impl cigar.aligned_pairs.deletion_rpos]
                CigarOpType::Deletion => {
                    let rpos = self.rpos;
                    self.rpos = advance_rpos(self.rpos, len);
                    return Some(AlignedPair::Deletion { rpos, del_len: len });
                }

                CigarOpType::RefSkip => {
                    let rpos = self.rpos;
                    self.rpos = advance_rpos(self.rpos, len);
                    return Some(AlignedPair::RefSkip { rpos, skip_len: len });
                }

                CigarOpType::SoftClip => {
                    if self.options.soft_clips {
                        let qpos = self.qpos;
                        self.qpos = self.qpos.saturating_add(len);
                        return Some(AlignedPair::SoftClip { qpos, len });
                    }
                    // r[impl cigar.aligned_pairs.qpos_semantics]
                    // Even when hidden, soft clips still advance qpos.
                    self.qpos = self.qpos.saturating_add(len);
                }

                // r[impl cigar.aligned_pairs.hard_clips]
                CigarOpType::HardClip => {
                    // Hard clips are never yielded and don't advance anything.
                }

                CigarOpType::Padding => {
                    if self.options.padding_and_unknown {
                        return Some(AlignedPair::Padding { len });
                    }
                }

                CigarOpType::Unknown(code) => {
                    if self.options.padding_and_unknown {
                        return Some(AlignedPair::Unknown { code, len });
                    }
                }
            }
        }
    }
}

// `size_hint` returns `(n, Some(n))` so the iterator is exact-sized.
impl ExactSizeIterator for AlignedPairs<'_> {}

// `next()` never returns Some after returning None — the implementation drains
// `ops` and `expanding` strictly forward.
impl std::iter::FusedIterator for AlignedPairs<'_> {}

// ── MatchesOnly iterator ───────────────────────────────────────────────────

// r[impl cigar.aligned_pairs.matches_only.bare]
/// Iterator over [`MatchPosition`] — produced by
/// [`AlignedPairs::matches_only`]. Walks the underlying `AlignedPairs` and
/// yields only `Match` events as flat structs.
#[derive(Debug, Clone)]
pub struct MatchesOnly<'a> {
    inner: AlignedPairs<'a>,
}

impl Iterator for MatchesOnly<'_> {
    type Item = MatchPosition;

    fn size_hint(&self) -> (usize, Option<usize>) {
        // We can't predict how many of the remaining events are Match without
        // re-walking the CIGAR, so report a filter-style hint: lower bound 0,
        // upper bound = inner's upper bound.
        let (_, upper) = self.inner.size_hint();
        (0, upper)
    }

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match self.inner.next()? {
                AlignedPair::Match { qpos, rpos, kind } => {
                    return Some(MatchPosition { qpos, rpos, kind });
                }
                _ => continue,
            }
        }
    }
}

impl std::iter::FusedIterator for MatchesOnly<'_> {}

/// Advance a `Pos0` by `n` positions, saturating at `i32::MAX`.
/// Used internally by the iterator; overflow only happens on degenerate BAM
/// (positions would already exceed BAM's i32 range) and saturation is the
/// safe fallback.
#[inline]
fn advance_rpos(rpos: Pos0, n: u32) -> Pos0 {
    let val = rpos.as_u64().saturating_add(u64::from(n));
    // val.min(i32::MAX as u64) is ≤ i32::MAX, so the cast cannot truncate.
    let clamped = u32::try_from(val.min(i32::MAX as u64)).unwrap_or(i32::MAX as u32);
    // clamped ≤ i32::MAX, so Pos0::new can't fail
    Pos0::new(clamped).unwrap_or(rpos)
}

// ── SlimRecord integration ────────────────────────────────────────────────

// r[impl cigar.aligned_pairs.slim_record]
impl SlimRecord {
    /// Walk this record's CIGAR, yielding typed [`AlignedPair`]s.
    ///
    /// Reads the CIGAR slice from the store at construction time.
    /// Once the slice is obtained, iteration is infallible.
    ///
    /// Default mode yields `Match`, `Insertion`, `Deletion`, `RefSkip`.
    /// Chain `.with_soft_clips()` or `.full()` on the result to widen.
    ///
    /// # Example
    /// ```ignore
    /// for pair in slim_record.aligned_pairs(&store)? {
    ///     if let AlignedPair::Match { qpos, rpos, kind } = pair {
    ///         // ...
    ///     }
    /// }
    /// ```
    pub fn aligned_pairs<'store, U>(
        &self,
        store: &'store RecordStore<U>,
    ) -> Result<AlignedPairs<'store>, RecordAccessError> {
        Ok(AlignedPairs::new(self.pos, self.cigar(store)?))
    }

    // r[impl cigar.aligned_pairs.with_read.slim_record]
    /// Walk this record's CIGAR with read seq/qual attached. One-shot helper:
    /// equivalent to `self.aligned_pairs(store)?.with_read(self.seq(store)?, self.qual(store)?)`
    /// but only borrows `store` once.
    ///
    /// Chain `.with_reference(&ref_seq)` to add reference-base lookup.
    ///
    /// # Example
    /// ```ignore
    /// for ev in slim.aligned_pairs_with_read(&store)? {
    ///     if let AlignedPairWithRead::Match { qpos, query, qual, .. } = ev {
    ///         // ...
    ///     }
    /// }
    /// ```
    pub fn aligned_pairs_with_read<'store, U>(
        &self,
        store: &'store RecordStore<U>,
    ) -> Result<super::aligned_pairs_view::AlignedPairsWithRead<'store, 'store>, AlignedPairsError>
    {
        let cigar = self.cigar(store)?;
        let seq = self.seq(store)?;
        let qual = self.qual(store)?;
        // Records pushed via `push_raw` always have cigar.qlen == seq.len() ==
        // qual.len(), so this validation should always succeed for store-resident
        // records — but the typed error makes the "should" provable.
        AlignedPairs::new(self.pos, cigar).with_read(seq, qual)
    }
}

// ── OwnedBamRecord integration ────────────────────────────────────────────

// r[impl cigar.aligned_pairs.owned_record]
impl super::owned_record::OwnedBamRecord {
    /// Walk this record's CIGAR, yielding typed [`AlignedPair`]s.
    ///
    /// Returns [`AlignedPairsError::UnmappedWithCigar`] if `pos = None` but
    /// the CIGAR is non-empty — walking that CIGAR without a base reference
    /// position would produce nonsense `rpos` values. For mapped records
    /// (`pos = Some(_)`) and fully-unmapped records (`pos = None` + empty
    /// CIGAR), iteration over the returned `AlignedPairs` is infallible.
    ///
    /// # Example
    /// ```ignore
    /// for pair in record.aligned_pairs()? {
    ///     // ...
    /// }
    /// ```
    pub fn aligned_pairs(&self) -> Result<AlignedPairs<'_>, AlignedPairsError> {
        match self.pos {
            Some(p) => Ok(AlignedPairs::new(p, &self.cigar)),
            None if self.cigar.is_empty() => Ok(AlignedPairs::new(Pos0::ZERO, &self.cigar)),
            None => Err(AlignedPairsError::UnmappedWithCigar { cigar_ops: self.cigar.len() }),
        }
    }

    // r[impl cigar.aligned_pairs.with_read.owned_record]
    /// One-shot walk with read seq/qual attached — symmetric with
    /// [`SlimRecord::aligned_pairs_with_read`](super::record_store::SlimRecord::aligned_pairs_with_read).
    ///
    /// Equivalent to `self.aligned_pairs()?.with_read(&self.seq, &self.qual)`,
    /// but bundled to avoid the verbose three-line chain at every call site.
    /// The same validation applies: cigar query length must match seq length;
    /// qual must be empty (BAM missing-qual sentinel) or match seq length.
    ///
    /// Chain `.with_reference(&ref_seq)` to add reference base lookups.
    ///
    /// # Example
    /// ```ignore
    /// for ev in record.aligned_pairs_with_read()? {
    ///     if let AlignedPairWithRead::Match { qpos, query, qual, .. } = ev {
    ///         // ...
    ///     }
    /// }
    /// ```
    pub fn aligned_pairs_with_read(
        &self,
    ) -> Result<super::aligned_pairs_view::AlignedPairsWithRead<'_, '_>, AlignedPairsError> {
        let pairs = self.aligned_pairs()?;
        pairs.with_read(&self.seq, &self.qual)
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────

#[cfg(test)]
#[allow(clippy::arithmetic_side_effects, reason = "test arithmetic on known small values")]
mod tests {
    use super::super::cigar::CigarOp as Op;
    use super::*;

    // Helper: construct a CigarOp
    fn m(len: u32) -> Op {
        Op::new(CigarOpType::Match, len)
    }
    fn ins(len: u32) -> Op {
        Op::new(CigarOpType::Insertion, len)
    }
    fn del(len: u32) -> Op {
        Op::new(CigarOpType::Deletion, len)
    }
    fn skip(len: u32) -> Op {
        Op::new(CigarOpType::RefSkip, len)
    }
    fn soft(len: u32) -> Op {
        Op::new(CigarOpType::SoftClip, len)
    }
    fn hard(len: u32) -> Op {
        Op::new(CigarOpType::HardClip, len)
    }
    fn pad(len: u32) -> Op {
        Op::new(CigarOpType::Padding, len)
    }
    fn unk(code: u8, len: u32) -> Op {
        Op::new(CigarOpType::Unknown(code), len)
    }

    fn p0(v: u32) -> Pos0 {
        Pos0::new(v).unwrap()
    }

    fn match_m(qpos: u32, rpos: Pos0) -> AlignedPair {
        AlignedPair::Match { qpos, rpos, kind: MatchKind::Match }
    }

    fn match_eq(qpos: u32, rpos: Pos0) -> AlignedPair {
        AlignedPair::Match { qpos, rpos, kind: MatchKind::SeqMatch }
    }

    fn match_x(qpos: u32, rpos: Pos0) -> AlignedPair {
        AlignedPair::Match { qpos, rpos, kind: MatchKind::SeqMismatch }
    }

    fn seq_match(len: u32) -> Op {
        Op::new(CigarOpType::SeqMatch, len)
    }

    fn seq_mismatch(len: u32) -> Op {
        Op::new(CigarOpType::SeqMismatch, len)
    }

    // ── Basic unit tests ──────────────────────────────────────────────────

    // r[verify cigar.aligned_pairs.default_mode]
    #[test]
    fn simple_match() {
        let cigar = [m(5)];
        let pairs: Vec<_> = AlignedPairs::new(p0(100), &cigar).collect();
        assert_eq!(pairs.len(), 5);
        assert_eq!(pairs[0], match_m(0, p0(100)));
        assert_eq!(pairs[4], match_m(4, p0(104)));
    }

    // r[verify cigar.aligned_pairs.match_kind]
    #[test]
    fn match_kind_is_preserved_per_op() {
        // 2M + 2= + 2X — each op type yields its own MatchKind
        let cigar = [m(2), seq_match(2), seq_mismatch(2)];
        let pairs: Vec<_> = AlignedPairs::new(p0(0), &cigar).collect();
        assert_eq!(pairs.len(), 6);
        assert_eq!(pairs[0], match_m(0, p0(0)));
        assert_eq!(pairs[1], match_m(1, p0(1)));
        assert_eq!(pairs[2], match_eq(2, p0(2)));
        assert_eq!(pairs[3], match_eq(3, p0(3)));
        assert_eq!(pairs[4], match_x(4, p0(4)));
        assert_eq!(pairs[5], match_x(5, p0(5)));
    }

    // r[verify cigar.aligned_pairs.match_kind]
    #[test]
    fn match_kind_does_not_change_qpos_rpos() {
        // Walk a single CIGAR mixing all three kinds. The (qpos, rpos)
        // sequence under kind variation must equal the same sequence with all
        // ops collapsed to plain `M`. If the iterator's position cursor ever
        // drifted based on `kind`, this would fire.
        //
        // Earlier version of this test compared three separate CIGARs (5M,
        // 5=, 5X) and would pass even if MatchKind handling were completely
        // broken — included this as a regression note.
        let mixed = [m(2), seq_match(3), seq_mismatch(2), m(1)];
        let collapsed = [m(8)];

        let strip_kind = |pairs: Vec<AlignedPair>| -> Vec<(u32, u32)> {
            pairs
                .iter()
                .filter_map(|p| match p {
                    AlignedPair::Match { qpos, rpos, .. } => Some((*qpos, **rpos)),
                    _ => None,
                })
                .collect()
        };
        let mixed_positions = strip_kind(AlignedPairs::new(p0(50), &mixed).collect());
        let collapsed_positions = strip_kind(AlignedPairs::new(p0(50), &collapsed).collect());
        assert_eq!(mixed_positions, collapsed_positions, "kind must not affect qpos/rpos");
        // Sanity check: the mixed walk really did expose all three kinds.
        let kinds: Vec<MatchKind> = AlignedPairs::new(p0(50), &mixed)
            .filter_map(|p| match p {
                AlignedPair::Match { kind, .. } => Some(kind),
                _ => None,
            })
            .collect();
        assert!(kinds.contains(&MatchKind::Match), "mixed walk must have M");
        assert!(kinds.contains(&MatchKind::SeqMatch), "mixed walk must have =");
        assert!(kinds.contains(&MatchKind::SeqMismatch), "mixed walk must have X");
    }

    // r[verify cigar.aligned_pairs.insertion_qpos]
    #[test]
    fn with_insertion() {
        let cigar = [m(2), ins(1), m(2)];
        let pairs: Vec<_> = AlignedPairs::new(p0(100), &cigar).collect();
        assert_eq!(pairs.len(), 5, "2M + 1I(summary) + 2M = 5 items");
        assert_eq!(pairs[0], match_m(0, p0(100)));
        assert_eq!(pairs[1], match_m(1, p0(101)));
        // Insertion summary: qpos = 2 (first inserted base), len = 1
        assert_eq!(pairs[2], AlignedPair::Insertion { qpos: 2, insert_len: 1 });
        assert_eq!(pairs[3], match_m(3, p0(102)));
        assert_eq!(pairs[4], match_m(4, p0(103)));
    }

    // r[verify cigar.aligned_pairs.deletion_rpos]
    #[test]
    fn with_deletion() {
        let cigar = [m(2), del(3), m(2)];
        let pairs: Vec<_> = AlignedPairs::new(p0(100), &cigar).collect();
        assert_eq!(pairs.len(), 5, "2M + 1D(summary) + 2M = 5 items");
        assert_eq!(pairs[0], match_m(0, p0(100)));
        assert_eq!(pairs[1], match_m(1, p0(101)));
        // Deletion summary: rpos = 102 (start of deletion), del_len = 3
        assert_eq!(pairs[2], AlignedPair::Deletion { rpos: p0(102), del_len: 3 });
        assert_eq!(pairs[3], match_m(2, p0(105)));
        assert_eq!(pairs[4], match_m(3, p0(106)));
    }

    #[test]
    fn with_refskip() {
        let cigar = [m(2), skip(5), m(3)];
        let pairs: Vec<_> = AlignedPairs::new(p0(100), &cigar).collect();
        assert_eq!(pairs.len(), 6, "2M + 1N(summary) + 3M = 6 items");
        assert_eq!(pairs[2], AlignedPair::RefSkip { rpos: p0(102), skip_len: 5 });
        assert_eq!(pairs[3], match_m(2, p0(107)));
    }

    // r[verify cigar.aligned_pairs.qpos_semantics]
    #[test]
    fn qpos_includes_soft_clips() {
        // 5S + 3M: first match should have qpos = 5
        let cigar = [soft(5), m(3)];
        let pairs: Vec<_> = AlignedPairs::new(p0(0), &cigar).collect();
        assert_eq!(pairs.len(), 3);
        assert_eq!(pairs[0], match_m(5, p0(0)));
        assert_eq!(pairs[2], match_m(7, p0(2)));
    }

    // r[verify cigar.aligned_pairs.hard_clips]
    #[test]
    fn hard_clips_ignored() {
        let cigar = [hard(3), m(2), hard(1)];
        let pairs: Vec<_> = AlignedPairs::new(p0(0), &cigar).collect();
        assert_eq!(pairs.len(), 2);
        // qpos starts at 0 — hard clips don't advance it
        assert_eq!(pairs[0], match_m(0, p0(0)));
        assert_eq!(pairs[1], match_m(1, p0(1)));
    }

    // r[verify cigar.aligned_pairs.default_mode]
    #[test]
    fn soft_clips_hidden_by_default() {
        let cigar = [soft(3), m(2)];
        let pairs: Vec<_> = AlignedPairs::new(p0(0), &cigar).collect();
        // Only Match variants, no SoftClip
        assert_eq!(pairs.len(), 2);
        assert!(pairs.iter().all(|p| matches!(p, AlignedPair::Match { .. })));
    }

    // r[verify cigar.aligned_pairs.options]
    #[test]
    fn with_soft_clips_enables_them() {
        let cigar = [soft(3), m(2)];
        let pairs: Vec<_> = AlignedPairs::new(p0(0), &cigar).with_soft_clips().collect();
        assert_eq!(pairs.len(), 3, "SoftClip(summary) + 2M");
        assert_eq!(pairs[0], AlignedPair::SoftClip { qpos: 0, len: 3 });
        assert_eq!(pairs[1], match_m(3, p0(0)));
    }

    // r[verify cigar.aligned_pairs.options]
    #[test]
    fn full_yields_everything() {
        let cigar = [soft(1), m(1), pad(2), ins(1), unk(9, 2)];
        let pairs: Vec<_> = AlignedPairs::new(p0(0), &cigar).full().collect();
        // 5 ops: SoftClip + Match + Padding + Insertion + Unknown
        assert_eq!(pairs.len(), 5);
        assert!(matches!(pairs[0], AlignedPair::SoftClip { .. }));
        assert!(matches!(pairs[1], AlignedPair::Match { .. }));
        assert_eq!(pairs[2], AlignedPair::Padding { len: 2 });
        assert!(matches!(pairs[3], AlignedPair::Insertion { .. }));
        assert!(matches!(pairs[4], AlignedPair::Unknown { code: 9, len: 2 }));
    }

    #[test]
    fn full_yields_padding_and_unknown() {
        // Simpler: just pad and unknown
        let cigar = [m(1), pad(3), unk(13, 4), m(1)];
        let pairs: Vec<_> = AlignedPairs::new(p0(0), &cigar).full().collect();
        assert_eq!(pairs.len(), 4);
        assert!(matches!(pairs[0], AlignedPair::Match { .. }));
        assert_eq!(pairs[1], AlignedPair::Padding { len: 3 });
        assert!(matches!(pairs[2], AlignedPair::Unknown { code: 13, len: 4 }));
        assert!(matches!(pairs[3], AlignedPair::Match { .. }));
    }

    #[test]
    fn default_skips_padding_and_unknown() {
        let cigar = [m(1), pad(1), unk(13, 4), m(1)];
        let pairs: Vec<_> = AlignedPairs::new(p0(0), &cigar).collect();
        assert_eq!(pairs.len(), 2);
        assert!(matches!(pairs[0], AlignedPair::Match { .. }));
        assert!(matches!(pairs[1], AlignedPair::Match { .. }));
    }

    // r[verify cigar.aligned_pairs.default_mode]
    #[test]
    fn empty_cigar() {
        let pairs: Vec<_> = AlignedPairs::new(p0(0), &[]).collect();
        assert!(pairs.is_empty());
    }

    // r[verify cigar.aligned_pairs.zero_length_ops]
    #[test]
    fn zero_length_match_skipped() {
        let cigar = [m(0), m(2)];
        let pairs: Vec<_> = AlignedPairs::new(p0(0), &cigar).collect();
        assert_eq!(pairs.len(), 2);
        assert_eq!(pairs[0], match_m(0, p0(0)));
    }

    // r[verify cigar.aligned_pairs.zero_length_ops]
    #[test]
    fn zero_length_indel_skipped() {
        // Zero-length I/D/N/S must not yield summary variants with len=0
        let cigar = [m(1), ins(0), del(0), skip(0), Op::new(CigarOpType::SoftClip, 0), m(1)];
        let pairs: Vec<_> = AlignedPairs::new(p0(0), &cigar).with_soft_clips().collect();
        assert_eq!(pairs.len(), 2, "only the two Match positions remain");
        assert_eq!(pairs[0], match_m(0, p0(0)));
        assert_eq!(pairs[1], match_m(1, p0(1)));
    }

    // r[verify cigar.aligned_pairs.zero_length_ops]
    #[test]
    fn zero_length_padding_and_unknown_skipped() {
        let cigar = [m(1), pad(0), unk(9, 0), m(1)];
        let pairs: Vec<_> = AlignedPairs::new(p0(0), &cigar).full().collect();
        assert_eq!(pairs.len(), 2);
        assert!(matches!(pairs[0], AlignedPair::Match { .. }));
        assert!(matches!(pairs[1], AlignedPair::Match { .. }));
    }

    // ── matches_only adapter ──────────────────────────────────────────────

    // r[verify cigar.aligned_pairs.matches_only.bare]
    #[test]
    fn matches_only_drops_indels_and_keeps_match_kind() {
        // 2M + 3I + 2= + 1D + 2X = 2 + 2 + 2 = 6 Match positions
        // (3I and 1D are dropped — they aren't Match events.)
        let cigar = [m(2), ins(3), seq_match(2), del(1), seq_mismatch(2)];
        let matches: Vec<_> = AlignedPairs::new(p0(100), &cigar).matches_only().collect();
        assert_eq!(matches.len(), 6);
        // Spot-check kind preservation across the M/=/X mix.
        assert_eq!(matches[0].kind, MatchKind::Match);
        assert_eq!(matches[1].kind, MatchKind::Match);
        assert_eq!(matches[2].kind, MatchKind::SeqMatch);
        assert_eq!(matches[3].kind, MatchKind::SeqMatch);
        assert_eq!(matches[4].kind, MatchKind::SeqMismatch);
        assert_eq!(matches[5].kind, MatchKind::SeqMismatch);
        // Position monotonicity
        for window in matches.windows(2) {
            assert!(window[0].qpos <= window[1].qpos);
            assert!(*window[0].rpos <= *window[1].rpos);
        }
    }

    // r[verify cigar.aligned_pairs.matches_only.bare]
    #[test]
    fn matches_only_count_equals_filtered_match_events() {
        let cigar = [soft(2), m(5), ins(3), m(4), del(2), m(3)];
        let bare_match_count = AlignedPairs::new(p0(0), &cigar)
            .filter(|p| matches!(p, AlignedPair::Match { .. }))
            .count();
        let matches_only_count = AlignedPairs::new(p0(0), &cigar).matches_only().count();
        assert_eq!(bare_match_count, matches_only_count);
        assert_eq!(matches_only_count, 12);
    }

    // ── size_hint / ExactSizeIterator ────────────────────────────────────

    #[test]
    fn size_hint_exact_for_match_only_cigar() {
        let cigar = [m(5)];
        let it = AlignedPairs::new(p0(0), &cigar);
        assert_eq!(it.size_hint(), (5, Some(5)));
        assert_eq!(it.len(), 5);
    }

    #[test]
    fn size_hint_exact_with_indels_and_clips() {
        // Default mode: 2 SoftClip hidden + 5M + 1I (summary) + 4M + 1D + 3M
        // = 5 + 1 + 4 + 1 + 3 = 14 events
        let cigar = [soft(2), m(5), ins(3), m(4), del(2), m(3)];
        let it = AlignedPairs::new(p0(0), &cigar);
        assert_eq!(it.size_hint(), (14, Some(14)));
    }

    #[test]
    fn size_hint_includes_soft_clips_when_enabled() {
        // 2S + 5M = 5 in default mode, 6 with soft clips
        let cigar = [soft(2), m(5)];
        assert_eq!(AlignedPairs::new(p0(0), &cigar).len(), 5);
        assert_eq!(AlignedPairs::new(p0(0), &cigar).with_soft_clips().len(), 6);
    }

    #[test]
    fn size_hint_skips_zero_length_ops() {
        // 0M (skipped) + 3M + 0I (skipped) + 2M = 5 events
        let cigar = [m(0), m(3), ins(0), m(2)];
        assert_eq!(AlignedPairs::new(p0(0), &cigar).len(), 5);
    }

    #[test]
    fn size_hint_decrements_with_iteration() {
        // After consuming N events, len() should return (total - N).
        let cigar = [m(5), del(1), m(3)];
        let mut it = AlignedPairs::new(p0(0), &cigar);
        assert_eq!(it.len(), 9); // 5M + 1D(summary) + 3M
        let _ = it.next();
        assert_eq!(it.len(), 8);
        let _ = it.next();
        assert_eq!(it.len(), 7);
        // Drain to end
        while it.next().is_some() {}
        assert_eq!(it.len(), 0);
    }

    #[test]
    fn collect_pre_allocates_with_size_hint() {
        // Verify size_hint is honored: the collected Vec's capacity is at
        // least the iterator's len(). std::vec::Vec uses the lower bound of
        // size_hint for `with_capacity` in `collect()`.
        let cigar = [m(100)];
        let collected: Vec<_> = AlignedPairs::new(p0(0), &cigar).collect();
        assert_eq!(collected.len(), 100);
        assert!(collected.capacity() >= 100);
    }

    // ── Clone ─────────────────────────────────────────────────────────────

    #[test]
    fn clone_lets_caller_walk_twice() {
        let cigar = [m(3), ins(1), m(2)];
        let it = AlignedPairs::new(p0(50), &cigar);
        let it_clone = it.clone();
        let first: Vec<_> = it.collect();
        let second: Vec<_> = it_clone.collect();
        assert_eq!(first, second);
    }

    // ── D-I adjacency ─────────────────────────────────────────────────────

    // r[verify cigar.aligned_pairs.iterator]
    #[test]
    fn deletion_followed_by_insertion_yields_two_events() {
        // D-I: should yield Deletion then Insertion (two separate events)
        // Unlike the pileup engine's ComplexIndel which collapses them
        let cigar = [del(2), ins(3)];
        let pairs: Vec<_> = AlignedPairs::new(p0(100), &cigar).collect();
        assert_eq!(pairs.len(), 2);
        assert_eq!(pairs[0], AlignedPair::Deletion { rpos: p0(100), del_len: 2 });
        assert_eq!(pairs[1], AlignedPair::Insertion { qpos: 0, insert_len: 3 });
    }

    // ── Full CIGAR walk ───────────────────────────────────────────────────

    #[test]
    fn complex_cigar_walk() {
        // 2S + 3M + 1I + 2M + 1D + 1N + 2M
        let cigar = [soft(2), m(3), ins(1), m(2), del(1), skip(1), m(2)];
        let pairs: Vec<_> = AlignedPairs::new(p0(50), &cigar).collect();

        // Expected: 3M + I(summary) + 2M + D(summary) + N(summary) + 2M = 10 items
        let expected = vec![
            match_m(2, p0(50)), // after 2S
            match_m(3, p0(51)),
            match_m(4, p0(52)),
            AlignedPair::Insertion { qpos: 5, insert_len: 1 },
            match_m(6, p0(53)),
            match_m(7, p0(54)),
            AlignedPair::Deletion { rpos: p0(55), del_len: 1 },
            AlignedPair::RefSkip { rpos: p0(56), skip_len: 1 },
            match_m(8, p0(57)),
            match_m(9, p0(58)),
        ];
        assert_eq!(pairs, expected);
    }

    // ── Property: position monotonicity ───────────────────────────────────

    // r[verify cigar.aligned_pairs.position_monotonicity]
    #[test]
    fn qpos_is_monotone_nondecreasing() {
        // 2S3M1I2M2D1M
        let cigar = [soft(2), m(3), ins(1), m(2), del(2), m(1)];
        let pairs: Vec<_> = AlignedPairs::new(p0(0), &cigar).with_soft_clips().collect();

        // Just verify the qpos values in order
        let qposes: Vec<u32> = pairs
            .iter()
            .filter_map(|p| match p {
                AlignedPair::Match { qpos, .. } => Some(*qpos),
                AlignedPair::Insertion { qpos, .. } => Some(*qpos),
                AlignedPair::SoftClip { qpos, .. } => Some(*qpos),
                _ => None,
            })
            .collect();
        assert!(!qposes.is_empty());
        assert!(qposes.windows(2).all(|w| w[0] <= w[1]));
    }

    // r[verify cigar.aligned_pairs.position_monotonicity]
    #[test]
    fn rpos_is_monotone_nondecreasing() {
        let cigar = [m(3), del(2), skip(1), m(2)];
        let pairs: Vec<_> = AlignedPairs::new(p0(100), &cigar).collect();
        let rposes: Vec<u32> = pairs
            .iter()
            .filter_map(|p| match p {
                AlignedPair::Match { rpos, .. } => Some(**rpos),
                AlignedPair::Deletion { rpos, .. } => Some(**rpos),
                AlignedPair::RefSkip { rpos, .. } => Some(**rpos),
                _ => None,
            })
            .collect();
        assert!(!rposes.is_empty());
        assert!(rposes.windows(2).all(|w| w[0] <= w[1]));
    }

    // ── Property test oracle ──────────────────────────────────────────────

    /// Independent "oracle" implementation that walks the CIGAR the same way
    /// `AlignedPairs` does, but without the state-machine pattern.
    /// Used in property tests to verify equivalence.
    fn oracle_walk(
        cigar: &[CigarOp],
        rec_pos: Pos0,
        options: AlignedPairsOptions,
    ) -> Vec<AlignedPair> {
        let mut pairs = Vec::new();
        let mut qpos = 0u32;
        let mut rpos = rec_pos;

        for op in cigar {
            let len = op.len();
            // Skip zero-length ops uniformly (htslib behavior).
            if len == 0 && !matches!(op.op_type(), CigarOpType::HardClip) {
                continue;
            }
            let match_kind = match op.op_type() {
                CigarOpType::Match => Some(MatchKind::Match),
                CigarOpType::SeqMatch => Some(MatchKind::SeqMatch),
                CigarOpType::SeqMismatch => Some(MatchKind::SeqMismatch),
                _ => None,
            };
            match op.op_type() {
                CigarOpType::Match | CigarOpType::SeqMatch | CigarOpType::SeqMismatch => {
                    let kind = match_kind.expect("set above for M/=/X");
                    for i in 0..len {
                        pairs.push(AlignedPair::Match {
                            qpos: qpos.saturating_add(i),
                            rpos: advance_rpos(rpos, i),
                            kind,
                        });
                    }
                    qpos = qpos.saturating_add(len);
                    rpos = advance_rpos(rpos, len);
                }
                CigarOpType::Insertion => {
                    pairs.push(AlignedPair::Insertion { qpos, insert_len: len });
                    qpos = qpos.saturating_add(len);
                }
                CigarOpType::Deletion => {
                    pairs.push(AlignedPair::Deletion { rpos, del_len: len });
                    rpos = advance_rpos(rpos, len);
                }
                CigarOpType::RefSkip => {
                    pairs.push(AlignedPair::RefSkip { rpos, skip_len: len });
                    rpos = advance_rpos(rpos, len);
                }
                CigarOpType::SoftClip => {
                    if options.soft_clips {
                        pairs.push(AlignedPair::SoftClip { qpos, len });
                    }
                    qpos = qpos.saturating_add(len);
                }
                CigarOpType::HardClip => {
                    // never yielded, don't advance
                }
                CigarOpType::Padding => {
                    if options.padding_and_unknown {
                        pairs.push(AlignedPair::Padding { len });
                    }
                }
                CigarOpType::Unknown(code) => {
                    if options.padding_and_unknown {
                        pairs.push(AlignedPair::Unknown { code, len });
                    }
                }
            }
        }

        pairs
    }

    #[test]
    fn oracle_matches_iterator_default() {
        let cigars: &[&[CigarOp]] = &[
            &[m(5)],
            &[m(2), ins(1), m(2)],
            &[m(2), del(3), m(2)],
            &[soft(2), m(3)],
            &[m(2), skip(5), m(3)],
            &[del(2), ins(3)],
            &[hard(3), m(2)],
            &[m(1), pad(2), m(1)],
            &[],
            &[soft(1), m(1), ins(1), del(1), skip(1), m(1)],
            &[m(1), seq_match(2), seq_mismatch(1), m(1)],
        ];

        for cigar in cigars {
            let actual: Vec<_> = AlignedPairs::new(p0(100), cigar).collect();
            let expected = oracle_walk(cigar, p0(100), AlignedPairsOptions::default());
            assert_eq!(actual, expected, "mismatch for CIGAR: {cigar:?}");
        }
    }

    #[test]
    fn oracle_matches_iterator_full() {
        let cigar = &[soft(1), m(1), pad(2), ins(1), del(1), unk(9, 2), m(1)];
        let actual: Vec<_> = AlignedPairs::new(p0(0), cigar).full().collect();
        let opts = AlignedPairsOptions { soft_clips: true, padding_and_unknown: true };
        let expected = oracle_walk(cigar, p0(0), opts);
        assert_eq!(actual, expected);
    }

    // ── Proptest: random CIGAR walk matches oracle ────────────────────────

    mod proptests {
        use super::*;
        use proptest::prelude::*;

        fn arb_cigar_op() -> impl Strategy<Value = CigarOp> {
            // Generate valid CIGAR ops within reasonable bounds.
            // Includes len=0 to exercise the zero-length-skip behavior.
            (0u8..=14u8, 0u32..=50u32).prop_map(|(code, len)| {
                // Map codes 9..=14 to Unknown variant (reserved codes)
                let op_type = CigarOpType::from_bam(code);
                CigarOp::new(op_type, len)
            })
        }

        fn arb_cigar() -> impl Strategy<Value = Vec<CigarOp>> {
            proptest::collection::vec(arb_cigar_op(), 0..20)
        }

        fn arb_pos0() -> impl Strategy<Value = Pos0> {
            (0u32..=100_000u32).prop_map(|v| Pos0::new(v).unwrap())
        }

        // r[verify cigar.aligned_pairs.default_mode]
        proptest! {
            #[test]
            fn matches_oracle_default(
                cigar in arb_cigar(),
                pos in arb_pos0(),
            ) {
                let actual: Vec<_> = AlignedPairs::new(pos, &cigar).collect();
                let expected = oracle_walk(&cigar, pos, AlignedPairsOptions::default());
                prop_assert_eq!(actual, expected);
            }
        }

        proptest! {
            #[test]
            fn matches_oracle_full(
                cigar in arb_cigar(),
                pos in arb_pos0(),
            ) {
                let actual: Vec<_> = AlignedPairs::new(pos, &cigar).full().collect();
                let opts = AlignedPairsOptions {
                    soft_clips: true,
                    padding_and_unknown: true,
                };
                let expected = oracle_walk(&cigar, pos, opts);
                prop_assert_eq!(actual, expected);
            }
        }

        // r[verify cigar.aligned_pairs.position_monotonicity]
        proptest! {
            #[test]
            fn ref_pos_monotone_nondecreasing(
                cigar in arb_cigar(),
            ) {
                let pairs: Vec<_> = AlignedPairs::new(Pos0::ZERO, &cigar).collect();
                let rposes: Vec<u32> = pairs.iter().filter_map(|p| match p {
                    AlignedPair::Match { rpos, .. } => Some(**rpos),
                    AlignedPair::Deletion { rpos, .. } => Some(**rpos),
                    AlignedPair::RefSkip { rpos, .. } => Some(**rpos),
                    _ => None,
                }).collect();
                prop_assert!(rposes.windows(2).all(|w| w[0] <= w[1]));
            }
        }

        proptest! {
            #[test]
            fn qpos_monotone_nondecreasing(
                cigar in arb_cigar(),
            ) {
                let pairs: Vec<_> = AlignedPairs::new(Pos0::ZERO, &cigar).full().collect();
                let qposes: Vec<u32> = pairs.iter().filter_map(|p| match p {
                    AlignedPair::Match { qpos, .. } => Some(*qpos),
                    AlignedPair::Insertion { qpos, .. } => Some(*qpos),
                    AlignedPair::SoftClip { qpos, .. } => Some(*qpos),
                    _ => None,
                }).collect();
                prop_assert!(qposes.windows(2).all(|w| w[0] <= w[1]));
            }
        }
    }

    // ── htslib comparison tests ──────────────────────────────────────────

    // r[verify cigar.aligned_pairs.htslib_equivalence]
    #[cfg(test)]
    mod htslib_tests {
        use super::*;

        /// Expand the actual `AlignedPairs` iterator into per-base
        /// `(Option<qpos>, Option<rpos>)` tuples — the shape rust-htslib's
        /// `aligned_pairs_full()` yields. Closes the loop: this test exercises
        /// the real iterator instead of comparing two seqair-internal oracles.
        ///
        /// Soft clips are enabled via `.with_soft_clips()` to match htslib;
        /// padding is intentionally excluded because rust-htslib's
        /// `aligned_pairs_full` panics on `Cigar::Pad`.
        fn expand_iterator(cigar: &[CigarOp], rec_pos: Pos0) -> Vec<(Option<u32>, Option<u32>)> {
            let mut result = Vec::new();
            for pair in AlignedPairs::new(rec_pos, cigar).with_soft_clips() {
                match pair {
                    AlignedPair::Match { qpos, rpos, .. } => {
                        result.push((Some(qpos), Some(*rpos)));
                    }
                    AlignedPair::Insertion { qpos, insert_len } => {
                        for i in 0..insert_len {
                            result.push((Some(qpos.saturating_add(i)), None));
                        }
                    }
                    AlignedPair::Deletion { rpos, del_len } => {
                        for i in 0..del_len {
                            result.push((None, Some(*advance_rpos(rpos, i))));
                        }
                    }
                    AlignedPair::RefSkip { rpos, skip_len } => {
                        for i in 0..skip_len {
                            result.push((None, Some(*advance_rpos(rpos, i))));
                        }
                    }
                    AlignedPair::SoftClip { qpos, len } => {
                        for i in 0..len {
                            result.push((Some(qpos.saturating_add(i)), None));
                        }
                    }
                    AlignedPair::Padding { .. } | AlignedPair::Unknown { .. } => {
                        // Default mode hides these; with_soft_clips alone
                        // doesn't enable them — included here for completeness.
                    }
                }
            }
            result
        }

        /// Drive `rust_htslib::bam::ext::BamRecordExtensions::aligned_pairs_full()`
        /// over the same CIGAR + pos and return its yields in the same shape
        /// `expand_iterator` produces.
        fn htslib_pairs(cigar_str: &str, pos: i64) -> Vec<(Option<u32>, Option<u32>)> {
            use rust_htslib::bam::ext::BamRecordExtensions;
            use rust_htslib::bam::record::Record;

            let cigar_string = build_htslib_cigar(cigar_str);
            let mut rec = Record::new();
            rec.set_pos(pos);
            rec.set_cigar(Some(&cigar_string));

            #[expect(
                clippy::cast_sign_loss,
                clippy::cast_possible_truncation,
                reason = "test fixtures: positions are non-negative and ≤ i32::MAX"
            )]
            let pairs = rec
                .aligned_pairs_full()
                .map(|arr| (arr[0].map(|v| v as u32), arr[1].map(|v| v as u32)))
                .collect();
            pairs
        }

        // r[verify cigar.aligned_pairs.htslib_equivalence]
        #[test]
        fn matches_htslib_aligned_pairs_full() {
            // (CIGAR string, pos). Cigar::Pad excluded — rust-htslib panics.
            // = and X are exercised here too — htslib collapses them into the
            // same (Some, Some) shape we produce.
            //
            // Hard-clip cases (`H`) explicitly verify htslib's "exclude
            // entirely, do not advance qpos" semantics — covered by spec
            // rule cigar.aligned_pairs.hard_clips.
            //
            // Adjacent indel cases (D-I, I-D, D-N, N-D) verify that the
            // summary form's separation of events matches htslib's expanded
            // form when both are flattened.
            let test_cases: &[(&str, i64)] = &[
                // ── Single-op CIGARs ──
                ("5M", 100),
                ("3=", 100),
                ("3X", 100),
                // ── Match with one indel ──
                ("2M1I2M", 100),
                ("2M3D2M", 100),
                ("3M2N4M", 100),
                // ── Soft clips ──
                ("5S3M", 0),
                ("3S5M2S", 0),
                ("3M5S", 0),
                // ── Hard clips: must NOT advance qpos and MUST be excluded ──
                ("3H5M", 100),
                ("5M2H", 100),
                ("3H5M2H", 100),
                ("3H2S5M", 100),
                // ── Hard + soft + match combinations ──
                ("2H3S5M2S1H", 100),
                // ── Adjacent indels ──
                ("2M1D1I2M", 100),
                ("2M1I2D3M", 100),
                ("3M1I1D2M", 100),
                ("2M1D2N1M", 100),
                // ── = and X interleaved ──
                ("3=2X1=", 50),
                ("2S3=1X2=2S", 0),
                ("1=1X1=1X1M", 50),
                // ── Long single ops to stress saturating arithmetic ──
                ("100M", 1_000_000),
                ("50M50D50M", 0),
            ];

            for &(cigar_str, pos) in test_cases {
                #[expect(
                    clippy::cast_sign_loss,
                    clippy::cast_possible_truncation,
                    reason = "test fixtures: positions are non-negative and ≤ i32::MAX"
                )]
                let pos_u32 = pos as u32;
                let our_pairs =
                    expand_iterator(&parse_cigar_string(cigar_str), Pos0::new(pos_u32).unwrap());
                let hts_pairs = htslib_pairs(cigar_str, pos);
                assert_eq!(
                    our_pairs, hts_pairs,
                    "CIGAR '{cigar_str}' at pos {pos}: seqair AlignedPairs (expanded) \
                     differs from rust-htslib::aligned_pairs_full"
                );
            }
        }

        // r[verify cigar.aligned_pairs.htslib_equivalence]
        #[test]
        fn match_kind_does_not_change_htslib_shape() {
            // Critical invariant: adding `kind: MatchKind` to AlignedPair::Match
            // must NOT change the (qpos, rpos) sequence — htslib parity is
            // about positions, not op kinds. M/=/X with the same lengths must
            // produce byte-identical expansions.
            let cigars = ["5M", "5=", "5X"];
            let pos = 100;

            let mut expansions = Vec::new();
            for s in cigars {
                expansions.push(expand_iterator(&parse_cigar_string(s), Pos0::new(pos).unwrap()));
            }
            assert_eq!(expansions[0], expansions[1], "5M and 5= must expand identically");
            assert_eq!(expansions[1], expansions[2], "5= and 5X must expand identically");
        }

        /// Build a rust-htslib `CigarString` from a CIGAR string like `"5M2I3D"`.
        fn build_htslib_cigar(s: &str) -> rust_htslib::bam::record::CigarString {
            use rust_htslib::bam::record::{Cigar, CigarString};
            let mut cigars = Vec::new();
            let mut num = 0u32;
            for b in s.bytes() {
                match b {
                    b'0'..=b'9' => {
                        num = num.saturating_mul(10).saturating_add(u32::from(b - b'0'));
                    }
                    b'M' => {
                        cigars.push(Cigar::Match(num));
                        num = 0;
                    }
                    b'I' => {
                        cigars.push(Cigar::Ins(num));
                        num = 0;
                    }
                    b'D' => {
                        cigars.push(Cigar::Del(num));
                        num = 0;
                    }
                    b'N' => {
                        cigars.push(Cigar::RefSkip(num));
                        num = 0;
                    }
                    b'S' => {
                        cigars.push(Cigar::SoftClip(num));
                        num = 0;
                    }
                    b'H' => {
                        cigars.push(Cigar::HardClip(num));
                        num = 0;
                    }
                    b'P' => {
                        cigars.push(Cigar::Pad(num));
                        num = 0;
                    }
                    b'=' => {
                        cigars.push(Cigar::Equal(num));
                        num = 0;
                    }
                    b'X' => {
                        cigars.push(Cigar::Diff(num));
                        num = 0;
                    }
                    _ => {}
                }
            }
            CigarString(cigars)
        }

        // r[verify cigar.aligned_pairs.htslib_equivalence]
        mod htslib_proptests {
            use super::*;
            use proptest::prelude::*;

            /// Generate a CIGAR fragment as `(char, len)`. Excludes `P` because
            /// rust-htslib's `aligned_pairs_full` panics on `Cigar::Pad`. Excludes
            /// op codes 9..=14 because rust-htslib has no representation for them.
            /// Restricts to non-empty (1..=20) lengths because zero-length op skip
            /// is htslib-equivalent (its for-loop simply doesn't iterate) but our
            /// expansion explicitly drops len=0 events; testing both produces the
            /// same empty contribution but the `assert_eq!` on `Vec<...>` would
            /// pass trivially. Keeping len > 0 stresses the actual walking logic.
            fn arb_op_char_len() -> impl Strategy<Value = (char, u32)> {
                let chars = prop_oneof![
                    Just('M'),
                    Just('I'),
                    Just('D'),
                    Just('N'),
                    Just('S'),
                    Just('H'),
                    Just('='),
                    Just('X'),
                ];
                (chars, 1u32..=20u32)
            }

            fn arb_cigar_string() -> impl Strategy<Value = String> {
                proptest::collection::vec(arb_op_char_len(), 1..=10).prop_map(|ops| {
                    let mut s = String::new();
                    for (c, n) in ops {
                        s.push_str(&n.to_string());
                        s.push(c);
                    }
                    s
                })
            }

            proptest! {
                /// For random valid CIGARs (M/I/D/N/S/H/=/X with non-zero
                /// lengths) at random positions, seqair's expanded
                /// `AlignedPairs` output MUST match rust-htslib's
                /// `aligned_pairs_full()` exactly.
                ///
                /// This is the strongest possible parity test we can build:
                /// rust-htslib is the htslib-binding ground truth, and the
                /// proptest exercises the full CIGAR-walk state machine on
                /// inputs we never hand-wrote.
                #[test]
                fn matches_htslib_random_cigars(
                    cigar_str in arb_cigar_string(),
                    pos in 0i64..=100_000i64,
                ) {
                    #[expect(
                        clippy::cast_sign_loss,
                        clippy::cast_possible_truncation,
                        reason = "proptest range 0..=100_000 fits in u32"
                    )]
                    let pos_u32 = pos as u32;
                    let our_pairs = expand_iterator(
                        &parse_cigar_string(&cigar_str),
                        Pos0::new(pos_u32).unwrap(),
                    );
                    let hts_pairs = htslib_pairs(&cigar_str, pos);
                    prop_assert_eq!(
                        our_pairs,
                        hts_pairs,
                        "CIGAR '{}' at pos {} diverges from rust-htslib",
                        cigar_str,
                        pos,
                    );
                }
            }
        }

        /// Parse a CIGAR string like `"5M2I3D"` into our `CigarOp` vec.
        fn parse_cigar_string(s: &str) -> Vec<CigarOp> {
            let mut ops = Vec::new();
            let mut num = 0u32;
            for b in s.bytes() {
                match b {
                    b'0'..=b'9' => {
                        num = num.saturating_mul(10).saturating_add(u32::from(b - b'0'));
                    }
                    b'M' => {
                        ops.push(Op::new(CigarOpType::Match, num));
                        num = 0;
                    }
                    b'I' => {
                        ops.push(Op::new(CigarOpType::Insertion, num));
                        num = 0;
                    }
                    b'D' => {
                        ops.push(Op::new(CigarOpType::Deletion, num));
                        num = 0;
                    }
                    b'N' => {
                        ops.push(Op::new(CigarOpType::RefSkip, num));
                        num = 0;
                    }
                    b'S' => {
                        ops.push(Op::new(CigarOpType::SoftClip, num));
                        num = 0;
                    }
                    b'H' => {
                        ops.push(Op::new(CigarOpType::HardClip, num));
                        num = 0;
                    }
                    b'P' => {
                        ops.push(Op::new(CigarOpType::Padding, num));
                        num = 0;
                    }
                    b'=' => {
                        ops.push(Op::new(CigarOpType::SeqMatch, num));
                        num = 0;
                    }
                    b'X' => {
                        ops.push(Op::new(CigarOpType::SeqMismatch, num));
                        num = 0;
                    }
                    _ => {}
                }
            }
            ops
        }
    }

    // ── SlimRecord integration via push_raw → store → SlimRecord round-trip ──

    mod slim_record_tests {
        use super::super::super::owned_record::OwnedBamRecord;
        use super::super::super::record_store::RecordStore;
        use super::*;
        use seqair_types::{BamFlags, Base, BaseQuality};

        /// Build a record via [`OwnedBamRecord`], serialize to BAM bytes, push
        /// into a fresh [`RecordStore`] via `push_raw`.
        fn store_with_record(pos: u32, cigar: &[CigarOp], seq_len: usize) -> RecordStore<()> {
            let rec = OwnedBamRecord::builder(0, Some(Pos0::new(pos).unwrap()), b"r".to_vec())
                .flags(BamFlags::empty())
                .cigar(cigar.to_vec())
                .seq(vec![Base::A; seq_len])
                .qual(vec![BaseQuality::from_byte(30); seq_len])
                .build()
                .unwrap();
            let mut buf = Vec::new();
            rec.to_bam_bytes(&mut buf).unwrap();

            let mut store = RecordStore::<()>::new();
            let _ = store.push_raw(&buf, &mut ()).unwrap();
            store
        }

        // r[verify cigar.aligned_pairs.slim_record]
        #[test]
        fn slim_record_round_trips_simple_match() {
            let cigar = [m(5)];
            let store = store_with_record(100, &cigar, 5);
            let rec = store.record(0);
            let pairs: Vec<_> = rec.aligned_pairs(&store).unwrap().collect();
            assert_eq!(pairs.len(), 5);
            assert_eq!(pairs[0], match_m(0, p0(100)));
            assert_eq!(pairs[4], match_m(4, p0(104)));
        }

        // r[verify cigar.aligned_pairs.slim_record]
        #[test]
        fn slim_record_matches_owned_record_walk() {
            // Build once, push into a store, then walk via both entry points.
            // The AlignedPair sequences must be identical.
            let cigar = vec![m(2), ins(1), m(2), del(1), m(2)];
            let owned = OwnedBamRecord::builder(0, Some(Pos0::new(200).unwrap()), b"r".to_vec())
                .flags(BamFlags::empty())
                .cigar(cigar.clone())
                .seq(vec![Base::A; 7])
                .qual(vec![BaseQuality::from_byte(30); 7])
                .build()
                .unwrap();
            let mut buf = Vec::new();
            owned.to_bam_bytes(&mut buf).unwrap();

            let mut store = RecordStore::<()>::new();
            let _ = store.push_raw(&buf, &mut ()).unwrap();

            let slim = store.record(0);
            let slim_pairs: Vec<_> = slim.aligned_pairs(&store).unwrap().collect();
            let owned_pairs: Vec<_> = owned.aligned_pairs().unwrap().collect();
            assert_eq!(slim_pairs, owned_pairs);
        }
    }
}