1use core::cell::RefCell;
2use std::ops::{Deref, DerefMut};
3use traits::Seq;
4use wide::u16x8;
5
6use crate::{intrinsics::transpose, padded_it::ChunkIt};
7
8use super::*;
9
10type SimdBuf = [S; 8];
11
12struct RecycledBox(Option<Box<SimdBuf>>);
13
14thread_local! {
15 static RECYCLED_BOX_CACHE: RefCell<Vec<Box<SimdBuf>>> = {
16 RefCell::new(vec![Box::new(SimdBuf::default())])
17 };
18}
19
20impl RecycledBox {
21 #[inline(always)]
22 fn take() -> Self {
23 let mut buf = RECYCLED_BOX_CACHE.with_borrow_mut(|v| RecycledBox(v.pop()));
24 buf.init_if_needed();
25 buf
26 }
27
28 #[inline(always)]
29 fn init_if_needed(&mut self) {
30 if self.0.is_none() {
31 self.0 = Some(Box::new(SimdBuf::default()));
32 }
33 }
34
35 #[inline(always)]
36 fn get(&self) -> &SimdBuf {
37 unsafe { self.0.as_ref().unwrap_unchecked() }
38 }
39
40 #[inline(always)]
41 fn get_mut(&mut self) -> &mut SimdBuf {
42 unsafe { self.0.as_mut().unwrap_unchecked() }
43 }
44}
45
46impl Deref for RecycledBox {
47 type Target = SimdBuf;
48
49 #[inline(always)]
50 fn deref(&self) -> &Self::Target {
51 self.get()
52 }
53}
54impl DerefMut for RecycledBox {
55 #[inline(always)]
56 fn deref_mut(&mut self) -> &mut SimdBuf {
57 self.get_mut()
58 }
59}
60
61impl Drop for RecycledBox {
62 #[inline(always)]
63 fn drop(&mut self) {
64 let mut x = None;
65 core::mem::swap(&mut x, &mut self.0);
66 RECYCLED_BOX_CACHE.with_borrow_mut(|v| v.push(unsafe { x.unwrap_unchecked() }));
67 }
68}
69
70struct RecycledVec(Vec<S>);
71
72thread_local! {
73 static RECYCLED_VEC_CACHE: RefCell<Vec<Vec<S>>> = {
74 RefCell::new(vec![])
75 };
76}
77
78impl RecycledVec {
79 #[inline(always)]
80 fn take() -> Self {
81 RecycledVec(RECYCLED_VEC_CACHE.with_borrow_mut(|v| v.pop().unwrap_or_default()))
82 }
83}
84
85impl Deref for RecycledVec {
86 type Target = Vec<S>;
87 #[inline(always)]
88 fn deref(&self) -> &Self::Target {
89 &self.0
90 }
91}
92impl DerefMut for RecycledVec {
93 #[inline(always)]
94 fn deref_mut(&mut self) -> &mut Self::Target {
95 &mut self.0
96 }
97}
98impl Drop for RecycledVec {
99 #[inline(always)]
100 fn drop(&mut self) {
101 RECYCLED_VEC_CACHE.with_borrow_mut(|v| v.push(std::mem::take(&mut self.0)));
102 }
103}
104
105#[doc(hidden)]
106pub struct Bits<const B: usize>;
107#[doc(hidden)]
108pub trait SupportedBits {}
109impl SupportedBits for Bits<1> {}
110impl SupportedBits for Bits<2> {}
111impl SupportedBits for Bits<4> {}
112impl SupportedBits for Bits<8> {}
113
114pub(crate) const PADDING: usize = 48;
116
117#[doc(hidden)]
119#[derive(Copy, Clone, Debug, MemSize, MemDbg)]
120pub struct PackedSeqBase<'s, const B: usize>
121where
122 Bits<B>: SupportedBits,
123{
124 seq: &'s [u8],
126 offset: usize,
128 len: usize,
130}
131
132#[doc(hidden)]
134#[derive(Clone, Debug, MemSize, MemDbg)]
135#[cfg_attr(feature = "pyo3", pyo3::pyclass)]
136#[cfg_attr(feature = "epserde", derive(epserde::Epserde))]
137pub struct PackedSeqVecBase<const B: usize>
138where
139 Bits<B>: SupportedBits,
140{
141 pub(crate) seq: Vec<u8>,
145
146 len: usize,
148}
149
150pub type PackedSeq<'s> = PackedSeqBase<'s, 2>;
151pub type PackedSeqVec = PackedSeqVecBase<2>;
152pub type BitSeq<'s> = PackedSeqBase<'s, 1>;
153pub type BitSeqVec = PackedSeqVecBase<1>;
154
155impl<'s, const B: usize> PackedSeqBase<'s, B>
158where
159 Bits<B>: SupportedBits,
160{
161 const CHAR_MASK: u64 = (1 << B) - 1;
163 const SIMD_B: S = S::new([B as u32; 8]);
164 const SIMD_CHAR_MASK: S = S::new([(1 << B) - 1; 8]);
165 const C8: usize = 8 / B;
167 const C32: usize = 32 / B;
169 const C256: usize = 256 / B;
171 const K64: usize = (64 - 8) / B + 1;
173}
174
175impl<const B: usize> PackedSeqVecBase<B>
177where
178 Bits<B>: SupportedBits,
179{
180 const C8: usize = 8 / B;
182}
183
184impl<const B: usize> Default for PackedSeqVecBase<B>
185where
186 Bits<B>: SupportedBits,
187{
188 fn default() -> Self {
189 Self {
190 seq: vec![0; PADDING],
191 len: 0,
192 }
193 }
194}
195
196#[inline(always)]
201pub fn pack_char(base: u8) -> u8 {
202 match base {
203 b'a' | b'A' => 0,
204 b'c' | b'C' => 1,
205 b'g' | b'G' => 3,
206 b't' | b'T' => 2,
207 _ => panic!(
208 "Unexpected character '{}' with ASCII value {base}. Expected one of ACTGactg.",
209 base as char
210 ),
211 }
212}
213
214#[inline(always)]
216pub fn pack_char_lossy(base: u8) -> u8 {
217 (base >> 1) & 3
218}
219#[inline(always)]
222pub fn pack_kmer_lossy(slice: &[u8]) -> u64 {
223 let mut kmer = 0;
224 for (i, &base) in slice.iter().enumerate() {
225 kmer |= (pack_char_lossy(base) as u64) << (2 * i);
226 }
227 kmer
228}
229#[inline(always)]
231pub fn pack_kmer_u128_lossy(slice: &[u8]) -> u128 {
232 let mut kmer = 0;
233 for (i, &base) in slice.iter().enumerate() {
234 kmer |= (pack_char_lossy(base) as u128) << (2 * i);
235 }
236 kmer
237}
238
239#[inline(always)]
241pub fn unpack_base(base: u8) -> u8 {
242 debug_assert!(base < 4, "Base {base} is not <4.");
243 b"ACTG"[base as usize]
244}
245
246#[inline(always)]
249pub fn unpack_kmer(kmer: u64) -> [u8; 32] {
250 std::array::from_fn(|i| unpack_base(((kmer >> (2 * i)) & 3) as u8))
251}
252#[inline(always)]
254pub fn unpack_kmer_into_vec(kmer: u64, k: usize, out: &mut Vec<u8>) {
255 out.clear();
256 out.extend((0..k).map(|i| unpack_base(((kmer >> (2 * i)) & 3) as u8)));
257}
258#[inline(always)]
260pub fn unpack_kmer_to_vec(kmer: u64, k: usize) -> Vec<u8> {
261 let mut out = vec![];
262 unpack_kmer_into_vec(kmer, k, &mut out);
263 out
264}
265
266#[inline(always)]
269pub fn unpack_kmer_u128(kmer: u128) -> [u8; 64] {
270 std::array::from_fn(|i| unpack_base(((kmer >> (2 * i)) & 3) as u8))
271}
272#[inline(always)]
274pub fn unpack_kmer_u128_into_vec(kmer: u128, k: usize, out: &mut Vec<u8>) {
275 out.clear();
276 out.extend((0..k).map(|i| unpack_base(((kmer >> (2 * i)) & 3) as u8)));
277}
278#[inline(always)]
280pub fn unpack_kmer_u128_to_vec(kmer: u128, k: usize) -> Vec<u8> {
281 let mut out = vec![];
282 unpack_kmer_u128_into_vec(kmer, k, &mut out);
283 out
284}
285
286#[inline(always)]
288pub const fn complement_char(base: u8) -> u8 {
289 match base {
290 b'A' => b'T',
291 b'C' => b'G',
292 b'G' => b'C',
293 b'T' => b'A',
294 _ => panic!("Unexpected character. Expected one of ACTGactg.",),
295 }
296}
297
298#[inline(always)]
300pub const fn complement_base(base: u8) -> u8 {
301 base ^ 2
302}
303
304#[inline(always)]
306pub fn complement_base_simd(base: u32x8) -> u32x8 {
307 const TWO: u32x8 = u32x8::new([2; 8]);
308 base ^ TWO
309}
310
311#[inline(always)]
313const fn revcomp_raw(word: u64) -> u64 {
314 #[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
315 {
316 let mut res = word.reverse_bits(); res = ((res >> 1) & 0x5555_5555_5555_5555) | ((res & 0x5555_5555_5555_5555) << 1);
318 res ^ 0xAAAA_AAAA_AAAA_AAAA
319 }
320
321 #[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))]
322 {
323 let mut res = word.swap_bytes();
324 res = ((res >> 4) & 0x0F0F_0F0F_0F0F_0F0F) | ((res & 0x0F0F_0F0F_0F0F_0F0F) << 4);
325 res = ((res >> 2) & 0x3333_3333_3333_3333) | ((res & 0x3333_3333_3333_3333) << 2);
326 res ^ 0xAAAA_AAAA_AAAA_AAAA
327 }
328}
329
330#[inline(always)]
332pub const fn revcomp_u64(word: u64, len: usize) -> u64 {
333 revcomp_raw(word) >> (usize::BITS as usize - 2 * len)
334}
335
336#[inline(always)]
337pub const fn revcomp_u128(word: u128, len: usize) -> u128 {
338 let low = word as u64;
339 let high = (word >> 64) as u64;
340 let rlow = revcomp_raw(low);
341 let rhigh = revcomp_raw(high);
342 let out = ((rlow as u128) << 64) | rhigh as u128;
343 out >> (u128::BITS as usize - 2 * len)
344}
345
346#[inline(always)]
351pub fn char_is_ambiguous(base: u8) -> u8 {
352 let table = b"ACTG";
354 let upper_mask = !(b'a' - b'A');
355 (table[pack_char_lossy(base) as usize] != (base & upper_mask)) as u8
356}
357
358#[inline(always)]
360pub const fn rev_u64(word: u64, len: usize) -> u64 {
361 word.reverse_bits() >> (usize::BITS as usize - len)
362}
363
364#[inline(always)]
366pub const fn rev_u128(word: u128, len: usize) -> u128 {
367 word.reverse_bits() >> (u128::BITS as usize - len)
368}
369
370impl<const B: usize> PackedSeqBase<'_, B>
373where
374 Bits<B>: SupportedBits,
375{
376 #[inline(always)]
378 pub fn normalize(&self) -> Self {
379 let start_byte = self.offset / Self::C8;
380 let end_byte = (self.offset + self.len).div_ceil(Self::C8);
381 Self {
382 seq: &self.seq[start_byte..end_byte + PADDING],
383 offset: self.offset % Self::C8,
384 len: self.len,
385 }
386 }
387
388 #[inline(always)]
390 pub fn unpack(&self) -> Vec<u8> {
391 self.iter_bp().map(unpack_base).collect()
392 }
393}
394
395#[inline(always)]
397pub(crate) unsafe fn read_slice_32_unchecked(seq: &[u8], idx: usize) -> u32x8 {
398 unsafe {
399 let src = seq.as_ptr().add(idx);
400 debug_assert!(idx + 32 <= seq.len());
401 std::mem::transmute::<_, *const u32x8>(src).read_unaligned()
402 }
403}
404
405#[inline(always)]
407pub(crate) fn read_slice_32(seq: &[u8], idx: usize) -> u32x8 {
408 unsafe {
409 let src = seq.as_ptr().add(idx);
410 if idx + 32 <= seq.len() {
411 std::mem::transmute::<_, *const u32x8>(src).read_unaligned()
412 } else {
413 let num_bytes = seq.len().saturating_sub(idx);
414 let mut result = [0u8; 32];
415 std::ptr::copy_nonoverlapping(src, result.as_mut_ptr(), num_bytes);
416 std::mem::transmute(result)
417 }
418 }
419}
420
421#[allow(unused)]
423#[inline(always)]
424pub(crate) fn read_slice_16(seq: &[u8], idx: usize) -> u16x8 {
425 unsafe {
426 let src = seq.as_ptr().add(idx);
427 if idx + 16 <= seq.len() {
428 std::mem::transmute::<_, *const u16x8>(src).read_unaligned()
429 } else {
430 let num_bytes = seq.len().saturating_sub(idx);
431 let mut result = [0u8; 16];
432 std::ptr::copy_nonoverlapping(src, result.as_mut_ptr(), num_bytes);
433 std::mem::transmute(result)
434 }
435 }
436}
437
438impl<'s, const B: usize> Seq<'s> for PackedSeqBase<'s, B>
439where
440 Bits<B>: SupportedBits,
441{
442 const BITS_PER_CHAR: usize = B;
443 const BASES_PER_BYTE: usize = Self::C8;
444 type SeqVec = PackedSeqVecBase<B>;
445
446 #[inline(always)]
447 fn len(&self) -> usize {
448 self.len
449 }
450
451 #[inline(always)]
452 fn is_empty(&self) -> bool {
453 self.len == 0
454 }
455
456 #[inline(always)]
457 fn get_ascii(&self, index: usize) -> u8 {
458 unpack_base(self.get(index))
459 }
460
461 #[inline(always)]
464 fn as_u64(&self) -> u64 {
465 assert!(self.len() <= 64 / B);
466
467 let mask = u64::MAX >> (64 - B * self.len());
468
469 if self.len() <= Self::K64 {
472 let x = unsafe { (self.seq.as_ptr() as *const u64).read_unaligned() };
473 (x >> (B * self.offset)) & mask
474 } else {
475 let x = unsafe { (self.seq.as_ptr() as *const u128).read_unaligned() };
476 (x >> (B * self.offset)) as u64 & mask
477 }
478 }
479
480 #[inline(always)]
483 fn revcomp_as_u64(&self) -> u64 {
484 match B {
485 1 => rev_u64(self.as_u64(), self.len()),
486 2 => revcomp_u64(self.as_u64(), self.len()),
487 _ => panic!("Rev(comp) is only supported for 1-bit and 2-bit alphabets."),
488 }
489 }
490
491 #[inline(always)]
494 fn as_u128(&self) -> u128 {
495 assert!(
496 self.len() <= (128 - 8) / B + 1,
497 "Sequences >61 long cannot be read with a single unaligned u128 read."
498 );
499
500 let mask = u128::MAX >> (128 - B * self.len());
501
502 let x = unsafe { (self.seq.as_ptr() as *const u128).read_unaligned() };
505 (x >> (B * self.offset)) & mask
506 }
507
508 #[inline(always)]
511 fn revcomp_as_u128(&self) -> u128 {
512 match B {
513 1 => rev_u128(self.as_u128(), self.len()),
514 2 => revcomp_u128(self.as_u128(), self.len()),
515 _ => panic!("Rev(comp) is only supported for 1-bit and 2-bit alphabets."),
516 }
517 }
518
519 #[inline(always)]
520 fn to_vec(&self) -> PackedSeqVecBase<B> {
521 assert_eq!(self.offset, 0);
522 PackedSeqVecBase {
523 seq: self
524 .seq
525 .iter()
526 .copied()
527 .chain(std::iter::repeat_n(0u8, PADDING))
528 .collect(),
529 len: self.len,
530 }
531 }
532
533 fn to_revcomp(&self) -> PackedSeqVecBase<B> {
534 match B {
535 1 | 2 => {}
536 _ => panic!("Can only reverse (&complement) 1-bit and 2-bit packed sequences.",),
537 }
538
539 let mut seq = self.seq[..(self.offset + self.len).div_ceil(Self::C8)]
540 .iter()
541 .rev()
543 .copied()
544 .map(|mut res| {
545 match B {
546 2 => {
547 res = ((res >> 4) & 0x0F) | ((res & 0x0F) << 4);
550 res = ((res >> 2) & 0x33) | ((res & 0x33) << 2);
551 res ^ 0xAA
553 }
554 1 => res.reverse_bits(),
555 _ => unreachable!(),
556 }
557 })
558 .chain(std::iter::repeat_n(0u8, PADDING))
559 .collect::<Vec<u8>>();
560
561 let new_offset = (Self::C8 - (self.offset + self.len) % Self::C8) % Self::C8;
563
564 if new_offset > 0 {
565 let shift = B * new_offset;
567 *seq.last_mut().unwrap() >>= shift;
568 for i in 0..seq.len() - 1 {
570 seq[i] = (seq[i] >> shift) | (seq[i + 1] << (8 - shift));
571 }
572 }
573
574 PackedSeqVecBase { seq, len: self.len }
575 }
576
577 #[inline(always)]
578 fn slice(&self, range: Range<usize>) -> Self {
579 debug_assert!(
580 range.end <= self.len,
581 "Slice index out of bounds: {} > {}",
582 range.end,
583 self.len
584 );
585 PackedSeqBase {
586 seq: self.seq,
587 offset: self.offset + range.start,
588 len: range.end - range.start,
589 }
590 .normalize()
591 }
592
593 #[inline(always)]
594 fn iter_bp(self) -> impl ExactSizeIterator<Item = u8> {
595 assert!(self.len <= self.seq.len() * Self::C8);
596
597 let this = self.normalize();
598
599 let mut byte = 0;
601 (0..this.len + this.offset)
602 .map(
603 #[inline(always)]
604 move |i| {
605 if i % Self::C8 == 0 {
606 byte = this.seq[i / Self::C8];
607 }
608 (byte >> (B * (i % Self::C8))) & Self::CHAR_MASK as u8
610 },
611 )
612 .advance(this.offset)
613 }
614
615 #[inline(always)]
616 fn par_iter_bp(self, context: usize) -> PaddedIt<impl ChunkIt<S>> {
617 self.par_iter_bp_with_buf(context, RecycledBox::take())
618 }
619
620 #[inline(always)]
621 fn par_iter_bp_delayed(self, context: usize, delay: Delay) -> PaddedIt<impl ChunkIt<(S, S)>> {
622 self.par_iter_bp_delayed_with_factor(context, delay, 1)
623 }
624
625 #[inline(always)]
628 fn par_iter_bp_delayed_2(
629 self,
630 context: usize,
631 delay1: Delay,
632 delay2: Delay,
633 ) -> PaddedIt<impl ChunkIt<(S, S, S)>> {
634 self.par_iter_bp_delayed_2_with_factor_and_buf(
635 context,
636 delay1,
637 delay2,
638 1,
639 RecycledVec::take(),
640 )
641 }
642
643 fn cmp_lcp(&self, other: &Self) -> (std::cmp::Ordering, usize) {
645 let mut lcp = 0;
646 let min_len = self.len.min(other.len);
647 for i in (0..min_len).step_by(Self::K64) {
648 let len = (min_len - i).min(Self::K64);
649 let this = self.slice(i..i + len);
650 let other = other.slice(i..i + len);
651 let this_word = this.as_u64();
652 let other_word = other.as_u64();
653 if this_word != other_word {
654 let eq = this_word ^ other_word;
656 let t = eq.trailing_zeros() as usize / B * B;
657 lcp += t / B;
658 let mask = (Self::CHAR_MASK) << t;
659 return ((this_word & mask).cmp(&(other_word & mask)), lcp);
660 }
661 lcp += len;
662 }
663 (self.len.cmp(&other.len), lcp)
664 }
665
666 #[inline(always)]
667 fn get(&self, index: usize) -> u8 {
668 let offset = self.offset + index;
669 let idx = offset / Self::C8;
670 let offset = offset % Self::C8;
671 (self.seq[idx] >> (B * offset)) & Self::CHAR_MASK as u8
672 }
673}
674
675impl<'s, const B: usize> PackedSeqBase<'s, B>
676where
677 Bits<B>: SupportedBits,
678{
679 #[inline(always)]
680 pub fn par_iter_bp_with_buf<BUF: DerefMut<Target = [S; 8]>>(
681 self,
682 context: usize,
683 mut buf: BUF,
684 ) -> PaddedIt<impl ChunkIt<S> + use<'s, B, BUF>> {
685 #[cfg(target_endian = "big")]
686 panic!("Big endian architectures are not supported.");
687
688 let this = self.normalize();
689 let o = this.offset;
690 assert!(o < Self::C8);
691
692 let num_kmers = if this.len == 0 {
693 0
694 } else {
695 (this.len + o).saturating_sub(context - 1)
696 };
697 let num_kmers_stride = this.len.saturating_sub(context - 1);
699 let n = num_kmers_stride.div_ceil(L).next_multiple_of(Self::C8);
700 let bytes_per_chunk = n / Self::C8;
701 let padding = Self::C8 * L * bytes_per_chunk - num_kmers_stride;
702
703 let offsets: [usize; 8] = from_fn(|l| l * bytes_per_chunk);
704 let mut cur = S::ZERO;
705
706 let par_len = if num_kmers == 0 {
707 0
708 } else {
709 n + context + o - 1
710 };
711
712 let last_i = par_len.saturating_sub(1) / Self::C32 * Self::C32;
713 assert!(offsets[7] + (last_i / Self::C8) + 32 <= this.seq.len());
715
716 let it = (0..par_len)
717 .map(
718 #[inline(always)]
719 move |i| {
720 if i % Self::C32 == 0 {
721 if i % Self::C256 == 0 {
722 let data: [u32x8; 8] = from_fn(
724 #[inline(always)]
725 |lane| unsafe {
726 read_slice_32_unchecked(
727 this.seq,
728 offsets[lane] + (i / Self::C8),
729 )
730 },
731 );
732 *buf = transpose(data);
733 }
734 cur = buf[(i % Self::C256) / Self::C32];
735 }
736 let chars = cur & Self::SIMD_CHAR_MASK;
738 cur = cur >> Self::SIMD_B;
740 chars
741 },
742 )
743 .advance(o);
744
745 PaddedIt { it, padding }
746 }
747
748 #[inline(always)]
749 pub fn par_iter_bp_delayed_with_factor(
750 self,
751 context: usize,
752 delay: Delay,
753 factor: usize,
754 ) -> PaddedIt<impl ChunkIt<(S, S)> + use<'s, B>> {
755 self.par_iter_bp_delayed_with_factor_and_buf(context, delay, factor, RecycledVec::take())
756 }
757
758 #[inline(always)]
759 pub fn par_iter_bp_delayed_with_buf<BUF: DerefMut<Target = Vec<S>>>(
760 self,
761 context: usize,
762 delay: Delay,
763 buf: BUF,
764 ) -> PaddedIt<impl ChunkIt<(S, S)> + use<'s, B, BUF>> {
765 self.par_iter_bp_delayed_with_factor_and_buf(context, delay, 1, buf)
766 }
767
768 #[inline(always)]
769 pub fn par_iter_bp_delayed_with_factor_and_buf<BUF: DerefMut<Target = Vec<S>>>(
770 self,
771 context: usize,
772 Delay(delay): Delay,
773 factor: usize,
774 mut buf: BUF,
775 ) -> PaddedIt<impl ChunkIt<(S, S)> + use<'s, B, BUF>> {
776 #[cfg(target_endian = "big")]
777 panic!("Big endian architectures are not supported.");
778
779 assert!(
780 delay < usize::MAX / 2,
781 "Delay={} should be >=0.",
782 delay as isize
783 );
784
785 let this = self.normalize();
786 let o = this.offset;
787 assert!(o < Self::C8);
788
789 let num_kmers = if this.len == 0 {
790 0
791 } else {
792 (this.len + o).saturating_sub(context - 1)
793 };
794 let num_kmers_stride = this.len.saturating_sub(context - 1);
796 let n = num_kmers_stride
797 .div_ceil(L)
798 .next_multiple_of(factor * Self::C8);
799 let bytes_per_chunk = n / Self::C8;
800 let padding = Self::C8 * L * bytes_per_chunk - num_kmers_stride;
801
802 let offsets: [usize; 8] = from_fn(|l| l * bytes_per_chunk);
803 let mut upcoming = S::ZERO;
804 let mut upcoming_d = S::ZERO;
805
806 let buf_len = (delay / Self::C32 + 8).next_power_of_two();
811 let buf_mask = buf_len - 1;
812 if buf.capacity() < buf_len {
813 *buf = vec![S::ZERO; buf_len];
815 } else {
816 buf.clear();
818 buf.resize(buf_len, S::ZERO);
819 }
820
821 let mut write_idx = 0;
822 let mut read_idx = (buf_len - delay / Self::C32) % buf_len;
825
826 let par_len = if num_kmers == 0 {
827 0
828 } else {
829 n + context + o - 1
830 };
831
832 let last_i = par_len.saturating_sub(1) / Self::C32 * Self::C32;
833 assert!(offsets[7] + (last_i / Self::C8) + 32 <= this.seq.len());
835
836 let it = (0..par_len)
837 .map(
838 #[inline(always)]
839 move |i| {
840 if i % Self::C32 == 0 {
841 if i % Self::C256 == 0 {
842 let data: [u32x8; 8] = from_fn(
844 #[inline(always)]
845 |lane| unsafe {
846 read_slice_32_unchecked(
847 this.seq,
848 offsets[lane] + (i / Self::C8),
849 )
850 },
851 );
852 unsafe {
853 *TryInto::<&mut [u32x8; 8]>::try_into(
854 buf.get_unchecked_mut(write_idx..write_idx + 8),
855 )
856 .unwrap_unchecked() = transpose(data);
857 }
858 if i == 0 {
859 let elem = !((1u32 << (B * o)) - 1);
861 let mask = S::splat(elem);
862 unsafe { assert_unchecked(write_idx < buf.len()) };
863 buf[write_idx] &= mask;
864 }
865 }
866 unsafe { assert_unchecked(write_idx < buf.len()) };
867 upcoming = buf[write_idx];
868 write_idx += 1;
869 write_idx &= buf_mask;
870 }
871 if i % Self::C32 == delay % Self::C32 {
872 unsafe { assert_unchecked(read_idx < buf.len()) };
873 upcoming_d = buf[read_idx];
874 read_idx += 1;
875 read_idx &= buf_mask;
876 }
877 let chars = upcoming & Self::SIMD_CHAR_MASK;
879 let chars_d = upcoming_d & Self::SIMD_CHAR_MASK;
880 upcoming = upcoming >> Self::SIMD_B;
882 upcoming_d = upcoming_d >> Self::SIMD_B;
883 (chars, chars_d)
884 },
885 )
886 .advance(o);
887
888 PaddedIt { it, padding }
889 }
890
891 #[inline(always)]
892 pub fn par_iter_bp_delayed_2_with_factor(
893 self,
894 context: usize,
895 delay1: Delay,
896 delay2: Delay,
897 factor: usize,
898 ) -> PaddedIt<impl ChunkIt<(S, S, S)> + use<'s, B>> {
899 self.par_iter_bp_delayed_2_with_factor_and_buf(
900 context,
901 delay1,
902 delay2,
903 factor,
904 RecycledVec::take(),
905 )
906 }
907
908 #[inline(always)]
909 pub fn par_iter_bp_delayed_2_with_buf<BUF: DerefMut<Target = Vec<S>>>(
910 self,
911 context: usize,
912 delay1: Delay,
913 delay2: Delay,
914 buf: BUF,
915 ) -> PaddedIt<impl ChunkIt<(S, S, S)> + use<'s, B, BUF>> {
916 self.par_iter_bp_delayed_2_with_factor_and_buf(context, delay1, delay2, 1, buf)
917 }
918
919 #[inline(always)]
925 pub fn par_iter_bp_delayed_2_with_factor_and_buf<BUF: DerefMut<Target = Vec<S>>>(
926 self,
927 context: usize,
928 Delay(delay1): Delay,
929 Delay(delay2): Delay,
930 factor: usize,
931 mut buf: BUF,
932 ) -> PaddedIt<impl ChunkIt<(S, S, S)> + use<'s, B, BUF>> {
933 #[cfg(target_endian = "big")]
934 panic!("Big endian architectures are not supported.");
935
936 let this = self.normalize();
937 let o = this.offset;
938 assert!(o < Self::C8);
939 assert!(delay1 <= delay2, "Delay1 must be at most delay2.");
940
941 let num_kmers = if this.len == 0 {
942 0
943 } else {
944 (this.len + o).saturating_sub(context - 1)
945 };
946 let num_kmers_stride = this.len.saturating_sub(context - 1);
948 let n = num_kmers_stride
949 .div_ceil(L)
950 .next_multiple_of(factor * Self::C8);
951 let bytes_per_chunk = n / Self::C8;
952 let padding = Self::C8 * L * bytes_per_chunk - num_kmers_stride;
953
954 let offsets: [usize; 8] = from_fn(|l| l * bytes_per_chunk);
955 let mut upcoming = S::ZERO;
956 let mut upcoming_d1 = S::ZERO;
957 let mut upcoming_d2 = S::ZERO;
958
959 let buf_len = (delay2 / Self::C32 + 8).next_power_of_two();
961 let buf_mask = buf_len - 1;
962 if buf.capacity() < buf_len {
963 *buf = vec![S::ZERO; buf_len];
965 } else {
966 buf.clear();
968 buf.resize(buf_len, S::ZERO);
969 }
970
971 let mut write_idx = 0;
972 let mut read_idx1 = (buf_len - delay1 / Self::C32) % buf_len;
975 let mut read_idx2 = (buf_len - delay2 / Self::C32) % buf_len;
976
977 let par_len = if num_kmers == 0 {
978 0
979 } else {
980 n + context + o - 1
981 };
982
983 let last_i = par_len.saturating_sub(1) / Self::C32 * Self::C32;
984 assert!(offsets[7] + (last_i / Self::C8) + 32 <= this.seq.len());
986
987 let it = (0..par_len)
988 .map(
989 #[inline(always)]
990 move |i| {
991 if i % Self::C32 == 0 {
992 if i % Self::C256 == 0 {
993 let data: [u32x8; 8] = from_fn(
995 #[inline(always)]
996 |lane| unsafe {
997 read_slice_32_unchecked(
998 this.seq,
999 offsets[lane] + (i / Self::C8),
1000 )
1001 },
1002 );
1003 unsafe {
1004 *TryInto::<&mut [u32x8; 8]>::try_into(
1005 buf.get_unchecked_mut(write_idx..write_idx + 8),
1006 )
1007 .unwrap_unchecked() = transpose(data);
1008 }
1009 if i == 0 {
1011 let elem = !((1u32 << (B * o)) - 1);
1013 let mask = S::splat(elem);
1014 buf[write_idx] &= mask;
1015 }
1016 }
1017 upcoming = buf[write_idx];
1018 write_idx += 1;
1019 write_idx &= buf_mask;
1020 }
1021 if i % Self::C32 == delay1 % Self::C32 {
1022 unsafe { assert_unchecked(read_idx1 < buf.len()) };
1023 upcoming_d1 = buf[read_idx1];
1024 read_idx1 += 1;
1025 read_idx1 &= buf_mask;
1026 }
1027 if i % Self::C32 == delay2 % Self::C32 {
1028 unsafe { assert_unchecked(read_idx2 < buf.len()) };
1029 upcoming_d2 = buf[read_idx2];
1030 read_idx2 += 1;
1031 read_idx2 &= buf_mask;
1032 }
1033 let chars = upcoming & Self::SIMD_CHAR_MASK;
1035 let chars_d1 = upcoming_d1 & Self::SIMD_CHAR_MASK;
1036 let chars_d2 = upcoming_d2 & Self::SIMD_CHAR_MASK;
1037 upcoming = upcoming >> Self::SIMD_B;
1039 upcoming_d1 = upcoming_d1 >> Self::SIMD_B;
1040 upcoming_d2 = upcoming_d2 >> Self::SIMD_B;
1041 (chars, chars_d1, chars_d2)
1042 },
1043 )
1044 .advance(o);
1045
1046 PaddedIt { it, padding }
1047 }
1048}
1049
1050impl<const B: usize> PartialEq for PackedSeqBase<'_, B>
1051where
1052 Bits<B>: SupportedBits,
1053{
1054 fn eq(&self, other: &Self) -> bool {
1056 if self.len != other.len {
1057 return false;
1058 }
1059 for i in (0..self.len).step_by(Self::K64) {
1060 let len = (self.len - i).min(Self::K64);
1061 let this = self.slice(i..i + len);
1062 let that = other.slice(i..i + len);
1063 if this.as_u64() != that.as_u64() {
1064 return false;
1065 }
1066 }
1067 true
1068 }
1069}
1070
1071impl<const B: usize> Eq for PackedSeqBase<'_, B> where Bits<B>: SupportedBits {}
1072
1073impl<const B: usize> PartialOrd for PackedSeqBase<'_, B>
1074where
1075 Bits<B>: SupportedBits,
1076{
1077 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1078 Some(self.cmp(other))
1079 }
1080}
1081
1082impl<const B: usize> Ord for PackedSeqBase<'_, B>
1083where
1084 Bits<B>: SupportedBits,
1085{
1086 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1088 let min_len = self.len.min(other.len);
1089 for i in (0..min_len).step_by(Self::K64) {
1090 let len = (min_len - i).min(Self::K64);
1091 let this = self.slice(i..i + len);
1092 let other = other.slice(i..i + len);
1093 let this_word = this.as_u64();
1094 let other_word = other.as_u64();
1095 if this_word != other_word {
1096 let eq = this_word ^ other_word;
1098 let t = eq.trailing_zeros() as usize / B * B;
1099 let mask = (Self::CHAR_MASK) << t;
1100 return (this_word & mask).cmp(&(other_word & mask));
1101 }
1102 }
1103 self.len.cmp(&other.len)
1104 }
1105}
1106
1107impl<const B: usize> SeqVec for PackedSeqVecBase<B>
1108where
1109 Bits<B>: SupportedBits,
1110{
1111 type Seq<'s> = PackedSeqBase<'s, B>;
1112
1113 #[inline(always)]
1114 fn into_raw(mut self) -> Vec<u8> {
1115 self.seq.resize(self.len.div_ceil(Self::C8), 0);
1116 self.seq
1117 }
1118
1119 #[inline(always)]
1120 fn as_slice(&self) -> Self::Seq<'_> {
1121 PackedSeqBase {
1122 seq: &self.seq[..self.len.div_ceil(Self::C8) + PADDING],
1123 offset: 0,
1124 len: self.len,
1125 }
1126 }
1127
1128 #[inline(always)]
1129 fn len(&self) -> usize {
1130 self.len
1131 }
1132
1133 #[inline(always)]
1134 fn is_empty(&self) -> bool {
1135 self.len == 0
1136 }
1137
1138 #[inline(always)]
1139 fn clear(&mut self) {
1140 self.seq.clear();
1141 self.len = 0;
1142 }
1143
1144 fn push_seq<'a>(&mut self, seq: PackedSeqBase<'_, B>) -> Range<usize> {
1145 let start = self.len.next_multiple_of(Self::C8) + seq.offset;
1146 let end = start + seq.len();
1147
1148 self.seq.resize(self.len.div_ceil(Self::C8), 0);
1150 self.seq.extend(seq.seq);
1152 self.len = end;
1153 start..end
1154 }
1155
1156 fn push_ascii(&mut self, seq: &[u8]) -> Range<usize> {
1165 match B {
1166 1 | 2 => {}
1167 _ => panic!(
1168 "Can only use ASCII input for 2-bit DNA packing, or 1-bit ambiguous indicators."
1169 ),
1170 }
1171
1172 self.seq
1173 .resize((self.len + seq.len()).div_ceil(Self::C8) + PADDING, 0);
1174 let start_aligned = self.len.next_multiple_of(Self::C8);
1175 let start = self.len;
1176 let len = seq.len();
1177 let mut idx = self.len / Self::C8;
1178
1179 let parse_base = |base| match B {
1180 1 => char_is_ambiguous(base),
1181 2 => pack_char_lossy(base),
1182 _ => unreachable!(),
1183 };
1184
1185 let unaligned = core::cmp::min(start_aligned - start, len);
1186 if unaligned > 0 {
1187 let mut packed_byte = self.seq[idx];
1188 for &base in &seq[..unaligned] {
1189 packed_byte |= parse_base(base) << ((self.len % Self::C8) * B);
1190 self.len += 1;
1191 }
1192 self.seq[idx] = packed_byte;
1193 idx += 1;
1194 }
1195
1196 #[allow(unused)]
1197 let mut last = unaligned;
1198
1199 if B == 2 {
1200 #[cfg(all(target_arch = "x86_64", target_feature = "bmi2"))]
1201 {
1202 last = unaligned + (len - unaligned) / 8 * 8;
1203
1204 for i in (unaligned..last).step_by(8) {
1205 let chunk =
1206 unsafe { seq.get_unchecked(i..i + 8).try_into().unwrap_unchecked() };
1207 let ascii = u64::from_le_bytes(chunk);
1208 let packed_bytes =
1209 unsafe { std::arch::x86_64::_pext_u64(ascii, 0x0606060606060606) } as u16;
1210 unsafe {
1211 self.seq
1212 .get_unchecked_mut(idx..(idx + 2))
1213 .copy_from_slice(&packed_bytes.to_le_bytes())
1214 };
1215 idx += 2;
1216 self.len += 8;
1217 }
1218 }
1219
1220 #[cfg(target_feature = "neon")]
1221 {
1222 use core::arch::aarch64::{
1223 vandq_u8, vdup_n_u8, vld1q_u8, vpadd_u8, vshlq_u8, vst1_u8,
1224 };
1225 use core::mem::transmute;
1226
1227 last = unaligned + (len - unaligned) / 16 * 16;
1228
1229 for i in (unaligned..last).step_by(16) {
1230 unsafe {
1231 let ascii = vld1q_u8(seq.as_ptr().add(i));
1232 let masked_bits = vandq_u8(ascii, transmute([6i8; 16]));
1233 let (bits_0, bits_1) = transmute(vshlq_u8(
1234 masked_bits,
1235 transmute([-1i8, 1, 3, 5, -1, 1, 3, 5, -1, 1, 3, 5, -1, 1, 3, 5]),
1236 ));
1237 let half_packed = vpadd_u8(bits_0, bits_1);
1238 let packed = vpadd_u8(half_packed, vdup_n_u8(0));
1239 vst1_u8(self.seq.as_mut_ptr().add(idx), packed);
1240 idx += Self::C8;
1241 self.len += 16;
1242 }
1243 }
1244 }
1245 }
1246
1247 if B == 1 {
1248 #[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
1249 {
1250 last = len;
1251 self.len += len - unaligned;
1252
1253 let mut last_i = unaligned;
1254
1255 for i in (unaligned..last).step_by(32) {
1256 use std::mem::transmute as t;
1257
1258 use wide::CmpEq;
1259 type S = wide::i8x32;
1261 let chars: S = unsafe { t(read_slice_32(seq, i)) };
1262 let upper_mask = !(b'a' - b'A');
1263 let chars = chars & S::splat(upper_mask as i8);
1265 let lossy_encoded = chars & S::splat(6);
1266 let table = unsafe { S::from(t::<_, S>(*b"AxCxTxGxxxxxxxxxAxCxTxGxxxxxxxxx")) };
1267 let lookup: S = unsafe {
1268 t(std::arch::x86_64::_mm256_shuffle_epi8(
1269 t(table),
1270 t(lossy_encoded),
1271 ))
1272 };
1273 let packed_bytes = !(chars.cmp_eq(lookup).move_mask() as u32);
1274
1275 last_i = i;
1276 unsafe {
1277 self.seq
1278 .get_unchecked_mut(idx..(idx + 4))
1279 .copy_from_slice(&packed_bytes.to_le_bytes())
1280 };
1281 idx += 4;
1282 }
1283
1284 if unaligned < last {
1286 idx -= 4;
1287 let mut val = unsafe {
1288 u32::from_le_bytes(
1289 self.seq
1290 .get_unchecked(idx..(idx + 4))
1291 .try_into()
1292 .unwrap_unchecked(),
1293 )
1294 };
1295 let keep = last - last_i;
1297 val <<= 32 - keep;
1298 val >>= 32 - keep;
1299 unsafe {
1300 self.seq
1301 .get_unchecked_mut(idx..(idx + 4))
1302 .copy_from_slice(&val.to_le_bytes())
1303 };
1304 idx += keep.div_ceil(8);
1305 }
1306 }
1307
1308 #[cfg(target_feature = "neon")]
1309 {
1310 use core::arch::aarch64::*;
1311 use core::mem::transmute;
1312
1313 last = unaligned + (len - unaligned) / 64 * 64;
1314
1315 for i in (unaligned..last).step_by(64) {
1316 unsafe {
1317 let ptr = seq.as_ptr().add(i);
1318 let chars = vld4q_u8(ptr);
1319
1320 let upper_mask = vdupq_n_u8(!(b'a' - b'A'));
1321 let chars = neon::map_8x16x4(chars, |v| vandq_u8(v, upper_mask));
1322
1323 let two_bits_mask = vdupq_n_u8(6);
1324 let lossy_encoded = neon::map_8x16x4(chars, |v| vandq_u8(v, two_bits_mask));
1325
1326 let table = transmute(*b"AxCxTxGxxxxxxxxx");
1327 let lookup = neon::map_8x16x4(lossy_encoded, |v| vqtbl1q_u8(table, v));
1328
1329 let mask = neon::map_two_8x16x4(chars, lookup, |v1, v2| vceqq_u8(v1, v2));
1330 let packed_bytes = !neon::movemask_64(mask);
1331
1332 self.seq[idx..(idx + 8)].copy_from_slice(&packed_bytes.to_le_bytes());
1333 idx += 8;
1334 self.len += 64;
1335 }
1336 }
1337 }
1338 }
1339
1340 let mut packed_byte = 0;
1341 for &base in &seq[last..] {
1342 packed_byte |= parse_base(base) << ((self.len % Self::C8) * B);
1343 self.len += 1;
1344 if self.len % Self::C8 == 0 {
1345 self.seq[idx] = packed_byte;
1346 idx += 1;
1347 packed_byte = 0;
1348 }
1349 }
1350 if self.len % Self::C8 != 0 && last < len {
1351 self.seq[idx] = packed_byte;
1352 idx += 1;
1353 }
1354 assert_eq!(idx + PADDING, self.seq.len());
1355 start..start + len
1356 }
1357
1358 #[cfg(feature = "rand")]
1359 fn random(n: usize) -> Self {
1360 use rand::{RngCore, SeedableRng};
1361
1362 let byte_len = n.div_ceil(Self::C8);
1363 let mut seq = vec![0; byte_len + PADDING];
1364 rand::rngs::SmallRng::from_os_rng().fill_bytes(&mut seq[..byte_len]);
1365 if n % Self::C8 != 0 {
1367 seq[byte_len - 1] &= (1 << (B * (n % Self::C8))) - 1;
1368 }
1369
1370 Self { seq, len: n }
1371 }
1372}
1373
1374impl PackedSeqVecBase<1> {
1375 pub fn with_len(n: usize) -> Self {
1376 Self {
1377 seq: vec![0; n.div_ceil(Self::C8) + PADDING],
1378 len: n,
1379 }
1380 }
1381
1382 pub fn random(len: usize, n_frac: f32) -> Self {
1383 let byte_len = len.div_ceil(Self::C8);
1384 let mut seq = vec![0; byte_len + PADDING];
1385
1386 assert!(
1387 (0.0..=0.3).contains(&n_frac),
1388 "n_frac={} should be in [0, 0.3]",
1389 n_frac
1390 );
1391
1392 for _ in 0..(len as f32 * n_frac) as usize {
1393 let idx = rand::random::<u64>() as usize % len;
1394 let byte = idx / Self::C8;
1395 let offset = idx % Self::C8;
1396 seq[byte] |= 1 << offset;
1397 }
1398
1399 Self { seq, len }
1400 }
1401}
1402
1403impl<'s> PackedSeqBase<'s, 1> {
1404 #[inline(always)]
1408 pub fn iter_kmer_ambiguity(self, k: usize) -> impl ExactSizeIterator<Item = bool> + use<'s> {
1409 let this = self.normalize();
1410 assert!(k > 0);
1411 assert!(k <= Self::K64);
1412 (this.offset..this.offset + this.len.saturating_sub(k - 1))
1413 .map(move |i| self.read_kmer(k, i) != 0)
1414 }
1415
1416 #[inline(always)]
1424 pub fn par_iter_kmer_ambiguity(
1425 self,
1426 k: usize,
1427 context: usize,
1428 skip: usize,
1429 ) -> PaddedIt<impl ChunkIt<S> + use<'s>> {
1430 #[cfg(target_endian = "big")]
1431 panic!("Big endian architectures are not supported.");
1432
1433 assert!(k > 0, "par_iter_kmers requires k>0, but k={k}");
1434 assert!(k <= 96, "par_iter_kmers requires k<=96, but k={k}");
1435
1436 let this = self.normalize();
1437 let o = this.offset;
1438 assert!(o < Self::C8);
1439
1440 let delay = k - 1;
1441
1442 let it = self.par_iter_bp_delayed(context, Delay(delay));
1443
1444 let mut cnt = u32x8::ZERO;
1445
1446 it.map(
1447 #[inline(always)]
1448 move |(a, r)| {
1449 cnt += a;
1450 let out = cnt.cmp_gt(S::ZERO);
1451 cnt -= r;
1452 out
1453 },
1454 )
1455 .advance(skip)
1456 }
1457
1458 #[inline(always)]
1459 pub fn par_iter_kmer_ambiguity_with_buf(
1460 self,
1461 k: usize,
1462 context: usize,
1463 skip: usize,
1464 buf: &'s mut Vec<S>,
1465 ) -> PaddedIt<impl ChunkIt<S> + use<'s>> {
1466 #[cfg(target_endian = "big")]
1467 panic!("Big endian architectures are not supported.");
1468
1469 assert!(k > 0, "par_iter_kmers requires k>0, but k={k}");
1470 assert!(k <= 96, "par_iter_kmers requires k<=96, but k={k}");
1471
1472 let this = self.normalize();
1473 let o = this.offset;
1474 assert!(o < Self::C8);
1475
1476 let delay = k - 1;
1477
1478 let it = self.par_iter_bp_delayed_with_buf(context, Delay(delay), buf);
1479
1480 let mut cnt = u32x8::ZERO;
1481
1482 it.map(
1483 #[inline(always)]
1484 move |(a, r)| {
1485 cnt += a;
1486 let out = cnt.cmp_gt(S::ZERO);
1487 cnt -= r;
1488 out
1489 },
1490 )
1491 .advance(skip)
1492 }
1493}
1494
1495#[cfg(target_feature = "neon")]
1496mod neon {
1497 use core::arch::aarch64::*;
1498
1499 #[inline(always)]
1500 pub fn movemask_64(v: uint8x16x4_t) -> u64 {
1501 unsafe {
1503 let acc = vsriq_n_u8(vsriq_n_u8(v.3, v.2, 1), vsriq_n_u8(v.1, v.0, 1), 2);
1504 vget_lane_u64(
1505 vreinterpret_u64_u8(vshrn_n_u16(
1506 vreinterpretq_u16_u8(vsriq_n_u8(acc, acc, 4)),
1507 4,
1508 )),
1509 0,
1510 )
1511 }
1512 }
1513
1514 #[inline(always)]
1515 pub fn map_8x16x4<F>(v: uint8x16x4_t, mut f: F) -> uint8x16x4_t
1516 where
1517 F: FnMut(uint8x16_t) -> uint8x16_t,
1518 {
1519 uint8x16x4_t(f(v.0), f(v.1), f(v.2), f(v.3))
1520 }
1521
1522 #[inline(always)]
1523 pub fn map_two_8x16x4<F>(v1: uint8x16x4_t, v2: uint8x16x4_t, mut f: F) -> uint8x16x4_t
1524 where
1525 F: FnMut(uint8x16_t, uint8x16_t) -> uint8x16_t,
1526 {
1527 uint8x16x4_t(f(v1.0, v2.0), f(v1.1, v2.1), f(v1.2, v2.2), f(v1.3, v2.3))
1528 }
1529}