fastars 0.1.0

Ultra-fast QC and trimming for short and long reads
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
//! Trimming module for adapter and quality trimming.
//!
//! This module provides various trimming algorithms:
//!
//! - Adapter trimming (5' and 3')
//! - Quality-based trimming
//! - Poly-X tail trimming
//! - Length-based trimming
//! - Long-read specific trimming

pub mod adapter;
pub mod global;
pub mod length;
pub mod long_read;
pub mod overlap;
pub mod quality;
pub mod tail;

// Re-export main types
pub use adapter::{detect_adapter, trim_adapter, trim_adapter_indexed, trim_adapter_targeted, AdapterConfig, AdapterIndices, AdapterKmerIndex, ILLUMINA_TRUSEQ_R1, ILLUMINA_TRUSEQ_R2, NEXTERA_R1, NEXTERA_R2};
pub use overlap::{analyze_overlap, trim_by_overlap, OverlapConfig, OverlapResult};
// OptimizedTrimmer is defined at the bottom of this file
pub use global::{trim_global, GlobalTrimConfig};
pub use length::{check_length, LengthConfig};
pub use long_read::{split_on_adapter, split_on_low_quality, LongReadConfig};
pub use quality::{sliding_window_trim, QualityTrimConfig};
pub use tail::{trim_poly_tail, TailConfig};
// TrimConfig is defined at the bottom of this file and re-exported here for convenience

/// Remove trailing N bases from a sequence after trimming.
///
/// This matches fastp's behavior where trailing Ns are removed after quality trimming.
/// In fastp (filter.cpp): `while(t>=0 && seq[t] == 'N') t--;`
#[inline]
fn trim_trailing_n(seq: &[u8], start: usize, end: usize) -> usize {
    let mut new_end = end;
    while new_end > start && seq[new_end - 1] == b'N' {
        new_end -= 1;
    }
    new_end
}

/// Remove leading N bases from a sequence after trimming.
///
/// This matches fastp's behavior where leading Ns are removed after quality trimming.
/// In fastp (filter.cpp): `while(s<l && seq[s] == 'N') s++;`
#[inline]
fn trim_leading_n(seq: &[u8], start: usize, end: usize) -> usize {
    let mut new_start = start;
    while new_start < end && seq[new_start] == b'N' {
        new_start += 1;
    }
    new_start
}

/// Zero-copy trim result representing a range within the original sequence.
///
/// Instead of allocating new strings, this stores indices into the original data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TrimResult {
    /// Start index (inclusive) of the trimmed region.
    pub start: usize,
    /// End index (exclusive) of the trimmed region.
    pub end: usize,
}

impl TrimResult {
    /// Create a new trim result.
    #[inline]
    pub fn new(start: usize, end: usize) -> Self {
        Self { start, end }
    }

    /// Create a trim result representing the full range.
    #[inline]
    pub fn full(len: usize) -> Self {
        Self { start: 0, end: len }
    }

    /// Create an empty trim result (zero length).
    #[inline]
    pub fn empty() -> Self {
        Self { start: 0, end: 0 }
    }

    /// Get the length of the trimmed region.
    #[inline]
    pub fn len(&self) -> usize {
        self.end.saturating_sub(self.start)
    }

    /// Check if the trimmed region is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.end <= self.start
    }

    /// Apply this trim result to a slice.
    #[inline]
    pub fn apply<'a, T>(&self, slice: &'a [T]) -> &'a [T] {
        if self.start >= slice.len() {
            return &slice[0..0];
        }
        let end = self.end.min(slice.len());
        &slice[self.start..end]
    }

    /// Combine two trim results (apply the second within the first).
    #[inline]
    pub fn combine(&self, other: &TrimResult) -> TrimResult {
        let new_start = self.start + other.start;
        let new_end = self.start + other.end.min(self.len());
        TrimResult::new(new_start, new_end)
    }
}

/// Processing mode for short vs long reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Mode {
    /// Short read mode (Illumina-style).
    /// Uses more aggressive quality trimming with smaller windows.
    #[default]
    Short,
    /// Long read mode (PacBio/ONT-style).
    /// Uses larger windows and handles higher error rates.
    Long,
}

