kmerust 0.3.2

A fast, parallel k-mer counter for DNA sequences in FASTA and FASTQ files
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
//! Streaming k-mer counting for memory-efficient processing of large files.
//!
//! This module provides APIs that process FASTA and FASTQ files without loading all
//! sequences into memory simultaneously, making it suitable for very large genomic
//! datasets. File format is auto-detected from the file extension.
//!
//! # API Variants
//!
//! | Function | Parallelism | Memory | Best For |
//! |----------|-------------|--------|----------|
//! | [`count_kmers_streaming`] | Parallel | Moderate | Most use cases |
//! | [`count_kmers_sequential`] | Single-threaded | Minimal | Extreme memory constraints |
//! | [`count_kmers_from_reader`] | Single-threaded | Minimal | Stdin/custom readers |
//!
//! # Memory Model
//!
//! **Streaming API ([`count_kmers_streaming`]):**
//! - Records are batched for parallel processing
//! - Provides good speed/memory balance
//! - Memory usage: sequences + count map
//!
//! **Sequential API ([`count_kmers_sequential`]):**
//! - Processes each record immediately as read
//! - Lowest possible memory footprint
//! - Memory usage: one sequence + count map
//!
//! **Reader API ([`count_kmers_from_reader`]):**
//! - Works with any `BufRead` source including stdin
//! - Single-threaded, minimal memory
//! - Enables Unix pipeline integration
//!
//! For both APIs, the count map (one `u64` key + one `u64` value per unique k-mer)
//! dominates memory usage for most datasets.
//!
//! # Packed Bits API
//!
//! For performance-critical applications, use [`count_kmers_streaming_packed`] to get
//! results as packed 64-bit integers instead of strings. This avoids string allocation
//! overhead when you need to do further processing on the k-mer counts.

use std::{collections::HashMap, fmt::Debug, io::BufRead, path::Path};

use bytes::Bytes;
use dashmap::DashMap;
use rayon::prelude::*;
use rustc_hash::FxHasher;
use std::hash::BuildHasherDefault;

use crate::{
    error::KmeRustError,
    format::SequenceFormat,
    input::Input,
    kmer::{pack_canonical, unpack_to_string, KmerLength},
};

#[cfg(feature = "tracing")]
use tracing::{debug, info, info_span};

/// Counts k-mers in a FASTA or FASTQ file using streaming I/O.
///
/// Processes sequences one at a time without loading the entire file into memory.
/// This is more memory-efficient than [`count_kmers`](crate::run::count_kmers) for
/// very large files.
///
/// File format is auto-detected from the extension:
/// - `.fa`, `.fasta`, `.fna` (and `.gz` variants) → FASTA
/// - `.fq`, `.fastq` (and `.gz` variants) → FASTQ
///
/// # Arguments
///
/// * `path` - Path to the FASTA/FASTQ file
/// * `k` - K-mer length (must be 1-32)
///
/// # Returns
///
/// A `HashMap` mapping k-mer strings to their counts.
///
/// # Errors
///
/// Returns an error if:
/// - `k` is outside the valid range (1-32)
/// - The file cannot be read or parsed
///
/// # Example
///
/// ```rust,no_run
/// use kmerust::streaming::count_kmers_streaming;
///
/// // Works with both FASTA and FASTQ
/// let counts = count_kmers_streaming("large_genome.fa", 21)?;
/// let counts = count_kmers_streaming("reads.fq.gz", 21)?;
/// println!("Found {} unique k-mers", counts.len());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn count_kmers_streaming<P>(path: P, k: usize) -> Result<HashMap<String, u64>, KmeRustError>
where
    P: AsRef<Path> + Debug,
{
    #[cfg(feature = "tracing")]
    info!(k = k, path = ?path, "Starting streaming k-mer counting");

    let k_len = KmerLength::new(k)?;
    let packed = count_kmers_streaming_packed(&path, k_len)?;

    #[cfg(feature = "tracing")]
    let _unpack_span = info_span!("unpack_kmers", count = packed.len()).entered();

    let result: HashMap<String, u64> = packed
        .into_par_iter()
        .map(|(bits, count)| (unpack_to_string(bits, k_len), count))
        .collect();

    #[cfg(feature = "tracing")]
    info!(
        unique_kmers = result.len(),
        "Streaming k-mer counting complete"
    );

    Ok(result)
}

