From f022d833941c9ffe78546172c8b95be512e32581 Mon Sep 17 00:00:00 2001 From: Eric Coissac Date: Tue, 1 Dec 2026 14:52:14 +0100 Subject: [PATCH] refactor: modernize arithmetic, control flow, and error handling Replace manual ceiling division with `div_ceil`, update `map_or` patterns to `is_some_and`/`is_ok_and`, and simplify error handling across the codebase. Move the `default` function for `GraphDeBruijn` from the index layer module to the De Bruijn graph module. - Move `default` from `src/obikindex/src/layer/meta.rs` to `src/obidebruinj/src/debruijn/graph.rs` and implement `Default` for `GraphDeBruijn` - Simplify `IndexBuilder::state`, `KmerIndex::genomes`, and `n_layers_per_partition` in `src/obikindex` by removing redundant `Ok` wrappers - Replace manual ceiling division with `div_ceil` in `src/obikindex/src/layer/fingerprint.rs` for data slicing and byte calculations - Update `Mphf` operations in `src/obikindex/src/layer/mphf_layer.rs` to use `mmap`, `load_full`, and `store` directly, and switch size calculations to `div_ceil` - Refine `IndexMode` in `src/obikindex/src/layer/meta.rs` to derive `Default` with `#[default]` on `Exact` - Update `count_partition` in `src/obikindexer/src/algorithms/counter/count.rs` to use `io::Error::other` with string conversion for error mapping - Switch `optimal_buckets` in `src/obikindexer/src/algorithms/dereplicator/dereplicate.rs` to use `div_ceil` for average sequence bytes and bucket estimation - Replace `max_or` and `map_or` with `is_none_or` and direct checks in `src/obikindexer/src/extensions/private_builder.rs` for layer building and artifact removal - Enforce odd k-mer and minimizer sizes in `src/obikmer/src/cli.rs` using `is_multiple_of` and update validation ranges - Update `resolve_approx_params` in `src/obikmer/src/cmd/index/mod.rs` to use `div_ceil` for parameter calculations - Add documentation for `DistanceArg` in `src/obikmer/src/cmd/phylo/values.rs` and clean up test modules - Refactor median calculation in `src/obikmer/src/cmd/utils/partition_stats.rs` to explicitly handle even and odd lengths - Replace `g.len() > 0` with `!g.is_empty()` in `src/obikmerge/src/partition_merge/mod.rs` - Use `isolate_lowest_one` in `src/obikphylo/src/siblings/algorithms/alignment_vcf.rs` for diploid allele calculation - Add documentation for `family_entropy` in `src/obikphylo/src/siblings/algorithms/entropy.rs` and remove empty test blocks - Replace `map_or` with `is_some_and` in `src/obikquery/src/findere.rs` and `src/obikquery/src/tests/findere.rs` for deque pruning logic - Simplify `remove_if_exists` in `src/obikrebuild/src/reindex.rs` to warn only on non-`NotFound` errors - Store `mime_type` by value in `src/obikrope/src/rope.rs` and update `mime_type` and `split_off` accordingly - Replace manual ceiling division with `div_ceil` in `src/obikseq/src/packed_seq.rs` for byte length and iteration logic - Update `build_dec4` in `src/obikseq/src/encoding.rs` to use a string slice literal for the decode table - Refactor `revcomp4` in `src/obikseq/src/revcomp_lookup.rs` to use `rotate_left` for nibble swapping - Simplify `run` in `src/obipipeline/src/scheduler/pool.rs` to use `if let Ok` for delta handling - Simplify MIME type checking in `src/obiread/src/chunk.rs` and update error handling for unsupported formats - Replace `map_or` with `is_ok_and` in `src/obiread/src/mimetype.rs` for FASTA/FASTQ detection - Update `normalize_fastq` and related functions in `src/obiread/src/normalize.rs` to handle `Result` returns from cursor reads - Simplify `skip_line` in `src/obiread/src/record.rs` to check `Ok` results directly - Simplify test assertions in `src/obiread/src/tests/chunk.rs` by removing unnecessary closures - Update `http_reader` in `src/obiread/src/xopen.rs` to map errors to `io::Error::other` and refine `expand_tilde` logic - Refactor minimizer change detection in `src/obiskbuilder/src/iter.rs` and `src/obiskbuilder/src/stream_iter.rs` to explicitly check `Some` and inequality - Update `push` in `src/obiskbuilder/src/rolling_stat.rs` to use `is_some_and` for hash and position checks - Replace manual ceiling division with `div_ceil` in `src/obiskbuilder/src/scratch.rs` for buffer slicing - Update `next` in `src/obiskio/src/unitig_index/kmer_iter.rs` to use `div_ceil` for byte length calculation - Replace manual ceiling division with `div_ceil` in `src/obiskio/src/unitig_index/kmer_raw.rs` for byte extraction - Update `src/obiskio/src/unitig_index/reader.rs` to use `div_ceil` for byte lengths and direct comparison for magic bytes - Replace manual ceiling division with `div_ceil` in `src/obiskio/src/unitig_index/writer.rs` for chunk and index writing - Simplify CPU set mapping in `src/obisys/src/numa/topology.rs` by removing explicit type annotations - Update `stop` in `src/obisys/src/stage.rs` to use direct delta comparisons for fault counts - Refine `matches` in `src/obitaxonomy/src/segment_pattern.rs` to check for inequality when rank is `None` --- src/obidebruinj/src/debruijn/graph.rs | 6 ++ src/obikindex/src/index/builder.rs | 2 +- src/obikindex/src/index/kmer_index.rs | 4 +- src/obikindex/src/layer/fingerprint.rs | 4 +- src/obikindex/src/layer/meta.rs | 8 +-- src/obikindex/src/layer/mphf_layer.rs | 24 ++++--- .../src/algorithms/counter/count.rs | 2 +- .../algorithms/dereplicator/dereplicate.rs | 4 +- .../src/extensions/private_builder.rs | 12 ++-- src/obikmer/src/cli.rs | 6 +- src/obikmer/src/cmd/index/mod.rs | 6 +- src/obikmer/src/cmd/phylo/values.rs | 64 +++++++++---------- src/obikmer/src/cmd/utils/partition_stats.rs | 2 +- src/obikmerge/src/partition_merge/mod.rs | 2 +- .../src/siblings/algorithms/alignment_vcf.rs | 2 +- .../src/siblings/algorithms/entropy.rs | 48 +++++++------- src/obikquery/src/findere.rs | 4 +- src/obikquery/src/tests/findere.rs | 4 +- src/obikrebuild/src/reindex.rs | 8 +-- src/obikrope/src/rope.rs | 6 +- src/obikseq/src/annotations.rs | 1 - src/obikseq/src/encoding.rs | 2 +- src/obikseq/src/packed_seq.rs | 10 +-- src/obikseq/src/revcomp_lookup.rs | 2 +- src/obipipeline/src/scheduler/pool.rs | 9 +-- src/obiread/src/chunk.rs | 48 +++++++------- src/obiread/src/mimetype.rs | 4 +- src/obiread/src/normalize.rs | 8 +-- src/obiread/src/record.rs | 2 +- src/obiread/src/tests/chunk.rs | 4 +- src/obiread/src/xopen.rs | 14 ++-- src/obiskbuilder/src/iter.rs | 18 +++--- src/obiskbuilder/src/rolling_stat.rs | 6 +- src/obiskbuilder/src/scratch.rs | 6 +- src/obiskbuilder/src/stream_iter.rs | 18 +++--- src/obiskio/src/unitig_index/kmer_iter.rs | 2 +- src/obiskio/src/unitig_index/kmer_raw.rs | 2 +- src/obiskio/src/unitig_index/reader.rs | 16 ++--- src/obiskio/src/unitig_index/writer.rs | 4 +- src/obisys/src/numa/topology.rs | 7 +- src/obisys/src/stage.rs | 14 ++-- src/obitaxonomy/src/segment_pattern.rs | 2 +- 42 files changed, 202 insertions(+), 215 deletions(-) diff --git a/src/obidebruinj/src/debruijn/graph.rs b/src/obidebruinj/src/debruijn/graph.rs index 02816293..6c838d0c 100644 --- a/src/obidebruinj/src/debruijn/graph.rs +++ b/src/obidebruinj/src/debruijn/graph.rs @@ -317,6 +317,12 @@ impl GraphDeBruijn { } } +impl Default for GraphDeBruijn { + fn default() -> Self { + Self::new() + } +} + /// Returns the count of neighbors and the index of the first /// neighbor if exactly one of the four canonical neighbours exists in /// the graph, where `i` is its index (0=A, 1=C, 2=G, 3=T). diff --git a/src/obikindex/src/index/builder.rs b/src/obikindex/src/index/builder.rs index 9272a815..556d0de0 100644 --- a/src/obikindex/src/index/builder.rs +++ b/src/obikindex/src/index/builder.rs @@ -121,6 +121,6 @@ impl IndexBuilder for KmerIndex { } fn state(&self) -> OKIResult { - Ok(self.meta.state().map_err(OKIError::Io)?) + self.meta.state().map_err(OKIError::Io) } } diff --git a/src/obikindex/src/index/kmer_index.rs b/src/obikindex/src/index/kmer_index.rs index 45773eda..1d0093cf 100644 --- a/src/obikindex/src/index/kmer_index.rs +++ b/src/obikindex/src/index/kmer_index.rs @@ -199,7 +199,7 @@ impl KmerIndex { /// Genome list — reads `index.meta` fresh (see `IndexMeta::genomes`, /// this can legitimately change during a run, unlike `config`). pub fn genomes(&self) -> OKIResult> { - Ok(self.meta.genomes().map_err(OKIError::Io)?) + self.meta.genomes().map_err(OKIError::Io) } pub fn n_partitions(&self) -> usize { 1usize << self.meta.config.n_bits @@ -270,7 +270,7 @@ impl KmerIndex { /// homogeneous across all partitions — reading it off partition 0 /// is enough, no need to scan every partition. pub fn n_layers_per_partition(&self) -> OKIResult { - Ok(self.n_layers(0)?) + self.n_layers(0) } /// Path to the unitigs file for partition `part`, layer `layer`. diff --git a/src/obikindex/src/layer/fingerprint.rs b/src/obikindex/src/layer/fingerprint.rs index fa2386cf..6f5a91c5 100644 --- a/src/obikindex/src/layer/fingerprint.rs +++ b/src/obikindex/src/layer/fingerprint.rs @@ -50,7 +50,7 @@ impl FingerprintVec { let mask: u64 = if b == 64 { u64::MAX } else { (1u64 << b) - 1 }; // SAFETY: the mmap lives as long as Self (kept via _mmap); data is read-only. let data: &'static [u8] = unsafe { - std::slice::from_raw_parts(mmap[HEADER..].as_ptr(), (n * b as usize + 7) / 8) + std::slice::from_raw_parts(mmap[HEADER..].as_ptr(), (n * b as usize).div_ceil(8)) }; let bits = BitSlice::::from_slice(data); Ok(Self { @@ -93,7 +93,7 @@ pub struct FingerprintVecWriter { impl FingerprintVecWriter { pub fn new(n: usize, b: u8) -> Self { assert!(b > 0 && b <= 64, "fingerprint width must be 1..=64"); - let data_bytes = (n * b as usize + 7) / 8; + let data_bytes = (n * b as usize).div_ceil(8); Self { buf: vec![0u8; data_bytes], n, diff --git a/src/obikindex/src/layer/meta.rs b/src/obikindex/src/layer/meta.rs index 1f6bdea1..4b505b2a 100644 --- a/src/obikindex/src/layer/meta.rs +++ b/src/obikindex/src/layer/meta.rs @@ -17,8 +17,10 @@ use crate::layer::utils::layer_dir; /// disk, the same probe [`EvidenceKind::detect`] uses. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] +#[derive(Default)] pub enum IndexMode { /// Exact evidence: `evidence.bin` + `unitigs.bin.idx`. Zero false positives. + #[default] Exact, /// Approximate evidence: `fingerprint.bin` only. /// `b` — fingerprint bits per slot; false-positive rate ≈ 1/2^b per query. @@ -31,12 +33,6 @@ pub enum IndexMode { Hybrid { b: u8, z: u8 }, } -impl Default for IndexMode { - fn default() -> Self { - Self::Exact - } -} - impl IndexMode { /// Detect the evidence mode actually on disk, from partition index /// directory `root`'s layer 0 — the single source of truth every layer diff --git a/src/obikindex/src/layer/mphf_layer.rs b/src/obikindex/src/layer/mphf_layer.rs index 046c37a8..a84e3aae 100644 --- a/src/obikindex/src/layer/mphf_layer.rs +++ b/src/obikindex/src/layer/mphf_layer.rs @@ -418,7 +418,7 @@ pub struct MphfOnly(MemCase); impl MphfOnly { pub fn open(dir: &Path) -> OKIResult { - let mphf: MemCase = unsafe { Mphf::mmap(&dir.join(MPHF_FILE), Flags::empty()) } + let mphf: MemCase = unsafe { Mphf::mmap(dir.join(MPHF_FILE), Flags::empty()) } .map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string(), @@ -476,15 +476,14 @@ impl MphfLayer { return Ok(0); } - let mphf: Mphf = unsafe { Mphf::load_full(&dir.join(MPHF_FILE)) }.map_err(|e| { - OKIError::InvalidData { + let mphf: Mphf = + unsafe { Mphf::load_full(dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string(), - } - })?; + })?; let mut ev = EvidenceWriter::new(n); - let mut seen = vec![0u8; (n + 7) / 8]; + let mut seen = vec![0u8; n.div_ceil(8)]; for (slot, _, chunk_id, rank) in SlottedKmers::new(&mphf, unitigs.iter_indexed_canonical_kmers()) @@ -535,12 +534,11 @@ impl MphfLayer { return Ok(0); } - let mphf: Mphf = unsafe { Mphf::load_full(&dir.join(MPHF_FILE)) }.map_err(|e| { - OKIError::InvalidData { + let mphf: Mphf = + unsafe { Mphf::load_full(dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string(), - } - })?; + })?; let mut fw = FingerprintVecWriter::new(n, b); @@ -590,7 +588,7 @@ impl MphfLayer { detail: "construction failed".into(), } })?; - unsafe { mphf.store(&dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData { + unsafe { mphf.store(dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string(), })?; @@ -613,14 +611,14 @@ impl MphfLayer { let keys = CanonicalKmerIter::new(&unitig_path).map_err(sk_to_olm)?; let mphf: Mphf = Mphf::new_from_par_iter(n, keys.map(|k| k.raw()).par_bridge(), mphf_params()); - unsafe { mphf.store(&dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData { + unsafe { mphf.store(dir.join(MPHF_FILE)) }.map_err(|e| OKIError::InvalidData { context: "layer", detail: e.to_string(), })?; // ── Pass 2: fill evidence files + callback ──────────────────────────── let unitigs2 = UnitigFileReader::open_sequential(&unitig_path)?; - let mut seen = vec![0u8; (n + 7) / 8]; + let mut seen = vec![0u8; n.div_ceil(8)]; match mode { IndexMode::Exact => { diff --git a/src/obikindexer/src/algorithms/counter/count.rs b/src/obikindexer/src/algorithms/counter/count.rs index 00ddf07e..abde0f43 100644 --- a/src/obikindexer/src/algorithms/counter/count.rs +++ b/src/obikindexer/src/algorithms/counter/count.rs @@ -68,7 +68,7 @@ pub(super) fn count_partition(dir: &Path, dedup_path: &Path, chunk_kmers: usize) ) .map_err(io::Error::other)?; - unsafe { EpSerialize::store(&mphf, &dir.join("mphf1.bin")) } + unsafe { EpSerialize::store(&mphf, dir.join("mphf1.bin")) } .map_err(|e| io::Error::other(e.to_string()))?; Ok(()) diff --git a/src/obikindexer/src/algorithms/dereplicator/dereplicate.rs b/src/obikindexer/src/algorithms/dereplicator/dereplicate.rs index e9401027..6b8c4c18 100644 --- a/src/obikindexer/src/algorithms/dereplicator/dereplicate.rs +++ b/src/obikindexer/src/algorithms/dereplicator/dereplicate.rs @@ -41,7 +41,7 @@ pub(crate) fn optimal_buckets(raw_path: &Path, available_bytes: u64) -> usize { _ => return 1, }; - let avg_seq_bytes = ((meta.length_sum + meta.instances - 1) / meta.instances + 3) / 4; + let avg_seq_bytes = meta.length_sum.div_ceil(meta.instances).div_ceil(4); // SuperKmer: header (4 B) + Box<[u8]> ptr+len (16 B) + heap seq bytes; value: u64 (8 B); ×1.5 for hashbrown overhead. let bytes_per_entry = ((4 + 16 + avg_seq_bytes + 8) as f64 * 1.5) as u64; let estimated = meta.instances * bytes_per_entry; @@ -52,7 +52,7 @@ pub(crate) fn optimal_buckets(raw_path: &Path, available_bytes: u64) -> usize { } // Round up to the next power of two. - let n = (estimated + budget - 1) / budget; + let n = estimated.div_ceil(budget); debug!("Dereplication: estimated={estimated} budget={budget} n_temp={n}"); n.next_power_of_two() as usize } diff --git a/src/obikindexer/src/extensions/private_builder.rs b/src/obikindexer/src/extensions/private_builder.rs index 2e9f6c62..12f3551f 100644 --- a/src/obikindexer/src/extensions/private_builder.rs +++ b/src/obikindexer/src/extensions/private_builder.rs @@ -188,7 +188,7 @@ impl PrivateBuilder for KmerIndex { match (&mphf1_opt, &counts1_opt) { (Some(mphf), Some(counts)) => { let ab = counts.get(mphf.index(&kmer.raw())); - ab >= min_ab && max_ab.map_or(true, |max| ab <= max) + ab >= min_ab && max_ab.is_none_or(|max| ab <= max) } _ => true, } @@ -222,7 +222,7 @@ impl PrivateBuilder for KmerIndex { fn remove_build_artifacts(&self, i: usize) { // No layer 0 = empty partition: no build artifacts to remove. - if self.partition(i).map_or(false, |p| p.n_layers() == 0) { + if self.partition(i).is_ok_and(|p| p.n_layers() == 0) { return; } let layer0 = match self.layer0(i) { @@ -244,9 +244,9 @@ impl PrivateBuilder for KmerIndex { // ── private helpers ────────────────────────────────────────────────────── fn remove_if_exists(path: &Path) { - if let Err(e) = fs::remove_file(path) { - if e.kind() != io::ErrorKind::NotFound { - eprintln!("warning: could not remove {}: {e}", path.display()); - } + if let Err(e) = fs::remove_file(path) + && e.kind() != io::ErrorKind::NotFound + { + eprintln!("warning: could not remove {}: {e}", path.display()); } } diff --git a/src/obikmer/src/cli.rs b/src/obikmer/src/cli.rs index bc2ac876..343c8868 100644 --- a/src/obikmer/src/cli.rs +++ b/src/obikmer/src/cli.rs @@ -69,11 +69,11 @@ impl CommonArgs { let k = self.kmer_size; let m = self.minimizer_size; - if k < 11 || k > 31 { + if !(11..=31).contains(&k) { eprintln!("error: --kmer-size must be in [11, 31] (got {k})"); std::process::exit(1); } - if k % 2 == 0 { + if k.is_multiple_of(2) { eprintln!("error: --kmer-size must be odd (got {k}); even k allows palindromic k-mers"); std::process::exit(1); } @@ -84,7 +84,7 @@ impl CommonArgs { ); std::process::exit(1); } - if m % 2 == 0 { + if m.is_multiple_of(2) { eprintln!("error: --minimizer-size must be odd (got {m})"); std::process::exit(1); } diff --git a/src/obikmer/src/cmd/index/mod.rs b/src/obikmer/src/cmd/index/mod.rs index 6d178323..60cfc037 100644 --- a/src/obikmer/src/cmd/index/mod.rs +++ b/src/obikmer/src/cmd/index/mod.rs @@ -125,13 +125,13 @@ pub(crate) fn resolve_approx_params( } (Some(z), None, Some(fp)) => { let bz = (-fp.log2()).ceil() as u32; - let b = ((bz + z as u32 - 1) / z as u32).max(1) as u8; + let b = bz.div_ceil(z as u32).max(1) as u8; let actual_fp = 1.0_f64 / (1u64 << (b as u32 * z as u32)) as f64; (z, b, actual_fp) } (None, Some(b), Some(fp)) => { let bz = (-fp.log2()).ceil() as u32; - let z = ((bz + b as u32 - 1) / b as u32).max(1) as u8; + let z = bz.div_ceil(b as u32).max(1) as u8; let actual_fp = 1.0_f64 / (1u64 << (b as u32 * z as u32)) as f64; (z, b, actual_fp) } @@ -148,7 +148,7 @@ pub(crate) fn resolve_approx_params( } (None, None, Some(fp)) => { let b = DEFAULT_B; - let z = ((bits_needed(fp) as u32 + b as u32 - 1) / b as u32).max(1) as u8; + let z = (bits_needed(fp) as u32).div_ceil(b as u32).max(1) as u8; let actual_fp = 1.0_f64 / (1u64 << (b as u32 * z as u32)) as f64; (z, b, actual_fp) } diff --git a/src/obikmer/src/cmd/phylo/values.rs b/src/obikmer/src/cmd/phylo/values.rs index 6fea4b3d..5385455f 100644 --- a/src/obikmer/src/cmd/phylo/values.rs +++ b/src/obikmer/src/cmd/phylo/values.rs @@ -113,38 +113,6 @@ pub fn distance_to_compute( distance.or_else(|| (nj || upgma).then_some(DistanceArg::Jaccard)) } -#[cfg(test)] -mod distance_tests { - use super::*; - - #[test] - fn nothing_asked_nothing_computed() { - assert!(distance_to_compute(None, false, false).is_none()); - } - - #[test] - fn tree_outputs_imply_jaccard() { - for (nj, upgma) in [(true, false), (false, true)] { - assert!(matches!( - distance_to_compute(None, nj, upgma), - Some(DistanceArg::Jaccard) - )); - } - } - - #[test] - fn an_explicit_distance_wins() { - assert!(matches!( - distance_to_compute(Some(DistanceArg::Mash), true, true), - Some(DistanceArg::Mash) - )); - assert!(matches!( - distance_to_compute(Some(DistanceArg::SnpJc), false, false), - Some(DistanceArg::SnpJc) - )); - } -} - impl DistanceArg { /// `Some` for the whole-index metrics, `None` for `snp-*` values. pub fn as_classic(self) -> Option { @@ -177,3 +145,35 @@ impl DistanceArg { }) } } + +#[cfg(test)] +mod distance_tests { + use super::*; + + #[test] + fn nothing_asked_nothing_computed() { + assert!(distance_to_compute(None, false, false).is_none()); + } + + #[test] + fn tree_outputs_imply_jaccard() { + for (nj, upgma) in [(true, false), (false, true)] { + assert!(matches!( + distance_to_compute(None, nj, upgma), + Some(DistanceArg::Jaccard) + )); + } + } + + #[test] + fn an_explicit_distance_wins() { + assert!(matches!( + distance_to_compute(Some(DistanceArg::Mash), true, true), + Some(DistanceArg::Mash) + )); + assert!(matches!( + distance_to_compute(Some(DistanceArg::SnpJc), false, false), + Some(DistanceArg::SnpJc) + )); + } +} diff --git a/src/obikmer/src/cmd/utils/partition_stats.rs b/src/obikmer/src/cmd/utils/partition_stats.rs index b0f55d0b..99ad58ce 100644 --- a/src/obikmer/src/cmd/utils/partition_stats.rs +++ b/src/obikmer/src/cmd/utils/partition_stats.rs @@ -66,7 +66,7 @@ fn stats_summary(totals: &[u64]) -> (u64, u64, f64, f64, u64, u64, u64) { let min = sorted[0]; let max = sorted[n - 1]; let mean = sorted.iter().sum::() as f64 / n as f64; - let median = if n % 2 == 0 { + let median = if n.is_multiple_of(2) { (sorted[n / 2 - 1] + sorted[n / 2]) as f64 / 2.0 } else { sorted[n / 2] as f64 diff --git a/src/obikmerge/src/partition_merge/mod.rs b/src/obikmerge/src/partition_merge/mod.rs index 75cfbadf..943d04dd 100644 --- a/src/obikmerge/src/partition_merge/mod.rs +++ b/src/obikmerge/src/partition_merge/mod.rs @@ -134,7 +134,7 @@ pub(crate) fn merge_partition( max_open, )?; - let any_new = g.len() > 0; + let any_new = !g.is_empty(); debug!( "partition {i}: de Bruijn graph done — {} new kmers", g.len() diff --git a/src/obikphylo/src/siblings/algorithms/alignment_vcf.rs b/src/obikphylo/src/siblings/algorithms/alignment_vcf.rs index b2496326..ea73df19 100644 --- a/src/obikphylo/src/siblings/algorithms/alignment_vcf.rs +++ b/src/obikphylo/src/siblings/algorithms/alignment_vcf.rs @@ -58,7 +58,7 @@ fn cell_alleles(cell: u8, diploid: bool) -> Option<[u8; 2]> { 0 => Some([ABSENT, ABSENT]), 1 => Some([allele(state), allele(state)]), 2 if diploid => { - let low = state & state.wrapping_neg(); + let low = state.isolate_lowest_one(); Some([allele(low), allele(state ^ low)]) } _ => None, diff --git a/src/obikphylo/src/siblings/algorithms/entropy.rs b/src/obikphylo/src/siblings/algorithms/entropy.rs index 0edc1780..50855242 100644 --- a/src/obikphylo/src/siblings/algorithms/entropy.rs +++ b/src/obikphylo/src/siblings/algorithms/entropy.rs @@ -82,6 +82,30 @@ pub(crate) fn family_entropy_4(genome_mask: &[u8]) -> Option<(f64, usize)> { use crate::siblings::AmbiguityPolicy; use crate::siblings::helpers::is_carrier; +/// Shannon entropy (bits) of one family under the counting convention an +/// [`AmbiguityPolicy`] selects: +/// - `Keep`: [`family_entropy`] — every genome carrying the family counts, +/// a genome with several members being a state of its own; +/// - `Forbid` (`--no-ambiguity`): [`family_entropy_4`] — only the genomes +/// carrying exactly one member count, the others being missing data, +/// exactly as the alignment itself will see them. Over those genomes the +/// 15-state entropy can only ever take the four single-base states, so the +/// two definitions coincide; +/// - `OnlyDiploid`: the 15-state entropy over the genomes with one or two +/// members (ten states), the others being missing data. +/// +/// Second value: the number of genomes the entropy was computed over. +pub(crate) fn family_entropy_under( + genome_mask: &[u8], + policy: AmbiguityPolicy, +) -> Option<(f64, usize)> { + match policy { + AmbiguityPolicy::Keep => family_entropy(genome_mask), + AmbiguityPolicy::Forbid => family_entropy_4(genome_mask), + AmbiguityPolicy::OnlyDiploid => family_entropy_with(genome_mask, policy), + } +} + #[cfg(test)] mod tests { use super::*; @@ -134,27 +158,3 @@ mod tests { assert!(family_entropy_4(&[]).is_none()); } } - -/// Shannon entropy (bits) of one family under the counting convention an -/// [`AmbiguityPolicy`] selects: -/// - `Keep`: [`family_entropy`] — every genome carrying the family counts, -/// a genome with several members being a state of its own; -/// - `Forbid` (`--no-ambiguity`): [`family_entropy_4`] — only the genomes -/// carrying exactly one member count, the others being missing data, -/// exactly as the alignment itself will see them. Over those genomes the -/// 15-state entropy can only ever take the four single-base states, so the -/// two definitions coincide; -/// - `OnlyDiploid`: the 15-state entropy over the genomes with one or two -/// members (ten states), the others being missing data. -/// -/// Second value: the number of genomes the entropy was computed over. -pub(crate) fn family_entropy_under( - genome_mask: &[u8], - policy: AmbiguityPolicy, -) -> Option<(f64, usize)> { - match policy { - AmbiguityPolicy::Keep => family_entropy(genome_mask), - AmbiguityPolicy::Forbid => family_entropy_4(genome_mask), - AmbiguityPolicy::OnlyDiploid => family_entropy_with(genome_mask, policy), - } -} diff --git a/src/obikquery/src/findere.rs b/src/obikquery/src/findere.rs index 58c6be44..3befdc84 100644 --- a/src/obikquery/src/findere.rs +++ b/src/obikquery/src/findere.rs @@ -47,11 +47,11 @@ pub(crate) fn sparse_findere_for_genome( dq.clear(); for (k, &(_, pos, val)) in run.iter().enumerate() { - while dq.back().map_or(false, |&(_, v)| v >= val) { + while dq.back().is_some_and(|&(_, v)| v >= val) { dq.pop_back(); } dq.push_back((k, val)); - while dq.front().map_or(false, |&(fk, _)| fk + z <= k) { + while dq.front().is_some_and(|&(fk, _)| fk + z <= k) { dq.pop_front(); } if k + 1 >= z { diff --git a/src/obikquery/src/tests/findere.rs b/src/obikquery/src/tests/findere.rs index 1df0a086..89314e5a 100644 --- a/src/obikquery/src/tests/findere.rs +++ b/src/obikquery/src/tests/findere.rs @@ -29,10 +29,10 @@ fn dense_reference_findere( let mut dq: std::collections::VecDeque<(usize, u32)> = std::collections::VecDeque::new(); for i in 0..n { let v_i = values[i]; - while dq.front().map_or(false, |&(f, _)| f + z <= i) { + while dq.front().is_some_and(|&(f, _)| f + z <= i) { dq.pop_front(); } - while dq.back().map_or(false, |&(_, v)| v >= v_i) { + while dq.back().is_some_and(|&(_, v)| v >= v_i) { dq.pop_back(); } dq.push_back((i, v_i)); diff --git a/src/obikrebuild/src/reindex.rs b/src/obikrebuild/src/reindex.rs index 69329772..61c81f51 100644 --- a/src/obikrebuild/src/reindex.rs +++ b/src/obikrebuild/src/reindex.rs @@ -123,9 +123,9 @@ fn remove_stale_evidence(layer: &KmerLayer, target: &IndexMode) { } fn remove_if_exists(path: &std::path::Path) { - if let Err(e) = std::fs::remove_file(path) { - if e.kind() != std::io::ErrorKind::NotFound { - eprintln!("warning: could not remove {}: {e}", path.display()); - } + if let Err(e) = std::fs::remove_file(path) + && e.kind() != std::io::ErrorKind::NotFound + { + eprintln!("warning: could not remove {}: {e}", path.display()); } } diff --git a/src/obikrope/src/rope.rs b/src/obikrope/src/rope.rs index ffcbaefd..ec0a8557 100644 --- a/src/obikrope/src/rope.rs +++ b/src/obikrope/src/rope.rs @@ -63,7 +63,7 @@ impl Rope { /// The MIME type of the rope, if known. pub fn mime_type(&self) -> Option<&str> { - self.mime_type.as_deref() + self.mime_type } /// Total number of blocks. @@ -122,7 +122,7 @@ impl Rope { } if pos == self.length { - return Ok(Rope::new(self.mime_type.clone())); + return Ok(Rope::new(self.mime_type)); } let (block_idx, from, _) = self.lookup(pos).ok_or_else(|| { @@ -156,7 +156,7 @@ impl Rope { self.length = pos; Ok(Rope { - mime_type: self.mime_type.clone(), + mime_type: self.mime_type, blocks: tail_blocks, length: tail_length, start_block_idx: tail_starts, diff --git a/src/obikseq/src/annotations.rs b/src/obikseq/src/annotations.rs index ba8a7bd1..88d3a43f 100644 --- a/src/obikseq/src/annotations.rs +++ b/src/obikseq/src/annotations.rs @@ -1,5 +1,4 @@ use serde::Serialize; -use serde_json; use std::io::{self, Write}; /// Minimal annotation carrying only the sequence length. diff --git a/src/obikseq/src/encoding.rs b/src/obikseq/src/encoding.rs index d95aaf20..9061311f 100644 --- a/src/obikseq/src/encoding.rs +++ b/src/obikseq/src/encoding.rs @@ -17,7 +17,7 @@ pub(crate) fn encode_base(b: u8) -> u8 { } const fn build_dec4() -> [u32; 256] { - const DECODE: [u8; 4] = [b'A', b'C', b'G', b'T']; + const DECODE: [u8; 4] = *b"ACGT"; let mut table = [0u32; 256]; let mut i = 0usize; while i < 256 { diff --git a/src/obikseq/src/packed_seq.rs b/src/obikseq/src/packed_seq.rs index 0614568f..afa28c99 100644 --- a/src/obikseq/src/packed_seq.rs +++ b/src/obikseq/src/packed_seq.rs @@ -133,7 +133,7 @@ impl FromIterator for PackedSeq { let mut seq: Vec = Vec::with_capacity(byte_len(lower.max(1))); let mut seql = 0usize; for nuc in iter { - if seql % 4 == 0 { + if seql.is_multiple_of(4) { seq.push(0); } *seq.last_mut().unwrap() |= (nuc & 0b11) << (6 - 2 * (seql % 4)); @@ -295,7 +295,7 @@ impl PackedSeq { pub fn sub(&self, start: usize, end: usize) -> Self { debug_assert!(end > start && end <= self.seql()); let seql = end - start; - let n = (seql + 3) / 4; + let n = seql.div_ceil(4); let mut out = vec![0u8; n]; let src = self.seq.view_bits::(); let dst = out.view_bits_mut::(); @@ -313,7 +313,7 @@ impl PackedSeq { let seql = self.seql(); debug_assert!(seql >= k, "sequence shorter than k"); debug_assert!( - seql - k + 1 <= MAX_KMERS_PER_CHUNK, + seql - k < MAX_KMERS_PER_CHUNK, "chunk exceeds MAX_KMERS_PER_CHUNK; split before calling write_to_binary" ); w.write_all(&[(seql - k) as u8])?; @@ -326,7 +326,7 @@ impl PackedSeq { let mut buf = [0u8; 1]; r.read_exact(&mut buf)?; let seql = buf[0] as usize + crate::params::k(); - let byte_len = (seql + 3) / 4; + let byte_len = seql.div_ceil(4); let tail = (seql % 4) as u8; let mut seq = vec![0u8; byte_len]; r.read_exact(&mut seq)?; @@ -460,7 +460,7 @@ fn complement(base: u8) -> u8 { #[inline] fn byte_len(seql: usize) -> usize { - (seql + 3) / 4 + seql.div_ceil(4) } /// Nucleotide count → `tail` value: 0 encodes 4, 1–3 are identity. diff --git a/src/obikseq/src/revcomp_lookup.rs b/src/obikseq/src/revcomp_lookup.rs index 3e3442af..63c541e7 100644 --- a/src/obikseq/src/revcomp_lookup.rs +++ b/src/obikseq/src/revcomp_lookup.rs @@ -4,7 +4,7 @@ pub(crate) static REVCOMP4: [u8; 256] = build_revcomp4(); pub(crate) const fn revcomp4(x: u8) -> u8 { let x = !x; // complement all bases - let x = (x >> 4) | (x << 4); // swap nibbles + let x = x.rotate_left(4); // swap nibbles let x = ((x >> 2) & 0x33) | ((x & 0x33) << 2); // swap 2-bit groups x } diff --git a/src/obipipeline/src/scheduler/pool.rs b/src/obipipeline/src/scheduler/pool.rs index 117539e8..d98bef3e 100644 --- a/src/obipipeline/src/scheduler/pool.rs +++ b/src/obipipeline/src/scheduler/pool.rs @@ -147,12 +147,9 @@ where } else if k == 1 { // ── Delta d'un flat worker ──────────────────────────── // delta = N - 1 (N items poussés, 1 item consommé) - match oper.recv(&flat_delta_rx) { - Ok(delta) => { - in_flight += delta; - flat_workers_active -= 1; - } - Err(_) => {} + if let Ok(delta) = oper.recv(&flat_delta_rx) { + in_flight += delta; + flat_workers_active -= 1; } } else if src_idx == Some(k) { // ── Nouvel item depuis la source ────────────────────── diff --git a/src/obiread/src/chunk.rs b/src/obiread/src/chunk.rs index 034f8e34..3ac766e4 100644 --- a/src/obiread/src/chunk.rs +++ b/src/obiread/src/chunk.rs @@ -112,18 +112,16 @@ impl Iterator for SeqChunkIter { pub fn read_fasta_chunks( path: &str, ) -> io::Result>>> { - let input = match xopen(path) { - Ok(mut i) => { - if i.mime_type() == Some("text/fasta") { - i - } else { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "not a FASTA file", - )); - } + let input = { + let mut i = xopen(path)?; + if i.mime_type() == Some("text/fasta") { + i + } else { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "not a FASTA file", + )); } - Err(e) => return Err(e), }; Ok(fasta_chunks(input)) } @@ -132,18 +130,16 @@ pub fn read_fasta_chunks( pub fn read_fastq_chunks( path: &str, ) -> io::Result>>> { - let input = match xopen(path) { - Ok(mut i) => { - if i.mime_type() == Some("text/fastq") { - i - } else { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "not a FASTQ file", - )); - } + let input = { + let mut i = xopen(path)?; + if i.mime_type() == Some("text/fastq") { + i + } else { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "not a FASTQ file", + )); } - Err(e) => return Err(e), }; Ok(fastq_chunks(input)) } @@ -164,8 +160,9 @@ pub fn read_sequence_chunks_sized( path: &str, block_size: usize, ) -> io::Result>>> { - let input = match xopen(path) { - Ok(mut i) => match i.mime_type() { + let input = { + let mut i = xopen(path)?; + match i.mime_type() { Some("text/fasta") => SeqChunkIter::new( i, block_size, @@ -184,8 +181,7 @@ pub fn read_sequence_chunks_sized( "not a FASTA or FASTQ file", )); } - }, - Err(e) => return Err(e), + } }; Ok(input) } diff --git a/src/obiread/src/mimetype.rs b/src/obiread/src/mimetype.rs index 8c3e209a..fb929c37 100644 --- a/src/obiread/src/mimetype.rs +++ b/src/obiread/src/mimetype.rs @@ -15,12 +15,12 @@ fn is_gbff(buf: &[u8]) -> bool { static RE_FASTA: LazyLock = LazyLock::new(|| Regex::new(r"^>[^ ]").unwrap()); fn is_fasta(buf: &[u8]) -> bool { - std::str::from_utf8(buf).map_or(false, |s| RE_FASTA.is_match(s)) + std::str::from_utf8(buf).is_ok_and(|s| RE_FASTA.is_match(s)) } static RE_FASTQ: LazyLock = LazyLock::new(|| Regex::new(r"^@[^ ].*\n[A-Za-z.-]+").unwrap()); fn is_fastq(buf: &[u8]) -> bool { - std::str::from_utf8(buf).map_or(false, |s| RE_FASTQ.is_match(s)) + std::str::from_utf8(buf).is_ok_and(|s| RE_FASTQ.is_match(s)) } fn is_text(buf: &[u8]) -> bool { diff --git a/src/obiread/src/normalize.rs b/src/obiread/src/normalize.rs index 3a5d43bd..9f4aa3bd 100644 --- a/src/obiread/src/normalize.rs +++ b/src/obiread/src/normalize.rs @@ -127,7 +127,7 @@ fn normalize_fasta(read: &ForwardCursor<'_>, wc: &mut ForwardCursor<'_>, k: usiz /// /// The k-mer size is used to determine the minimum length of Sequence /// to be considered valid. -fn normalize_fastq(read: &ForwardCursor<'_>, mut wc: &mut ForwardCursor<'_>, k: usize) { +fn normalize_fastq(read: &ForwardCursor<'_>, wc: &mut ForwardCursor<'_>, k: usize) { loop { skip_line(read); // skip header @@ -151,7 +151,7 @@ fn normalize_fastq(read: &ForwardCursor<'_>, mut wc: &mut ForwardCursor<'_>, k: } } - end_segment(&mut wc, k); + end_segment(wc, k); skip_line(read); // skip + line skip_line(read); // skip quality line @@ -180,7 +180,7 @@ fn end_segment(wc: &mut ForwardCursor<'_>, k: usize) { } fn skip_line(read: &ForwardCursor<'_>) { - while let Some(c) = read.read_next().ok() { + while let Ok(c) = read.read_next() { if is_newline(c) { skip_newlines(read); return; @@ -195,7 +195,7 @@ fn skip_newlines(read: &ForwardCursor<'_>) { } fn skip_until_acgt_or_newline(read: &ForwardCursor<'_>) { - while let Some(c) = read.read_ahead(1).ok() { + while let Ok(c) = read.read_ahead(1) { if is_newline(c) || is_acgt(c & !0x20u8) { return; } diff --git a/src/obiread/src/record.rs b/src/obiread/src/record.rs index 3d687257..addd5ae6 100644 --- a/src/obiread/src/record.rs +++ b/src/obiread/src/record.rs @@ -224,7 +224,7 @@ fn read_id(cursor: &ForwardCursor<'_>) -> String { } fn skip_line(cursor: &ForwardCursor<'_>) { - while let Some(c) = cursor.read_next().ok() { + while let Ok(c) = cursor.read_next() { if c == b'\n' { return; } diff --git a/src/obiread/src/tests/chunk.rs b/src/obiread/src/tests/chunk.rs index 2f434396..e153acc6 100644 --- a/src/obiread/src/tests/chunk.rs +++ b/src/obiread/src/tests/chunk.rs @@ -28,7 +28,7 @@ fn fasta_single_record_one_chunk() { fn fasta_two_records_split_across_chunks() { let data: &[u8] = b">s1\nACGT\n>s2\nTTTT\n"; let chunks: Vec<_> = fasta_iter(data, 10).collect::>().unwrap(); - let all: Vec = chunks.iter().flat_map(|r| rope_to_vec(r)).collect(); + let all: Vec = chunks.iter().flat_map(rope_to_vec).collect(); assert_eq!(all, b">s1\nACGT\n>s2\nTTTT\n"); } @@ -77,7 +77,7 @@ fn fastq_at_in_quality_handled() { make_fastq(&[(b"ACGTACGT", b"@@@@IIII"), (b"TTTTTTTT", b"HHHHHHHH")]).into_boxed_slice(), ); let chunks: Vec<_> = fastq_iter(data, 16).collect::>().unwrap(); - let all: Vec = chunks.iter().flat_map(|r| rope_to_vec(r)).collect(); + let all: Vec = chunks.iter().flat_map(rope_to_vec).collect(); assert_eq!(all, *data); } diff --git a/src/obiread/src/xopen.rs b/src/obiread/src/xopen.rs index df1e768f..e59f0acd 100644 --- a/src/obiread/src/xopen.rs +++ b/src/obiread/src/xopen.rs @@ -82,7 +82,7 @@ pub fn estimated_decompressed_len(source: &str) -> Option { fn http_reader(url: &str) -> io::Result> { ureq::get(url) .call() - .map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string())) + .map_err(|e| io::Error::other(e.to_string())) .map(|resp| -> Box { Box::new(resp.into_body().into_reader()) }) } @@ -93,12 +93,12 @@ fn decompress(raw: Box) -> io::Result> { } fn expand_tilde(path: &str) -> std::borrow::Cow<'_, str> { - if path.starts_with("~/") { - if let Some(home) = std::env::var_os("HOME") { - let mut expanded = home.to_string_lossy().into_owned(); - expanded.push_str(&path[1..]); - return std::borrow::Cow::Owned(expanded); - } + if path.starts_with("~/") + && let Some(home) = std::env::var_os("HOME") + { + let mut expanded = home.to_string_lossy().into_owned(); + expanded.push_str(&path[1..]); + return std::borrow::Cow::Owned(expanded); } std::borrow::Cow::Borrowed(path) } diff --git a/src/obiskbuilder/src/iter.rs b/src/obiskbuilder/src/iter.rs index 8a331232..ffb2707d 100644 --- a/src/obiskbuilder/src/iter.rs +++ b/src/obiskbuilder/src/iter.rs @@ -116,16 +116,16 @@ impl Iterator for SuperKmerIter<'_> { let min_pos = self.stat.minimizer_position().unwrap_or(0); // ── 2. Minimizer change check ───────────────────────────────────── - if let Some(prev) = self.prev_min { - if min != prev { - let result = self.try_emit(); - self.cursor.rewind(self.k).ok(); - self.reset(); - if result.is_some() { - return result; - } - continue; + if let Some(prev) = self.prev_min + && min != prev + { + let result = self.try_emit(); + self.cursor.rewind(self.k).ok(); + self.reset(); + if result.is_some() { + return result; } + continue; } // ── 3. Super-kmer length check ──────────────────────────────────── diff --git a/src/obiskbuilder/src/rolling_stat.rs b/src/obiskbuilder/src/rolling_stat.rs index 02ef174c..5a2c7358 100644 --- a/src/obiskbuilder/src/rolling_stat.rs +++ b/src/obiskbuilder/src/rolling_stat.rs @@ -140,13 +140,13 @@ impl RollingStat { if self.received >= m { let possible_canonical_m = (self.rolling_k & self.m_mask).min(self.rolling_rck >> ((k - m) * 2)); - let possible_hash_m = hash_kmer(possible_canonical_m << 64 - m * 2); + let possible_hash_m = hash_kmer(possible_canonical_m << (64 - m * 2)); let possible_pos_m = self.received - m; while self .minimier .back() - .map_or(false, |it| it.hash >= possible_hash_m) + .is_some_and(|it| it.hash >= possible_hash_m) { self.minimier.pop_back(); } @@ -160,7 +160,7 @@ impl RollingStat { while self .minimier .front() - .map_or(false, |it| it.position + k < self.received) + .is_some_and(|it| it.position + k < self.received) { self.minimier.pop_front(); } diff --git a/src/obiskbuilder/src/scratch.rs b/src/obiskbuilder/src/scratch.rs index 1f7b7bfd..1da736ce 100644 --- a/src/obiskbuilder/src/scratch.rs +++ b/src/obiskbuilder/src/scratch.rs @@ -58,8 +58,8 @@ impl SuperKmerScratch { /// Resets the buffer to empty afterward. pub fn emit(&mut self, min_pos: usize) -> RoutableSuperKmer { let seql = self.len; - debug_assert!(seql >= 1 && seql <= MAX_SUPERKMER_LEN); - let n = (seql + 3) / 4; + debug_assert!((1..=MAX_SUPERKMER_LEN).contains(&seql)); + let n = seql.div_ceil(4); let seq: Box<[u8]> = self.buf[..n].into(); self.buf[..n].fill(0); self.len = 0; @@ -67,7 +67,7 @@ impl SuperKmerScratch { } /// Discard all accumulated nucleotides without producing a [`SuperKmer`]. pub fn reset(&mut self) { - let n = (self.len + 3) / 4; + let n = self.len.div_ceil(4); self.buf[..n].fill(0); self.len = 0; } diff --git a/src/obiskbuilder/src/stream_iter.rs b/src/obiskbuilder/src/stream_iter.rs index 1fea3fdd..9dd6afc7 100644 --- a/src/obiskbuilder/src/stream_iter.rs +++ b/src/obiskbuilder/src/stream_iter.rs @@ -98,16 +98,16 @@ impl Iterator for SuperKmerStreamIter<'_> { let min_pos = self.stat.minimizer_position().unwrap_or(0); // ── 2. Minimizer change ─────────────────────────────────────────── - if let Some(prev) = self.prev_min { - if min != prev { - let result = self.try_emit(); - self.cursor.rewind(self.k); - self.reset(); - if result.is_some() { - return result; - } - continue; + if let Some(prev) = self.prev_min + && min != prev + { + let result = self.try_emit(); + self.cursor.rewind(self.k); + self.reset(); + if result.is_some() { + return result; } + continue; } // ── 3. Super-kmer length cap ────────────────────────────────────── diff --git a/src/obiskio/src/unitig_index/kmer_iter.rs b/src/obiskio/src/unitig_index/kmer_iter.rs index c06fe969..4ac4fb59 100644 --- a/src/obiskio/src/unitig_index/kmer_iter.rs +++ b/src/obiskio/src/unitig_index/kmer_iter.rs @@ -85,7 +85,7 @@ impl Iterator for CanonicalKmerIter { return Some(CanonicalKmer::from_raw_unchecked(canon)); } let seql_minus_k = self.mmap[self.chunk_pos] as usize; - let byte_len = (seql_minus_k + self.k + 3) / 4; + let byte_len = (seql_minus_k + self.k).div_ceil(4); self.chunk_pos += 1 + byte_len; self.load_chunk(); } diff --git a/src/obiskio/src/unitig_index/kmer_raw.rs b/src/obiskio/src/unitig_index/kmer_raw.rs index 821be290..801a7cc9 100644 --- a/src/obiskio/src/unitig_index/kmer_raw.rs +++ b/src/obiskio/src/unitig_index/kmer_raw.rs @@ -19,7 +19,7 @@ pub(super) fn extract_kmer_raw(bytes: &[u8], j: usize, k: usize) -> u64 { let bit_start = j * 2; let byte_start = bit_start / 8; let bit_offset = bit_start % 8; - let bytes_needed = (bit_offset + 2 * k + 7) / 8; + let bytes_needed = (bit_offset + 2 * k).div_ceil(8); let mut acc = 0u128; for idx in 0..bytes_needed { diff --git a/src/obiskio/src/unitig_index/reader.rs b/src/obiskio/src/unitig_index/reader.rs index 0b10400a..78ffa2d0 100644 --- a/src/obiskio/src/unitig_index/reader.rs +++ b/src/obiskio/src/unitig_index/reader.rs @@ -58,7 +58,7 @@ impl UnitigFileReader { while offset < mmap.len() { let seql_minus_k = mmap[offset] as usize; n_kmers += seql_minus_k + 1; - offset += 1 + (seql_minus_k + k + 3) / 4; + offset += 1 + (seql_minus_k + k).div_ceil(4); n_unitigs += 1; } @@ -126,14 +126,14 @@ impl UnitigFileReader { let mut offset = self.block_offsets.get(block) as usize; for _ in 0..rem { let seql_minus_k = self.mmap[offset] as usize; - offset += 1 + (seql_minus_k + self.k + 3) / 4; + offset += 1 + (seql_minus_k + self.k).div_ceil(4); } offset } else { let mut offset = 0usize; for _ in 0..i { let seql_minus_k = self.mmap[offset] as usize; - offset += 1 + (seql_minus_k + self.k + 3) / 4; + offset += 1 + (seql_minus_k + self.k).div_ceil(4); } offset } @@ -149,7 +149,7 @@ impl UnitigFileReader { pub fn unitig(&self, i: usize) -> Unitig { let offset = self.chunk_start(i); let seql = self.mmap[offset] as usize + self.k; - let byte_len = (seql + 3) / 4; + let byte_len = seql.div_ceil(4); let bytes = self.mmap[offset + 1..offset + 1 + byte_len] .to_vec() .into_boxed_slice(); @@ -190,7 +190,7 @@ impl UnitigFileReader { let mut offset = 0usize; (0..n).map(move |chunk_id| { let seql = mmap[offset] as usize + k; - let byte_len = (seql + 3) / 4; + let byte_len = seql.div_ceil(4); let bytes = mmap[offset + 1..offset + 1 + byte_len] .to_vec() .into_boxed_slice(); @@ -224,7 +224,7 @@ impl UnitigFileReader { (0..n).map(move |chunk_id| { let mmap = &*this.mmap; let seql = mmap[offset] as usize + k; - let byte_len = (seql + 3) / 4; + let byte_len = seql.div_ceil(4); let bytes = mmap[offset + 1..offset + 1 + byte_len] .to_vec() .into_boxed_slice(); @@ -277,7 +277,7 @@ impl UnitigFileReader { .map(move |chunk_id| { let mmap = &*this.mmap; let seql = mmap[offset] as usize + k; - let byte_len = (seql + 3) / 4; + let byte_len = seql.div_ceil(4); let bytes = mmap[offset + 1..offset + 1 + byte_len] .to_vec() .into_boxed_slice(); @@ -337,7 +337,7 @@ fn read_idx(path: &Path) -> SKResult<(usize, usize, u8, BlockOffsets)> { let data = unsafe { Mmap::map(&file).map_err(SKError::Io)? }; let magic_bytes = &data[0..4]; - if magic_bytes != &MAGIC { + if magic_bytes != MAGIC { return Err(SKError::BadMagic { expected: "UIX3", got: magic_bytes.try_into().unwrap(), diff --git a/src/obiskio/src/unitig_index/writer.rs b/src/obiskio/src/unitig_index/writer.rs index e37b9fc4..947c45d5 100644 --- a/src/obiskio/src/unitig_index/writer.rs +++ b/src/obiskio/src/unitig_index/writer.rs @@ -87,7 +87,7 @@ impl UnitigFileWriter { fn write_chunk(&mut self, unitig: &Unitig) -> SKResult<()> { let seql = unitig.seql(); - let byte_len = (seql + 3) / 4; + let byte_len = seql.div_ceil(4); debug_assert!( seql - self.k <= u8::MAX as usize, @@ -174,7 +174,7 @@ pub fn build_unitig_idx(unitigs_path: &Path, block_bits: u8) -> SKResult<()> { block_offsets.push(offset as u32); } let seql_minus_k = mmap[offset] as usize; - let byte_len = (seql_minus_k + k + 3) / 4; + let byte_len = (seql_minus_k + k).div_ceil(4); n_kmers += seql_minus_k + 1; offset += 1 + byte_len; chunk_count += 1; diff --git a/src/obisys/src/numa/topology.rs b/src/obisys/src/numa/topology.rs index 806d6a81..376ab52f 100644 --- a/src/obisys/src/numa/topology.rs +++ b/src/obisys/src/numa/topology.rs @@ -37,12 +37,7 @@ pub fn build() -> NumaSetup { let mut nodes: Vec> = topology .objects_with_type(ObjectType::NUMANode) .filter_map(|obj| obj.cpuset()) - .map(|cpuset| { - cpuset - .iter_set() - .map(|idx| usize::from(idx)) - .collect::>() - }) + .map(|cpuset| cpuset.iter_set().map(usize::from).collect::>()) .filter(|v| !v.is_empty()) .collect(); diff --git a/src/obisys/src/stage.rs b/src/obisys/src/stage.rs index 91608cac..705e2c86 100644 --- a/src/obisys/src/stage.rs +++ b/src/obisys/src/stage.rs @@ -36,13 +36,13 @@ impl Stage { user_secs: tv_to_secs(end.ru_utime) - tv_to_secs(self.ru.ru_utime), sys_secs: tv_to_secs(end.ru_stime) - tv_to_secs(self.ru.ru_stime), max_rss_bytes: rss_to_bytes(&end), - minor_faults: delta(end.ru_minflt as i64, self.ru.ru_minflt as i64), - major_faults: delta(end.ru_majflt as i64, self.ru.ru_majflt as i64), - vol_ctx: delta(end.ru_nvcsw as i64, self.ru.ru_nvcsw as i64), - invol_ctx: delta(end.ru_nivcsw as i64, self.ru.ru_nivcsw as i64), - in_blocks: delta(end.ru_inblock as i64, self.ru.ru_inblock as i64), - out_blocks: delta(end.ru_oublock as i64, self.ru.ru_oublock as i64), - swaps: delta(end.ru_nswap as i64, self.ru.ru_nswap as i64), + minor_faults: delta(end.ru_minflt, self.ru.ru_minflt), + major_faults: delta(end.ru_majflt, self.ru.ru_majflt), + vol_ctx: delta(end.ru_nvcsw, self.ru.ru_nvcsw), + invol_ctx: delta(end.ru_nivcsw, self.ru.ru_nivcsw), + in_blocks: delta(end.ru_inblock, self.ru.ru_inblock), + out_blocks: delta(end.ru_oublock, self.ru.ru_oublock), + swaps: delta(end.ru_nswap, self.ru.ru_nswap), }; info!( stage = %stats.label, diff --git a/src/obitaxonomy/src/segment_pattern.rs b/src/obitaxonomy/src/segment_pattern.rs index 4b41ec62..f2054b34 100644 --- a/src/obitaxonomy/src/segment_pattern.rs +++ b/src/obitaxonomy/src/segment_pattern.rs @@ -46,6 +46,6 @@ impl SegmentPattern { /// Name must match exactly. If a rank is specified in the pattern, the /// segment's rank must match; otherwise any rank (or no rank) is accepted. pub fn matches(&self, seg: &TaxSegment) -> bool { - self.name == seg.name() && self.rank.as_deref().map_or(true, |r| seg.rank() == Some(r)) + self.name == seg.name() && self.rank.as_deref().is_none_or(|r| seg.rank() == Some(r)) } }