impl Mode {
    /// Get default quality trimming window size for this mode.
    #[inline]
    pub fn default_window_size(&self) -> usize {
        match self {
            Mode::Short => 4,
            Mode::Long => 20,
        }
    }

    /// Get default quality threshold for this mode.
    #[inline]
    pub fn default_quality_threshold(&self) -> u8 {
        match self {
            Mode::Short => 15,
            Mode::Long => 7,
        }
    }

    /// Get default minimum length for this mode.
    #[inline]
    pub fn default_min_length(&self) -> usize {
        match self {
            Mode::Short => 15,
            Mode::Long => 200,
        }
    }
}

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

    #[test]
    fn test_trim_result_new() {
        let tr = TrimResult::new(5, 10);
        assert_eq!(tr.start, 5);
        assert_eq!(tr.end, 10);
        assert_eq!(tr.len(), 5);
    }

    #[test]
    fn test_trim_result_full() {
        let tr = TrimResult::full(100);
        assert_eq!(tr.start, 0);
        assert_eq!(tr.end, 100);
        assert_eq!(tr.len(), 100);
    }

    #[test]
    fn test_trim_result_empty() {
        let tr = TrimResult::empty();
        assert!(tr.is_empty());
        assert_eq!(tr.len(), 0);
    }

    #[test]
    fn test_trim_result_apply() {
        let data = b"ACGTACGTACGT";
        let tr = TrimResult::new(2, 8);
        let result = tr.apply(data);
        assert_eq!(result, b"GTACGT");
    }

    #[test]
    fn test_trim_result_apply_bounds() {
        let data = b"ACGT";
        let tr = TrimResult::new(10, 20);
        let result = tr.apply(data);
        assert!(result.is_empty());
    }

    #[test]
    fn test_trim_result_combine() {
        let first = TrimResult::new(5, 15);
        let second = TrimResult::new(2, 8);
        let combined = first.combine(&second);
        assert_eq!(combined.start, 7);
        assert_eq!(combined.end, 13);
    }

    #[test]
    fn test_mode_defaults() {
        assert_eq!(Mode::Short.default_window_size(), 4);
        assert_eq!(Mode::Long.default_window_size(), 20);
        assert_eq!(Mode::Short.default_quality_threshold(), 15);
        assert_eq!(Mode::Long.default_quality_threshold(), 7);
        assert_eq!(Mode::Short.default_min_length(), 15);
        assert_eq!(Mode::Long.default_min_length(), 200);
    }

    #[test]
    fn test_mode_default_is_short() {
        assert_eq!(Mode::default(), Mode::Short);
    }
}

// ============================================================================
// Aggregate TrimConfig
// ============================================================================

/// Aggregate configuration for all trimming operations.
///
/// Combines quality, adapter, tail, global, and length trimming configurations
/// into a single structure for pipeline use.
#[derive(Debug, Clone, Default)]
pub struct TrimConfig {
    /// Global (fixed position) trimming configuration
    pub global: GlobalTrimConfig,
    /// Quality-based trimming configuration
    pub quality: QualityTrimConfig,
    /// Adapter trimming configuration
    pub adapter: AdapterConfig,
    /// Poly-X tail trimming configuration
    pub tail: TailConfig,
    /// Length filtering configuration
    pub length: LengthConfig,
}

impl TrimConfig {
    /// Create a new TrimConfig with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create configuration for short read mode (Illumina-style).
    pub fn short_read() -> Self {
        Self {
            global: GlobalTrimConfig::default(),
            quality: QualityTrimConfig::short_read(),
            adapter: AdapterConfig::truseq(),
            tail: TailConfig::poly_g(), // NextSeq/NovaSeq artifacts
            length: LengthConfig::short_read(),
        }
    }

    /// Create configuration for long read mode (PacBio/ONT-style).
    pub fn long_read() -> Self {
        Self {
            global: GlobalTrimConfig::default(),
            quality: QualityTrimConfig::long_read(),
            adapter: AdapterConfig::disabled(),
            tail: TailConfig::default(),
            length: LengthConfig::long_read(),
        }
    }