/// Counts k-mers and returns packed 64-bit representations.
///
/// This is the most efficient API for k-mer counting when you need to do
/// further processing on the results. It avoids string allocation entirely.
///
/// File format is auto-detected from the extension:
/// - `.fa`, `.fasta`, `.fna` (and `.gz` variants) → FASTA
/// - `.fq`, `.fastq` (and `.gz` variants) → FASTQ
///
/// # Arguments
///
/// * `path` - Path to the FASTA/FASTQ file
/// * `k` - Validated k-mer length
///
/// # Returns
///
/// A `HashMap` mapping packed k-mer bits to their counts.
///
/// # Example
///
/// ```rust,no_run
/// use kmerust::streaming::count_kmers_streaming_packed;
/// use kmerust::kmer::KmerLength;
///
/// let k = KmerLength::new(21)?;
/// let counts = count_kmers_streaming_packed("genome.fa", k)?;
/// let counts = count_kmers_streaming_packed("reads.fq.gz", k)?;
///
/// // Process packed bits directly without string conversion
/// for (packed_bits, count) in counts {
///     if count >= 10 {
///         println!("K-mer {packed_bits:#x} appears {count} times");
///     }
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn count_kmers_streaming_packed<P>(
    path: P,
    k: KmerLength,
) -> Result<HashMap<u64, u64>, KmeRustError>
where
    P: AsRef<Path> + Debug,
{
    let counter = StreamingKmerCounter::new();
    counter.count_file(path, k)
}

/// Counts k-mers from an in-memory byte slice.
///
/// Useful for testing or when sequence data is already in memory.
///
/// # Arguments
///
/// * `sequences` - Iterator of sequence byte slices
/// * `k` - Validated k-mer length
///
/// # Returns
///
/// A `HashMap` mapping packed k-mer bits to their counts.
///
/// # Example
///
/// ```rust
/// use kmerust::streaming::count_kmers_from_sequences;
/// use kmerust::kmer::KmerLength;
/// use bytes::Bytes;
///
/// let sequences = vec![
///     Bytes::from_static(b"ACGTACGT"),
///     Bytes::from_static(b"TGCATGCA"),
/// ];
///
/// let k = KmerLength::new(4)?;
/// let counts = count_kmers_from_sequences(sequences.into_iter(), k);
/// # Ok::<(), kmerust::error::KmerLengthError>(())
/// ```
pub fn count_kmers_from_sequences<I>(sequences: I, k: KmerLength) -> HashMap<u64, u64>
where
    I: Iterator<Item = Bytes>,
{
    let counter = StreamingKmerCounter::new();
    counter.count_sequences(sequences, k)
}

/// Counts k-mers with true sequential processing for minimum memory usage.
///
/// Unlike [`count_kmers_streaming`] which batches sequences for parallel processing,
/// this function processes each sequence immediately as it's read from disk.
/// This provides the lowest possible peak memory usage at the cost of being
/// single-threaded.
///
/// File format is auto-detected from the extension:
/// - `.fa`, `.fasta`, `.fna` (and `.gz` variants) → FASTA
/// - `.fq`, `.fastq` (and `.gz` variants) → FASTQ
///
/// # When to Use
///
/// Use this function when:
/// - Memory is extremely constrained
/// - The file is very large relative to available RAM
/// - You're processing files where individual sequences are very long
///
/// For most use cases, [`count_kmers_streaming`] provides a better balance of
/// speed and memory efficiency.
///
/// # Arguments
///
/// * `path` - Path to the FASTA/FASTQ file
/// * `k` - K-mer length (must be 1-32)
///
/// # Returns
///
/// A `HashMap` mapping packed k-mer bits to their counts.
///
/// # Errors
///
/// Returns an error if:
/// - `k` is outside the valid range (1-32)
/// - The file cannot be read or parsed
///
/// # Example
///
/// ```rust,no_run
/// use kmerust::streaming::count_kmers_sequential;
///
/// let counts = count_kmers_sequential("huge_genome.fa", 21)?;
/// let counts = count_kmers_sequential("reads.fq.gz", 21)?;
/// println!("Found {} unique k-mers", counts.len());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn count_kmers_sequential<P>(path: P, k: usize) -> Result<HashMap<u64, u64>, KmeRustError>
where
    P: AsRef<Path> + Debug,
{
    let k_len = KmerLength::new(k)?;
    let counter = SequentialKmerCounter::new();
    counter.count_file(path, k_len)
}

/// Counts k-mers from standard input.
///
/// Reads FASTA-formatted sequences from stdin and counts k-mers.
/// This enables Unix pipeline integration:
///
/// ```bash
/// cat genome.fa | krust 21
/// zcat large.fa.gz | krust 21 > counts.tsv
/// seqtk sample reads.fq 0.1 | krust 17
/// ```
///
/// # Arguments
///
/// * `k` - K-mer length (must be 1-32)
///
/// # Returns
///
/// A `HashMap` mapping k-mer strings to their counts.
///
/// # Errors
///
/// Returns an error if:
/// - `k` is outside the valid range (1-32)
/// - The input cannot be parsed as FASTA
///
/// # Example
///
/// ```rust,no_run
/// use kmerust::streaming::count_kmers_stdin;
///
/// let counts = count_kmers_stdin(21)?;
/// println!("Found {} unique k-mers", counts.len());
/// # Ok::<(), kmerust::error::KmeRustError>(())
/// ```
pub fn count_kmers_stdin(k: usize) -> Result<HashMap<String, u64>, KmeRustError> {
    count_kmers_stdin_with_format(k, SequenceFormat::Auto)
}

