Skip to content

Commit 45f1370

Browse files
committed
fix: catch out-of-range k-mer lengths in debug builds for public APIs
reverse_complement_bits already asserted 1 <= k <= 32 in debug, but lacked a comment explaining the release-mode behaviour. validate_and_pack asserted non-empty input but silently truncated sequences longer than 32. Add debug_assert!(seq.len() <= 32) and a SAFETY comment so misuse is caught early in tests without penalising release performance.
1 parent 355d830 commit 45f1370

1 file changed

Lines changed: 9 additions & 1 deletion

File tree

src/kmer.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,9 @@ fn unpack_to_bytes_from_raw(packed_bits: u64, k: usize) -> Bytes {
482482
/// Panics in debug builds if `k` is 0 or greater than 32.
483483
#[inline]
484484
pub const fn reverse_complement_bits(bits: u64, k: usize) -> u64 {
485+
// SAFETY: k is only validated via debug_assert — in release builds, k=0
486+
// causes a shift by 64 (Rust wraps to 0) and k>32 overflows the mask.
487+
// All internal callers guarantee 1 <= k <= 32 via KmerLength validation.
485488
debug_assert!(k >= 1 && k <= 32, "k must be 1..=32");
486489

487490
// Step 1: Complement all 2-bit pairs (A<->T, C<->G is XOR with 0b11 per pair)
@@ -534,7 +537,7 @@ pub const fn canonical_bits(packed: u64, k: usize) -> u64 {
534537
///
535538
/// # Panics
536539
///
537-
/// Panics in debug builds if `seq` is empty.
540+
/// Panics in debug builds if `seq` is empty or longer than 32.
538541
///
539542
/// # Examples
540543
///
@@ -557,6 +560,11 @@ pub fn validate_and_pack(seq: &[u8]) -> Result<u64, InvalidBaseError> {
557560
!seq.is_empty(),
558561
"validate_and_pack requires a non-empty slice"
559562
);
563+
debug_assert!(
564+
seq.len() <= 32,
565+
"validate_and_pack: sequence length {len} exceeds maximum k-mer size 32",
566+
len = seq.len()
567+
);
560568
let mut packed: u64 = 0;
561569
for (i, &b) in seq.iter().enumerate() {
562570
match b {

0 commit comments

Comments
 (0)