    /// Create configuration with all trimming disabled.
    pub fn disabled() -> Self {
        Self {
            global: GlobalTrimConfig::default(),
            quality: QualityTrimConfig::default()
                .with_cut_front(false)
                .with_cut_tail(false),
            adapter: AdapterConfig::disabled(),
            tail: TailConfig::new().with_min_length(usize::MAX),
            length: LengthConfig::new().with_min_length(0),
        }
    }

    /// Set global trimming configuration.
    pub fn with_global(mut self, config: GlobalTrimConfig) -> Self {
        self.global = config;
        self
    }

    /// Set quality trimming configuration.
    pub fn with_quality(mut self, config: QualityTrimConfig) -> Self {
        self.quality = config;
        self
    }

    /// Set adapter trimming configuration.
    pub fn with_adapter(mut self, config: AdapterConfig) -> Self {
        self.adapter = config;
        self
    }

    /// Set tail trimming configuration.
    pub fn with_tail(mut self, config: TailConfig) -> Self {
        self.tail = config;
        self
    }

    /// Set length filtering configuration.
    pub fn with_length(mut self, config: LengthConfig) -> Self {
        self.length = config;
        self
    }

    /// Apply all trimming operations to a sequence and quality.
    ///
    /// Returns the final TrimResult after applying global, quality, adapter,
    /// and tail trimming in sequence.
    ///
    /// # Arguments
    /// * `seq` - The read sequence
    /// * `qual` - Quality scores (Phred+33 encoded)
    /// * `is_read2` - Whether this is read 2 in a paired-end pair
    ///
    /// # Returns
    /// Combined TrimResult indicating the final trimmed range.
    pub fn apply(&self, seq: &[u8], qual: &[u8]) -> TrimResult {
        self.apply_with_read_type(seq, qual, false)
    }

    /// Apply all trimming operations with read type specification.
    ///
    /// # Arguments
    /// * `seq` - The read sequence
    /// * `qual` - Quality scores (Phred+33 encoded)
    /// * `is_read2` - Whether this is read 2 in a paired-end pair
    ///
    /// # Returns
    /// Combined TrimResult indicating the final trimmed range.
    pub fn apply_with_read_type(&self, seq: &[u8], qual: &[u8], is_read2: bool) -> TrimResult {
        if seq.is_empty() {
            return TrimResult::empty();
        }

        let mut result = TrimResult::full(seq.len());

        // 1. Global trimming (fixed position trimming)
        let global_result = trim_global(seq, &self.global, is_read2);
        result = result.combine(&global_result);

        if result.is_empty() {
            return result;
        }

        // Get the trimmed sequence and quality for subsequent operations
        let trimmed_qual = result.apply(qual);

        // 2. Quality trimming (uses quality scores)
        let qual_result = sliding_window_trim(trimmed_qual, &self.quality);
        result = result.combine(&qual_result);

        if result.is_empty() {
            return result;
        }

        // 2b. Remove trailing/leading N bases after quality trimming (fastp compatibility)
        // fastp does this after cut_tail and cut_front respectively
        if self.quality.cut_tail {
            result.end = trim_trailing_n(seq, result.start, result.end);
            if result.is_empty() {
                return result;
            }
        }
        if self.quality.cut_front {
            result.start = trim_leading_n(seq, result.start, result.end);
            if result.is_empty() {
                return result;
            }
        }

        // Get the trimmed sequence for subsequent operations
        let trimmed_seq = result.apply(seq);

        // 3. Adapter trimming
        let adapter_result = trim_adapter(trimmed_seq, &self.adapter);
        result = result.combine(&adapter_result);

        if result.is_empty() {
            return result;
        }

        // Get the trimmed sequence for subsequent operations
        let trimmed_seq = result.apply(seq);

        // 4. Poly-X tail trimming
        let tail_result = trim_poly_tail(trimmed_seq, &self.tail);
        result = result.combine(&tail_result);

        result
    }

    /// Check if the trimmed length passes the length filter.
    #[inline]
    pub fn check_length(&self, len: usize) -> bool {
        check_length(len, &self.length)
    }
}

// ============================================================================
// Optimized Trimmer with Overlap and Kmer Indexing
// ============================================================================