/// Counts k-mers from standard input with explicit format specification.
///
/// # Arguments
///
/// * `k` - K-mer length (must be 1-32)
/// * `format` - Input format (Auto defaults to FASTA for stdin)
///
/// # Returns
///
/// A `HashMap` mapping k-mer strings to their counts.
///
/// # Errors
///
/// Returns an error if:
/// - `k` is outside the valid range (1-32)
/// - The input cannot be parsed
pub fn count_kmers_stdin_with_format(
    k: usize,
    format: SequenceFormat,
) -> Result<HashMap<String, u64>, KmeRustError> {
    let k_len = KmerLength::new(k)?;
    // For stdin, resolve format with None path (defaults to FASTA if Auto)
    let resolved_format = format.resolve(None);
    let packed = {
        let stdin = std::io::stdin();
        let reader = stdin.lock();
        count_kmers_from_reader_impl_with_format(reader, k_len, resolved_format)?
    };

    Ok(packed
        .into_iter()
        .map(|(bits, count)| (unpack_to_string(bits, k_len), count))
        .collect())
}

/// Counts k-mers from standard input, returning packed bit representations.
///
/// This is the most efficient stdin API, avoiding string allocation.
///
/// # Arguments
///
/// * `k` - Validated k-mer length
///
/// # Returns
///
/// A `HashMap` mapping packed k-mer bits to their counts.
///
/// # Errors
///
/// Returns an error if the input cannot be parsed as FASTA.
pub fn count_kmers_stdin_packed(k: KmerLength) -> Result<HashMap<u64, u64>, KmeRustError> {
    let stdin = std::io::stdin();
    let reader = stdin.lock();
    count_kmers_from_reader_impl(reader, k)
}

/// Counts k-mers from any buffered reader.
///
/// This is the most flexible API, allowing k-mer counting from any source
/// that implements `BufRead`, including files, stdin, network streams, or
/// in-memory buffers.
///
/// # Arguments
///
/// * `reader` - Any type implementing `BufRead`
/// * `k` - K-mer length (must be 1-32)
///
/// # Returns
///
/// A `HashMap` mapping k-mer strings to their counts.
///
/// # Errors
///
/// Returns an error if:
/// - `k` is outside the valid range (1-32)
/// - The input cannot be parsed as FASTA
///
/// # Example
///
/// ```rust
/// use kmerust::streaming::count_kmers_from_reader;
/// use std::io::BufReader;
///
/// let fasta_data = b">seq1\nACGTACGT\n>seq2\nTGCATGCA\n";
/// let reader = BufReader::new(&fasta_data[..]);
/// let counts = count_kmers_from_reader(reader, 4)?;
/// assert!(!counts.is_empty());
/// # Ok::<(), kmerust::error::KmeRustError>(())
/// ```
pub fn count_kmers_from_reader<R>(reader: R, k: usize) -> Result<HashMap<String, u64>, KmeRustError>
where
    R: BufRead,
{
    let k_len = KmerLength::new(k)?;
    let packed = count_kmers_from_reader_impl(reader, k_len)?;

    Ok(packed
        .into_iter()
        .map(|(bits, count)| (unpack_to_string(bits, k_len), count))
        .collect())
}

/// Counts k-mers from any buffered reader, returning packed bit representations.
///
/// This is the most efficient reader API, avoiding string allocation.
///
/// # Arguments
///
/// * `reader` - Any type implementing `BufRead`
/// * `k` - Validated k-mer length
///
/// # Returns
///
/// A `HashMap` mapping packed k-mer bits to their counts.
///
/// # Errors
///
/// Returns an error if the input cannot be parsed as FASTA.
///
/// # Example
///
/// ```rust
/// use kmerust::streaming::count_kmers_from_reader_packed;
/// use kmerust::kmer::KmerLength;
/// use std::io::BufReader;
///
/// let fasta_data = b">seq1\nACGTACGT\n>seq2\nTGCATGCA\n";
/// let reader = BufReader::new(&fasta_data[..]);
/// let k = KmerLength::new(4)?;
/// let counts = count_kmers_from_reader_packed(reader, k)?;
/// assert!(!counts.is_empty());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn count_kmers_from_reader_packed<R>(
    reader: R,
    k: KmerLength,
) -> Result<HashMap<u64, u64>, KmeRustError>
where
    R: BufRead,
{
    count_kmers_from_reader_impl(reader, k)
}

/// Counts k-mers from an [`Input`] source (file or stdin).
///
/// This is the main entry point for input-agnostic k-mer counting.
///
/// # Arguments
///
/// * `input` - The input source (file path or stdin)
/// * `k` - K-mer length (must be 1-32)
///
/// # Returns
///
/// A `HashMap` mapping k-mer strings to their counts.
///
/// # Errors
///
/// Returns an error if:
/// - `k` is outside the valid range (1-32)
/// - The input cannot be read or parsed
///
/// # Example
///
/// ```rust,no_run
/// use kmerust::streaming::count_kmers_from_input;
/// use kmerust::input::Input;
/// use std::path::Path;
///
/// // From file
/// let input = Input::from_path(Path::new("genome.fa"));
/// let counts = count_kmers_from_input(&input, 21)?;
///
/// // From stdin (would read from actual stdin)
/// let input = Input::Stdin;
/// // let counts = count_kmers_from_input(&input, 21)?;
/// # Ok::<(), kmerust::error::KmeRustError>(())
/// ```
pub fn count_kmers_from_input(
    input: &Input,
    k: usize,
) -> Result<HashMap<String, u64>, KmeRustError> {
    match input {
        Input::File(path) => count_kmers_streaming(path, k),
        Input::Stdin => count_kmers_stdin(k),
    }
}

/// Counts k-mers from an [`Input`] source, returning packed bit representations.
///
/// # Arguments
///
/// * `input` - The input source (file path or stdin)
/// * `k` - Validated k-mer length
///
/// # Returns
///
/// A `HashMap` mapping packed k-mer bits to their counts.
///
/// # Errors
///
/// Returns an error if the input cannot be read or parsed.
pub fn count_kmers_from_input_packed(
    input: &Input,
    k: KmerLength,
) -> Result<HashMap<u64, u64>, KmeRustError> {
    match input {
        Input::File(path) => count_kmers_streaming_packed(path, k),
        Input::Stdin => count_kmers_stdin_packed(k),
    }
}

/// Internal implementation for counting k-mers from a reader.
#[cfg(not(feature = "needletail"))]
fn count_kmers_from_reader_impl<R>(
    reader: R,
    k: KmerLength,
) -> Result<HashMap<u64, u64>, KmeRustError>
where
    R: BufRead,
{
    count_kmers_from_reader_impl_with_format(reader, k, SequenceFormat::Fasta)
}

/// Internal implementation for counting k-mers from a reader with format.
#[cfg(not(feature = "needletail"))]
fn count_kmers_from_reader_impl_with_format<R>(
    reader: R,
    k: KmerLength,
    format: SequenceFormat,
) -> Result<HashMap<u64, u64>, KmeRustError>
where
    R: BufRead,
{
    use bio::io::{fasta, fastq};

    let mut counts: HashMap<u64, u64, BuildHasherDefault<FxHasher>> =
        HashMap::with_hasher(BuildHasherDefault::default());

    match format {
        SequenceFormat::Fastq => {
            let fastq_reader = fastq::Reader::new(reader);
            for result in fastq_reader.records() {
                let record = result.map_err(|e| KmeRustError::SequenceParse {
                    details: e.to_string(),
                })?;
                process_sequence_into_counts(&mut counts, record.seq(), None, k, None);
            }
        }
        SequenceFormat::Fasta | SequenceFormat::Auto => {
            let fasta_reader = fasta::Reader::new(reader);
            for result in fasta_reader.records() {
                let record = result.map_err(|e| KmeRustError::SequenceParse {
                    details: e.to_string(),
                })?;
                process_sequence_into_counts(&mut counts, record.seq(), None, k, None);
            }
        }
    }

    Ok(counts.into_iter().collect())
}

/// Internal implementation for counting k-mers from a reader (needletail version).
///
/// Note: needletail requires the reader to be `Send`, so we read into a buffer first.
#[cfg(feature = "needletail")]
fn count_kmers_from_reader_impl<R>(
    reader: R,
    k: KmerLength,
) -> Result<HashMap<u64, u64>, KmeRustError>
where
    R: BufRead,
{
    // needletail auto-detects format, so we can ignore the format parameter
    count_kmers_from_reader_impl_with_format(reader, k, SequenceFormat::Auto)
}

/// Internal implementation for counting k-mers from a reader with format (needletail version).
///
/// Note: needletail requires the reader to be `Send`, so we read into a buffer first.
/// needletail auto-detects FASTA/FASTQ format, so the format parameter is informational.
#[cfg(feature = "needletail")]
fn count_kmers_from_reader_impl_with_format<R>(
    mut reader: R,
    k: KmerLength,
    _format: SequenceFormat,
) -> Result<HashMap<u64, u64>, KmeRustError>
where
    R: BufRead,
{
    use std::io::Cursor;

    // Read all data into a buffer since needletail requires Send
    let mut buffer = Vec::new();
    reader
        .read_to_end(&mut buffer)
        .map_err(|e| KmeRustError::SequenceParse {
            details: format!("failed to read input: {e}"),
        })?;

    let mut parser = needletail::parse_fastx_reader(Cursor::new(buffer)).map_err(|e| {
        KmeRustError::SequenceParse {
            details: e.to_string(),
        }
    })?;
    let mut counts: HashMap<u64, u64, BuildHasherDefault<FxHasher>> =
        HashMap::with_hasher(BuildHasherDefault::default());

    while let Some(result) = parser.next() {
        let record = result.map_err(|e| KmeRustError::SequenceParse {
            details: e.to_string(),
        })?;
        process_sequence_into_counts(&mut counts, &record.seq(), None, k, None);
    }

    Ok(counts.into_iter().collect())
}