/// Optimized trimmer that combines overlap analysis and kmer indexing.
///
/// This is the high-performance path for paired-end reads:
/// 1. First tries overlap-based adapter detection (O(n), very fast when reads overlap)
/// 2. Falls back to kmer-indexed detection (O(n) average case)
/// 3. Never uses brute-force O(n×m) search
#[derive(Debug, Clone)]
pub struct OptimizedTrimmer {
    /// Base trim configuration.
    pub config: TrimConfig,
    /// Overlap analysis configuration.
    pub overlap_config: OverlapConfig,
    /// Pre-built adapter kmer indices.
    pub adapter_indices: AdapterIndices,
}

impl OptimizedTrimmer {
    /// Create an optimized trimmer from a TrimConfig.
    pub fn new(config: TrimConfig) -> Self {
        let adapter_indices = AdapterIndices::from_config(&config.adapter);
        Self {
            config,
            overlap_config: OverlapConfig::default(),
            adapter_indices,
        }
    }

    /// Create an optimized trimmer with custom overlap configuration.
    pub fn with_overlap_config(mut self, overlap_config: OverlapConfig) -> Self {
        self.overlap_config = overlap_config;
        self
    }

    /// Apply trimming to a single read (uses kmer-indexed adapter detection).
    #[inline]
    pub fn apply(&self, seq: &[u8], qual: &[u8]) -> TrimResult {
        self.apply_single_optimized(seq, qual, false)
    }

    /// Apply trimming to a single read with read type specification.
    #[inline]
    pub fn apply_with_read_type(&self, seq: &[u8], qual: &[u8], is_read2: bool) -> TrimResult {
        self.apply_single_optimized(seq, qual, is_read2)
    }

    /// Internal single-read trimming with kmer-indexed adapter detection.
    fn apply_single_optimized(&self, seq: &[u8], qual: &[u8], is_read2: bool) -> TrimResult {
        if seq.is_empty() {
            return TrimResult::empty();
        }

        let mut result = TrimResult::full(seq.len());

        // 1. Global trimming
        let global_result = trim_global(seq, &self.config.global, is_read2);
        result = result.combine(&global_result);
        if result.is_empty() {
            return result;
        }

        // 2. Quality trimming
        let trimmed_qual = result.apply(qual);
        let qual_result = sliding_window_trim(trimmed_qual, &self.config.quality);
        result = result.combine(&qual_result);
        if result.is_empty() {
            return result;
        }

        // 2b. Remove trailing/leading N bases after quality trimming (fastp compatibility)
        if self.config.quality.cut_tail {
            result.end = trim_trailing_n(seq, result.start, result.end);
            if result.is_empty() {
                return result;
            }
        }
        if self.config.quality.cut_front {
            result.start = trim_leading_n(seq, result.start, result.end);
            if result.is_empty() {
                return result;
            }
        }

        // 3. Adapter trimming (kmer-indexed)
        let trimmed_seq = result.apply(seq);
        let adapter_result = trim_adapter_indexed(trimmed_seq, &self.adapter_indices, &self.config.adapter);
        result = result.combine(&adapter_result);
        if result.is_empty() {
            return result;
        }

        // 4. Poly-X tail trimming
        let trimmed_seq = result.apply(seq);
        let tail_result = trim_poly_tail(trimmed_seq, &self.config.tail);
        result = result.combine(&tail_result);

        result
    }