/// Process a sequence and add k-mer counts to the map.
///
/// If quality scores are provided along with a minimum quality threshold,
/// k-mers containing bases with quality below the threshold are skipped.
fn process_sequence_into_counts(
    counts: &mut HashMap<u64, u64, BuildHasherDefault<FxHasher>>,
    seq: &[u8],
    qual: Option<&[u8]>,
    k: KmerLength,
    min_quality: Option<u8>,
) {
    let k_val = k.get();
    if seq.len() < k_val {
        return;
    }

    // Pre-compute quality threshold as ASCII value (Phred+33)
    let quality_threshold = min_quality.map(|q| q.saturating_add(33));

    let mut i = 0;
    while i <= seq.len() - k_val {
        // Check quality if filtering is enabled
        if let (Some(q), Some(threshold)) = (qual, quality_threshold) {
            if let Some(bad_pos) = q[i..i + k_val].iter().position(|&qv| qv < threshold) {
                i += bad_pos + 1; // Skip past low-quality base
                continue;
            }
        }

        match pack_canonical(&seq[i..i + k_val]) {
            Ok(canonical_bits) => {
                *counts.entry(canonical_bits).or_insert(0) += 1;
                i += 1;
            }
            Err(err) => {
                i += err.position + 1;
            }
        }
    }
}

/// A truly sequential k-mer counter with minimal memory footprint.
///
/// Processes sequences one at a time as they're read, without batching.
struct SequentialKmerCounter {
    counts: HashMap<u64, u64, BuildHasherDefault<FxHasher>>,
}

impl SequentialKmerCounter {
    fn new() -> Self {
        Self {
            counts: HashMap::with_hasher(BuildHasherDefault::<FxHasher>::default()),
        }
    }

    #[cfg(not(feature = "needletail"))]
    fn count_file<P>(mut self, path: P, k: KmerLength) -> Result<HashMap<u64, u64>, KmeRustError>
    where
        P: AsRef<Path> + Debug,
    {
        use bio::io::{fasta, fastq};

        let path_ref = path.as_ref();
        let format = SequenceFormat::from_extension(path_ref);

        #[cfg(feature = "tracing")]
        let _span = info_span!("sequential_count", path = ?path_ref, ?format).entered();

        // Handle gzip if the feature is enabled
        #[cfg(feature = "gzip")]
        let is_gzip = path_ref.extension().map(|ext| ext == "gz").unwrap_or(false);

        #[cfg(feature = "gzip")]
        if is_gzip {
            use flate2::read::GzDecoder;
            use std::{fs::File, io::BufReader};

            let file = File::open(path_ref).map_err(|e| KmeRustError::SequenceRead {
                source: e,
                path: path_ref.to_path_buf(),
            })?;
            let decoder = GzDecoder::new(file);
            let buf_reader = BufReader::new(decoder);

            match format {
                SequenceFormat::Fastq => {
                    let reader = fastq::Reader::new(buf_reader);
                    for result in reader.records() {
                        let record = result.map_err(|e| KmeRustError::SequenceParse {
                            details: e.to_string(),
                        })?;
                        self.process_sequence(record.seq(), None, k, None);
                    }
                }
                SequenceFormat::Fasta | SequenceFormat::Auto => {
                    let reader = fasta::Reader::new(buf_reader);
                    for result in reader.records() {
                        let record = result.map_err(|e| KmeRustError::SequenceParse {
                            details: e.to_string(),
                        })?;
                        self.process_sequence(record.seq(), None, k, None);
                    }
                }
            }

            return Ok(self.counts.into_iter().collect());
        }

        // Non-gzip path
        match format {
            SequenceFormat::Fastq => {
                let reader =
                    fastq::Reader::from_file(path_ref).map_err(|e| KmeRustError::SequenceRead {
                        source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
                        path: path_ref.to_path_buf(),
                    })?;

                for result in reader.records() {
                    let record = result.map_err(|e| KmeRustError::SequenceParse {
                        details: e.to_string(),
                    })?;
                    self.process_sequence(record.seq(), None, k, None);
                }
            }
            SequenceFormat::Fasta | SequenceFormat::Auto => {
                let reader =
                    fasta::Reader::from_file(path_ref).map_err(|e| KmeRustError::SequenceRead {
                        source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
                        path: path_ref.to_path_buf(),
                    })?;

                for result in reader.records() {
                    let record = result.map_err(|e| KmeRustError::SequenceParse {
                        details: e.to_string(),
                    })?;
                    self.process_sequence(record.seq(), None, k, None);
                }
            }
        }

        Ok(self.counts.into_iter().collect())
    }

    #[cfg(feature = "needletail")]
    fn count_file<P>(mut self, path: P, k: KmerLength) -> Result<HashMap<u64, u64>, KmeRustError>
    where
        P: AsRef<Path> + Debug,
    {
        let path_ref = path.as_ref();

        #[cfg(feature = "tracing")]
        let _span = info_span!("sequential_count", path = ?path_ref).entered();

        let mut reader =
            needletail::parse_fastx_file(path_ref).map_err(|e| KmeRustError::SequenceRead {
                source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
                path: path_ref.to_path_buf(),
            })?;

        // Process each record immediately as it's read - no batching
        while let Some(result) = reader.next() {
            let record = result.map_err(|e| KmeRustError::SequenceParse {
                details: e.to_string(),
            })?;
            self.process_sequence(&record.seq(), None, k, None);
        }

        Ok(self.counts.into_iter().collect())
    }

    fn process_sequence(
        &mut self,
        seq: &[u8],
        qual: Option<&[u8]>,
        k: KmerLength,
        min_quality: Option<u8>,
    ) {
        let k_val = k.get();
        if seq.len() < k_val {
            return;
        }

        // Pre-compute quality threshold as ASCII value (Phred+33)
        let quality_threshold = min_quality.map(|q| q.saturating_add(33));

        let mut i = 0;
        while i <= seq.len() - k_val {
            // Check quality if filtering is enabled
            if let (Some(q), Some(threshold)) = (qual, quality_threshold) {
                if let Some(bad_pos) = q[i..i + k_val].iter().position(|&qv| qv < threshold) {
                    i += bad_pos + 1; // Skip past low-quality base
                    continue;
                }
            }

            match pack_canonical(&seq[i..i + k_val]) {
                Ok(canonical_bits) => {
                    *self.counts.entry(canonical_bits).or_insert(0) += 1;
                    i += 1;
                }
                Err(err) => {
                    i += err.position + 1;
                }
            }
        }
    }
}

/// A streaming k-mer counter that processes sequences one at a time.
struct StreamingKmerCounter {
    counts: DashMap<u64, u64, BuildHasherDefault<FxHasher>>,
}

impl StreamingKmerCounter {
    fn new() -> Self {
        Self {
            counts: DashMap::with_hasher(BuildHasherDefault::<FxHasher>::default()),
        }
    }

    #[cfg(all(not(feature = "needletail"), not(feature = "gzip")))]
    fn count_file<P>(self, path: P, k: KmerLength) -> Result<HashMap<u64, u64>, KmeRustError>
    where
        P: AsRef<Path> + Debug,
    {
        use bio::io::{fasta, fastq};

        let path_ref = path.as_ref();
        let format = SequenceFormat::from_extension(path_ref);

        #[cfg(feature = "tracing")]
        let read_span = info_span!("read_sequences", path = ?path_ref, ?format).entered();

        // Read sequences into a Vec for parallel processing
        let sequences: Vec<Bytes> = match format {
            SequenceFormat::Fastq => {
                let reader =
                    fastq::Reader::from_file(path_ref).map_err(|e| KmeRustError::SequenceRead {
                        source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
                        path: path_ref.to_path_buf(),
                    })?;
                reader
                    .records()
                    .map(|r| {
                        r.map(|rec| Bytes::copy_from_slice(rec.seq())).map_err(|e| {
                            KmeRustError::SequenceParse {
                                details: e.to_string(),
                            }
                        })
                    })
                    .collect::<Result<Vec<_>, _>>()?
            }
            SequenceFormat::Fasta | SequenceFormat::Auto => {
                let reader =
                    fasta::Reader::from_file(path_ref).map_err(|e| KmeRustError::SequenceRead {
                        source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
                        path: path_ref.to_path_buf(),
                    })?;
                reader
                    .records()
                    .map(|r| {
                        r.map(|rec| Bytes::copy_from_slice(rec.seq())).map_err(|e| {
                            KmeRustError::SequenceParse {
                                details: e.to_string(),
                            }
                        })
                    })
                    .collect::<Result<Vec<_>, _>>()?
            }
        };

        #[cfg(feature = "tracing")]
        {
            drop(read_span);
            debug!(sequences = sequences.len(), "Read sequences from file");
        }

        #[cfg(feature = "tracing")]
        let process_span = info_span!("process_sequences", count = sequences.len()).entered();

        sequences.par_iter().for_each(|seq| {
            self.process_sequence(seq, None, k, None);
        });

        Ok(self.counts.into_iter().collect())
    }