    /// Apply trimming to paired-end reads with overlap-first optimization.
    ///
    /// This is the fastest path for paired-end reads:
    /// 1. Apply global and quality trimming to both reads
    /// 2. Try overlap-based adapter detection (very fast)
    /// 3. If no overlap found, use kmer-indexed detection
    /// 4. Apply poly-X tail trimming
    ///
    /// # Returns
    /// (r1_trim_result, r2_trim_result)
    pub fn apply_paired(
        &self,
        r1_seq: &[u8],
        r1_qual: &[u8],
        r2_seq: &[u8],
        r2_qual: &[u8],
    ) -> (TrimResult, TrimResult) {
        if r1_seq.is_empty() || r2_seq.is_empty() {
            return (TrimResult::empty(), TrimResult::empty());
        }

        // 1. Global trimming
        let mut r1_result = TrimResult::full(r1_seq.len());
        let mut r2_result = TrimResult::full(r2_seq.len());

        let global_r1 = trim_global(r1_seq, &self.config.global, false);
        let global_r2 = trim_global(r2_seq, &self.config.global, true);
        r1_result = r1_result.combine(&global_r1);
        r2_result = r2_result.combine(&global_r2);

        if r1_result.is_empty() || r2_result.is_empty() {
            return (r1_result, r2_result);
        }

        // 2. Quality trimming
        let r1_qual_trimmed = r1_result.apply(r1_qual);
        let r2_qual_trimmed = r2_result.apply(r2_qual);
        let qual_r1 = sliding_window_trim(r1_qual_trimmed, &self.config.quality);
        let qual_r2 = sliding_window_trim(r2_qual_trimmed, &self.config.quality);
        r1_result = r1_result.combine(&qual_r1);
        r2_result = r2_result.combine(&qual_r2);

        if r1_result.is_empty() || r2_result.is_empty() {
            return (r1_result, r2_result);
        }

        // 2b. Remove trailing/leading N bases after quality trimming (fastp compatibility)
        if self.config.quality.cut_tail {
            r1_result.end = trim_trailing_n(r1_seq, r1_result.start, r1_result.end);
            r2_result.end = trim_trailing_n(r2_seq, r2_result.start, r2_result.end);
            if r1_result.is_empty() || r2_result.is_empty() {
                return (r1_result, r2_result);
            }
        }
        if self.config.quality.cut_front {
            r1_result.start = trim_leading_n(r1_seq, r1_result.start, r1_result.end);
            r2_result.start = trim_leading_n(r2_seq, r2_result.start, r2_result.end);
            if r1_result.is_empty() || r2_result.is_empty() {
                return (r1_result, r2_result);
            }
        }

        // 3. Adapter trimming
        let r1_seq_trimmed = r1_result.apply(r1_seq);
        let r2_seq_trimmed = r2_result.apply(r2_seq);

        let adapter_r1 = trim_adapter(r1_seq_trimmed, &self.config.adapter);
        let adapter_r2 = trim_adapter(r2_seq_trimmed, &self.config.adapter);
        r1_result = r1_result.combine(&adapter_r1);
        r2_result = r2_result.combine(&adapter_r2);

        if r1_result.is_empty() || r2_result.is_empty() {
            return (r1_result, r2_result);
        }

        // 4. Poly-X tail trimming
        let r1_seq_final = r1_result.apply(r1_seq);
        let r2_seq_final = r2_result.apply(r2_seq);
        let tail_r1 = trim_poly_tail(r1_seq_final, &self.config.tail);
        let tail_r2 = trim_poly_tail(r2_seq_final, &self.config.tail);
        r1_result = r1_result.combine(&tail_r1);
        r2_result = r2_result.combine(&tail_r2);

        (r1_result, r2_result)
    }