    #[cfg(all(not(feature = "needletail"), feature = "gzip"))]
    fn count_file<P>(self, path: P, k: KmerLength) -> Result<HashMap<u64, u64>, KmeRustError>
    where
        P: AsRef<Path> + Debug,
    {
        use bio::io::{fasta, fastq};
        use flate2::read::GzDecoder;
        use std::{fs::File, io::BufReader};

        let path_ref = path.as_ref();
        let format = SequenceFormat::from_extension(path_ref);
        let is_gzip = path_ref.extension().map(|ext| ext == "gz").unwrap_or(false);

        #[cfg(feature = "tracing")]
        let read_span = info_span!("read_sequences", path = ?path_ref, ?format).entered();

        // Read sequences into a Vec for parallel processing
        let sequences: Vec<Bytes> = match (format, is_gzip) {
            (SequenceFormat::Fastq, true) => {
                let file = File::open(path_ref).map_err(|e| KmeRustError::SequenceRead {
                    source: e,
                    path: path_ref.to_path_buf(),
                })?;
                let decoder = GzDecoder::new(file);
                let reader = fastq::Reader::new(BufReader::new(decoder));
                reader
                    .records()
                    .map(|r| {
                        r.map(|rec| Bytes::copy_from_slice(rec.seq())).map_err(|e| {
                            KmeRustError::SequenceParse {
                                details: e.to_string(),
                            }
                        })
                    })
                    .collect::<Result<Vec<_>, _>>()?
            }
            (SequenceFormat::Fastq, false) => {
                let reader =
                    fastq::Reader::from_file(path_ref).map_err(|e| KmeRustError::SequenceRead {
                        source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
                        path: path_ref.to_path_buf(),
                    })?;
                reader
                    .records()
                    .map(|r| {
                        r.map(|rec| Bytes::copy_from_slice(rec.seq())).map_err(|e| {
                            KmeRustError::SequenceParse {
                                details: e.to_string(),
                            }
                        })
                    })
                    .collect::<Result<Vec<_>, _>>()?
            }
            (SequenceFormat::Fasta | SequenceFormat::Auto, true) => {
                let file = File::open(path_ref).map_err(|e| KmeRustError::SequenceRead {
                    source: e,
                    path: path_ref.to_path_buf(),
                })?;
                let decoder = GzDecoder::new(file);
                let reader = fasta::Reader::new(BufReader::new(decoder));
                reader
                    .records()
                    .map(|r| {
                        r.map(|rec| Bytes::copy_from_slice(rec.seq())).map_err(|e| {
                            KmeRustError::SequenceParse {
                                details: e.to_string(),
                            }
                        })
                    })
                    .collect::<Result<Vec<_>, _>>()?
            }
            (SequenceFormat::Fasta | SequenceFormat::Auto, false) => {
                let reader =
                    fasta::Reader::from_file(path_ref).map_err(|e| KmeRustError::SequenceRead {
                        source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
                        path: path_ref.to_path_buf(),
                    })?;
                reader
                    .records()
                    .map(|r| {
                        r.map(|rec| Bytes::copy_from_slice(rec.seq())).map_err(|e| {
                            KmeRustError::SequenceParse {
                                details: e.to_string(),
                            }
                        })
                    })
                    .collect::<Result<Vec<_>, _>>()?
            }
        };

        #[cfg(feature = "tracing")]
        {
            drop(read_span);
            debug!(sequences = sequences.len(), "Read sequences from file");
        }

        #[cfg(feature = "tracing")]
        let process_span = info_span!("process_sequences", count = sequences.len()).entered();

        sequences.par_iter().for_each(|seq| {
            self.process_sequence(seq, None, k, None);
        });

        Ok(self.counts.into_iter().collect())
    }

    #[cfg(feature = "needletail")]
    fn count_file<P>(self, path: P, k: KmerLength) -> Result<HashMap<u64, u64>, KmeRustError>
    where
        P: AsRef<Path> + Debug,
    {
        let path_ref = path.as_ref();

        #[cfg(feature = "tracing")]
        let read_span = info_span!("read_fasta", path = ?path_ref).entered();

        let mut reader =
            needletail::parse_fastx_file(path_ref).map_err(|e| KmeRustError::SequenceRead {
                source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
                path: path_ref.to_path_buf(),
            })?;

        // Collect sequences for parallel processing
        let mut sequences = Vec::new();
        while let Some(record) = reader.next() {
            let record = record.map_err(|e| KmeRustError::SequenceParse {
                details: e.to_string(),
            })?;
            sequences.push(Bytes::copy_from_slice(&record.seq()));
        }

        #[cfg(feature = "tracing")]
        {
            drop(read_span);
            debug!(sequences = sequences.len(), "Read sequences from file");
        }

        #[cfg(feature = "tracing")]
        let _process_span = info_span!("process_sequences", count = sequences.len()).entered();

        sequences.par_iter().for_each(|seq| {
            self.process_sequence(seq, None, k, None);
        });

        Ok(self.counts.into_iter().collect())
    }

    fn count_sequences<I>(self, sequences: I, k: KmerLength) -> HashMap<u64, u64>
    where
        I: Iterator<Item = Bytes>,
    {
        for seq in sequences {
            self.process_sequence(&seq, None, k, None);
        }
        self.counts.into_iter().collect()
    }