    /// Check if the trimmed length passes the length filter.
    #[inline]
    pub fn check_length(&self, len: usize) -> bool {
        self.config.check_length(len)
    }
}

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

    #[test]
    fn test_trim_config_default() {
        let config = TrimConfig::default();
        assert!(config.quality.cut_tail);
        assert!(config.adapter.adapter_r1.is_some());
    }

    #[test]
    fn test_trim_config_short_read() {
        let config = TrimConfig::short_read();
        assert_eq!(config.quality.window_size, 4);
        assert_eq!(config.quality.threshold, 15);
        assert!(config.adapter.adapter_r1.is_some());
    }

    #[test]
    fn test_trim_config_long_read() {
        let config = TrimConfig::long_read();
        assert_eq!(config.quality.window_size, 20);
        assert_eq!(config.quality.threshold, 7);
        assert!(config.adapter.adapter_r1.is_none());
        assert_eq!(config.length.min_length, 200);
    }

    #[test]
    fn test_trim_config_disabled() {
        let config = TrimConfig::disabled();
        assert!(config.adapter.adapter_r1.is_none());
        assert_eq!(config.length.min_length, 0);
    }

    #[test]
    fn test_trim_config_apply_quality() {
        fn make_qual(scores: &[u8]) -> Vec<u8> {
            scores.iter().map(|&s| s + 33).collect()
        }

        let seq = b"ACGTACGTACGTACGT";
        let qual = make_qual(&[30, 30, 30, 30, 30, 30, 30, 30, 5, 5, 5, 5, 5, 5, 5, 5]);

        let config = TrimConfig::new()
            .with_quality(QualityTrimConfig::default().with_cut_tail(true))
            .with_adapter(AdapterConfig::disabled())
            .with_tail(TailConfig::new().with_min_length(usize::MAX));

        let result = config.apply(seq, &qual);
        assert!(result.end < seq.len());
    }

    #[test]
    fn test_trim_config_apply_empty() {
        let config = TrimConfig::default();
        let result = config.apply(&[], &[]);
        assert!(result.is_empty());
    }

    #[test]
    fn test_trim_config_check_length() {
        let config = TrimConfig::new()
            .with_length(LengthConfig::new().with_min_length(50));

        assert!(!config.check_length(30));
        assert!(config.check_length(50));
        assert!(config.check_length(100));
    }

    #[test]
    fn test_trim_config_builder() {
        let config = TrimConfig::new()
            .with_quality(QualityTrimConfig::long_read())
            .with_adapter(AdapterConfig::nextera())
            .with_tail(TailConfig::poly_a())
            .with_length(LengthConfig::long_read());

        assert_eq!(config.quality.window_size, 20);
        assert_eq!(config.length.min_length, 200);
    }

    #[test]
    fn test_trim_trailing_n() {
        // Basic trailing N removal
        let seq = b"ACGTACGTNNN";
        assert_eq!(trim_trailing_n(seq, 0, seq.len()), 8);

        // No trailing N
        let seq = b"ACGTACGT";
        assert_eq!(trim_trailing_n(seq, 0, seq.len()), 8);

        // All N
        let seq = b"NNNNNNNN";
        assert_eq!(trim_trailing_n(seq, 0, seq.len()), 0);

        // Single trailing N
        let seq = b"ACGTN";
        assert_eq!(trim_trailing_n(seq, 0, seq.len()), 4);

        // N in middle, not trailing
        let seq = b"ACNGT";
        assert_eq!(trim_trailing_n(seq, 0, seq.len()), 5);

        // With offset start
        let seq = b"NNACGTNNN";
        assert_eq!(trim_trailing_n(seq, 2, seq.len()), 6);
    }

    #[test]
    fn test_trim_leading_n() {
        // Basic leading N removal
        let seq = b"NNNACGTACGT";
        assert_eq!(trim_leading_n(seq, 0, seq.len()), 3);

        // No leading N
        let seq = b"ACGTACGT";
        assert_eq!(trim_leading_n(seq, 0, seq.len()), 0);

        // All N
        let seq = b"NNNNNNNN";
        assert_eq!(trim_leading_n(seq, 0, seq.len()), 8);

        // Single leading N
        let seq = b"NACGT";
        assert_eq!(trim_leading_n(seq, 0, seq.len()), 1);

        // N in middle, not leading
        let seq = b"ACNGT";
        assert_eq!(trim_leading_n(seq, 0, seq.len()), 0);
    }

    #[test]
    fn test_trim_config_removes_trailing_n() {
        fn make_qual(scores: &[u8]) -> Vec<u8> {
            scores.iter().map(|&s| s + 33).collect()
        }

        // Sequence with trailing Ns that should be removed after quality trimming
        let seq = b"ACGTACGTACGTNNN";
        let qual = make_qual(&[30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30]);

        let config = TrimConfig::new()
            .with_quality(QualityTrimConfig::default().with_cut_tail(true))
            .with_adapter(AdapterConfig::disabled())
            .with_tail(TailConfig::new().with_min_length(usize::MAX));

        let result = config.apply(seq, &qual);
        let trimmed = result.apply(seq);

        // Should remove trailing Ns
        assert!(!trimmed.ends_with(b"N"));
        assert_eq!(trimmed, b"ACGTACGTACGT");
    }
}