    fn process_sequence(
        &self,
        seq: &Bytes,
        qual: Option<&[u8]>,
        k: KmerLength,
        min_quality: Option<u8>,
    ) {
        let k_val = k.get();
        if seq.len() < k_val {
            return;
        }

        // Pre-compute quality threshold as ASCII value (Phred+33)
        let quality_threshold = min_quality.map(|q| q.saturating_add(33));

        let mut i = 0;
        while i <= seq.len() - k_val {
            // Check quality if filtering is enabled
            if let (Some(q), Some(threshold)) = (qual, quality_threshold) {
                if let Some(bad_pos) = q[i..i + k_val].iter().position(|&qv| qv < threshold) {
                    i += bad_pos + 1; // Skip past low-quality base
                    continue;
                }
            }

            match pack_canonical(&seq[i..i + k_val]) {
                Ok(canonical_bits) => {
                    self.counts
                        .entry(canonical_bits)
                        .and_modify(|c| *c = c.saturating_add(1))
                        .or_insert(1);
                    i += 1;
                }
                Err(err) => {
                    i += err.position + 1;
                }
            }
        }
    }
}

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

    #[test]
    fn count_from_sequences_basic() {
        let sequences = vec![Bytes::from_static(b"ACGTACGT")];
        let k = KmerLength::new(4).unwrap();
        let counts = count_kmers_from_sequences(sequences.into_iter(), k);

        // ACGT, CGTA, GTAC, TACG, ACGT
        // Canonical forms: ACGT (palindrome), CGTA<->TACG (CGTA smaller), GTAC (palindrome)
        // ACGT appears twice (positions 0 and 4)
        assert!(!counts.is_empty());
    }

    #[test]
    fn count_from_sequences_empty() {
        let sequences: Vec<Bytes> = vec![];
        let k = KmerLength::new(4).unwrap();
        let counts = count_kmers_from_sequences(sequences.into_iter(), k);
        assert!(counts.is_empty());
    }

    #[test]
    fn count_from_sequences_short_sequence() {
        let sequences = vec![Bytes::from_static(b"ACG")];
        let k = KmerLength::new(4).unwrap();
        let counts = count_kmers_from_sequences(sequences.into_iter(), k);
        assert!(counts.is_empty());
    }

    #[test]
    fn count_from_sequences_multiple() {
        let sequences = vec![
            Bytes::from_static(b"AAAA"),
            Bytes::from_static(b"TTTT"), // RC of AAAA
        ];
        let k = KmerLength::new(4).unwrap();
        let counts = count_kmers_from_sequences(sequences.into_iter(), k);

        // AAAA and TTTT should map to same canonical (AAAA)
        assert_eq!(counts.len(), 1);
        let count = counts.values().next().unwrap();
        assert_eq!(*count, 2);
    }

    #[test]
    fn quality_filtering_skips_low_quality_kmers() {
        let mut counts: HashMap<u64, u64, BuildHasherDefault<FxHasher>> =
            HashMap::with_hasher(BuildHasherDefault::default());

        // Sequence: ACGTACGT
        // Quality: IIII!!!! (I=40, !=0 in Phred+33)
        // With min_quality=20, k-mers starting at positions 0,1,2,3 should pass (all high quality)
        // But positions 4+ have low quality bases in the window
        let seq = b"ACGTACGT";
        let qual = b"IIII!!!!"; // I = ASCII 73 = Phred 40, ! = ASCII 33 = Phred 0
        let k = KmerLength::new(4).unwrap();
        let min_quality = Some(20u8);

        process_sequence_into_counts(&mut counts, seq, Some(qual), k, min_quality);

        // Only k-mers from positions 0 (ACGT) should be counted
        // Position 0: ACGT (qual IIII) - passes
        // Position 1: CGTA (qual III!) - fails (! < 20)
        // Position 2: GTAC (qual II!!) - fails
        // Position 3: TACG (qual I!!!) - fails
        // Position 4: ACGT (qual !!!!) - fails
        assert_eq!(counts.len(), 1);
        let count = counts.values().next().unwrap();
        assert_eq!(*count, 1);
    }

    #[test]
    fn quality_filtering_with_no_threshold_counts_all() {
        let mut counts: HashMap<u64, u64, BuildHasherDefault<FxHasher>> =
            HashMap::with_hasher(BuildHasherDefault::default());

        let seq = b"ACGTACGT";
        let qual = b"IIII!!!!";
        let k = KmerLength::new(4).unwrap();

        // No quality threshold - all k-mers should be counted
        process_sequence_into_counts(&mut counts, seq, Some(qual), k, None);

        // Without quality filtering, we get all k-mers
        // ACGT appears twice (positions 0 and 4)
        assert!(!counts.is_empty());
    }

    #[test]
    fn quality_filtering_with_zero_threshold_counts_all() {
        let mut counts: HashMap<u64, u64, BuildHasherDefault<FxHasher>> =
            HashMap::with_hasher(BuildHasherDefault::default());

        let seq = b"ACGTACGT";
        let qual = b"IIII!!!!";
        let k = KmerLength::new(4).unwrap();

        // Quality 0 threshold - ! (Phred 0) passes because 0 >= 0
        // But the threshold is converted to ASCII 33 (0 + 33), and ! is ASCII 33
        // So ! exactly meets the threshold
        process_sequence_into_counts(&mut counts, seq, Some(qual), k, Some(0));

        // With threshold 0, all positions should pass
        assert!(!counts.is_empty());
    }

    #[test]
    fn quality_filtering_without_quality_data_counts_all() {
        let mut counts: HashMap<u64, u64, BuildHasherDefault<FxHasher>> =
            HashMap::with_hasher(BuildHasherDefault::default());

        let seq = b"ACGTACGT";
        let k = KmerLength::new(4).unwrap();

        // No quality data (like FASTA) - quality filtering is ignored
        process_sequence_into_counts(&mut counts, seq, None, k, Some(20));

        // Without quality data, all k-mers should be counted
        assert!(!counts.is_empty());
    }
}