Skip to content
This repository was archived by the owner on Dec 6, 2024. It is now read-only.

Commit 7b8529f

Browse files
committed
style: Fix clippy warnings
1 parent 3b3e58c commit 7b8529f

14 files changed

+92
-113
lines changed

benches/array_bench.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@ use std::iter::FromIterator;
77
fn run_benchmark(c: &mut Criterion) {
88
let mut group = c.benchmark_group("bench-byte-array");
99
group.bench_function("from-bytes", |b| {
10-
b.iter(|| SSeq::from_bytes(b"AGTCCTCTGCATTTTG"))
10+
b.iter(|| SSeq::from_bytes(b"AGTCCTCTGCATTTTG"));
1111
});
1212
group.bench_function("from-bytes-unchecked", |b| {
13-
b.iter(|| SSeq::from_bytes_unchecked(b"AGTCCTCTGCATTTTG"))
13+
b.iter(|| SSeq::from_bytes_unchecked(b"AGTCCTCTGCATTTTG"));
1414
});
1515
group.bench_function("from-iter", |b| {
16-
b.iter(|| SSeq::from_iter(b"AGTCCTCTGCATTTTG"))
16+
b.iter(|| SSeq::from_iter(b"AGTCCTCTGCATTTTG"));
1717
});
1818
group.finish();
1919
}

benches/benchmarks.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -115,12 +115,12 @@ fn run_fastq_lz4_benchmark(c: &mut Criterion) {
115115
c.bench_function("bench-lz4-wc", |b| {
116116
b.iter(
117117
|| assert_eq!(lz4_count(INTERLEAVED_LZ4_FASTQ), 16000), // 16000 lines
118-
)
118+
);
119119
});
120120
c.bench_function("bench-lz4-read-pair-iter-count", |b| {
121121
b.iter(
122122
|| assert_eq!(read_pair_count(INTERLEAVED_LZ4_FASTQ), 2000), // 2000 read pairs
123-
)
123+
);
124124
});
125125
// let chemistry: ChemistryDef =
126126
// serde_json::from_reader(File::open("tests/rna_read/sc_vdj_chemistry.json").unwrap())
@@ -141,12 +141,12 @@ fn run_fastq_gz_benchmark(c: &mut Criterion) {
141141
c.bench_function("bench-gz-wc", |b| {
142142
b.iter(
143143
|| assert_eq!(gz_count(INTERLEAVED_GZ_FASTQ), 16000), // 16000 lines
144-
)
144+
);
145145
});
146146
c.bench_function("bench-gz-read-pair-iter-count", |b| {
147147
b.iter(
148148
|| assert_eq!(read_pair_count(INTERLEAVED_GZ_FASTQ), 2000), // 2000 read pairs
149-
)
149+
);
150150
});
151151
// let chemistry: ChemistryDef =
152152
// serde_json::from_reader(File::open("tests/rna_read/sc_vdj_chemistry.json").unwrap())
@@ -167,12 +167,12 @@ fn run_fastq_benchmark(c: &mut Criterion) {
167167
c.bench_function("bench-fastq-wc", |b| {
168168
b.iter(
169169
|| assert_eq!(simple_count(INTERLEAVED_FASTQ), 16000), // 16000 lines
170-
)
170+
);
171171
});
172172
c.bench_function("bench-fastq-read-pair-iter-count", |b| {
173173
b.iter(
174174
|| assert_eq!(read_pair_count(INTERLEAVED_FASTQ), 2000), // 2000 read pairs
175-
)
175+
);
176176
});
177177
// let chemistry: ChemistryDef =
178178
// serde_json::from_reader(File::open("tests/rna_read/sc_vdj_chemistry.json").unwrap())
@@ -222,7 +222,7 @@ fn sseq_serde_bincode(c: &mut Criterion) {
222222
let mut b = Vec::new();
223223
bincode::serialize_into(&mut b, &sseqs).unwrap();
224224
assert!(!b.is_empty());
225-
})
225+
});
226226
});
227227
}
228228

src/adapter_trimmer.rs

+7-12
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
//! Trim adapters from reads using a combination of
22
//! k-mer matches, sparse alignment and banded alignment.
3-
//! Inspired by the [cutadapt](https://cutadapt.readthedocs.io/)
4-
//! tool.
3+
//! Inspired by the [cutadapt](https://cutadapt.readthedocs.io/) tool.
54
//!
65
//! # Features/Limitations
7-
//! * Supports regular, anchored and non-internal, 3' and 5'
8-
//! adapter trimming
6+
//! * Supports regular, anchored and non-internal, 3' and 5' adapter trimming
97
//! * Linked adapters are not supported as of now
108
//! * Allowed error rate for the adapter is 10%
119
//!
@@ -23,13 +21,10 @@ use bio::alignment::pairwise::{self, MatchParams, Scoring};
2321
use bio::alignment::sparse;
2422
use bio::alignment::sparse::HashMapFx;
2523
use serde::{Deserialize, Serialize};
26-
use std::cmp::Ordering;
27-
use std::cmp::{max, min};
28-
use std::collections::HashMap;
29-
use std::collections::HashSet;
24+
use std::cmp::{max, min, Ordering};
25+
use std::collections::{HashMap, HashSet};
3026
use std::fmt::Debug;
3127
use std::hash::BuildHasher;
32-
use std::i32;
3328
use std::ops::Range;
3429

3530
type Aligner = pairwise::banded::Aligner<MatchParams>;
@@ -122,7 +117,7 @@ pub enum AdapterLoc {
122117
/// * `end`: whether it's a `FivePrime` adapter or a `ThreePrime` adapter
123118
/// * `location`: Specify the location of the adapter (See [`AdapterLoc`](enum.AdapterLoc.html))
124119
/// * `seq`: The sequence of the adapter as a `String`. One could use a `Vec<u8>` here, but
125-
/// chose a String for the ease of auto (de)serialization from a json file.
120+
/// choose a String for the ease of auto (de)serialization from a json file.
126121
///
127122
/// # Example
128123
/// The example below shows how you can create an `Adapter` from a JSON string
@@ -270,7 +265,7 @@ impl<'a> AdapterTrimmer<'a> {
270265
///
271266
/// Ouput:
272267
/// * `Option<TrimResult>`: `None` if the adapter is not found,
273-
/// otherwise `Some(TrimResult)` (See [`TrimResult`](struct.TrimResult.html))
268+
/// otherwise `Some(TrimResult)` (See [`TrimResult`](struct.TrimResult.html))
274269
pub fn find(&mut self, read: &[u8]) -> Option<TrimResult> {
275270
use bio::alignment::AlignmentOperation::{Del, Ins, Match, Subst};
276271

@@ -642,7 +637,7 @@ fn compute_path(
642637
{
643638
let mut max_l_score = pairwise::MIN_SCORE;
644639
let mut max_r_score = pairwise::MIN_SCORE;
645-
for &this_match in matches.iter() {
640+
for &this_match in matches {
646641
max_l_score = max(max_l_score, l_score(this_match));
647642
max_r_score = max(max_r_score, r_score(this_match));
648643
}

src/array.rs

+7-12
Original file line numberDiff line numberDiff line change
@@ -106,12 +106,11 @@ where
106106
*l = *r.borrow();
107107
len += 1;
108108
}
109-
if src.next().is_some() {
110-
panic!(
111-
"Error: Input iter exceeds capacity of {} bytes.",
112-
bytes.len()
113-
);
114-
}
109+
assert!(
110+
src.next().is_none(),
111+
"Error: Input iter exceeds capacity of {} bytes.",
112+
bytes.len()
113+
);
115114

116115
ByteArray {
117116
length: len,
@@ -200,9 +199,7 @@ where
200199
type Output = u8;
201200

202201
fn index(&self, index: usize) -> &Self::Output {
203-
if index >= self.length as usize {
204-
panic!("index out of bounds")
205-
}
202+
assert!(index < self.length as usize, "index out of bounds");
206203

207204
&self.bytes[index]
208205
}
@@ -213,9 +210,7 @@ where
213210
T: ArrayContent,
214211
{
215212
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
216-
if index >= self.length as usize {
217-
panic!("index out of bounds")
218-
}
213+
assert!(index < self.length as usize, "index out of bounds");
219214
&mut self.bytes[index]
220215
}
221216
}

src/background_iterator.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,7 @@ mod test {
9393
let v = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
9494

9595
let iter = (0..11usize).map(move |i| {
96-
if v[i] == 5 {
97-
panic!("simulated panic");
98-
}
96+
assert!(v[i] != 5, "simulated panic");
9997
v[i]
10098
});
10199

src/filenames/bcl2fastq.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,7 @@ mod tests_from_tenkit {
495495
#[test]
496496
fn test_sample_name_verification() -> Result<()> {
497497
let path = "tests/filenames/tenkit91";
498-
for &s in ["test_sample", "test_sample_suffix"].iter() {
498+
for &s in &["test_sample", "test_sample_suffix"] {
499499
let query = Bcl2FastqDef {
500500
fastq_path: path.to_string(),
501501
sample_name_spec: s.into(),

src/filenames/bcl_processor.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ impl FindFastqs for BclProcessorFastqDef {
7575
if self.sample_index_spec.matches(&bcl_proc.si)
7676
&& self.lane_spec.contains(bcl_proc.lane_mode())
7777
{
78-
res.push(fastqs)
78+
res.push(fastqs);
7979
}
8080
}
8181

src/filenames/fastq_dir.rs

+6-7
Original file line numberDiff line numberDiff line change
@@ -37,21 +37,20 @@ impl Bcl2FastqDir {
3737
});
3838
}
3939

40-
let is_lane_split = match fastq_data
40+
let Ok(is_lane_split) = fastq_data
4141
.iter()
4242
.map(|(g, _)| match g.lane_mode {
4343
LaneMode::NoLaneSplitting => false,
4444
LaneMode::SingleLane(_) => true,
4545
})
4646
.dedup()
4747
.exactly_one()
48-
{
49-
Ok(val) => val,
50-
Err(_) => bail!(
48+
else {
49+
bail!(
5150
"Some files in the fastq path {} are split by lane, while some are not. \
5251
This is not supported.",
5352
fastq_path.display()
54-
),
53+
);
5554
};
5655

5756
let samples = fastq_data.iter().map(|(g, _)| g.sample.clone()).collect();
@@ -230,7 +229,7 @@ impl FastqChecker {
230229

231230
let lane_spec = match lanes {
232231
None => LaneSpec::Any,
233-
Some(ref l) => LaneSpec::Lanes(l.iter().cloned().collect()),
232+
Some(l) => LaneSpec::Lanes(l.iter().copied().collect()),
234233
};
235234

236235
if bcl_dir
@@ -243,7 +242,7 @@ impl FastqChecker {
243242

244243
Ok(match sample_name_spec {
245244
SampleNameSpec::Names(names) => names,
246-
_ => unreachable!(),
245+
SampleNameSpec::Any => unreachable!(),
247246
})
248247
}
249248

src/illumina_header_info.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ impl InputFastqs {
3636
.ok_or_else(|| anyhow!("No Read1 in FASTQ data"))?;
3737

3838
let header = std::str::from_utf8(header)?;
39-
let header_prefix = header.split(|x: char| x == ' ' || x == '/').next();
39+
let header_prefix = header.split([' ', '/']).next();
4040
if header_prefix.is_none() {
4141
return Ok(None);
4242
}

src/lib.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@
44
//! Major functionality includes:
55
//! * Find groups FASTQs (R1/R2/I1/I2) following Illumina filename conventions
66
//! * Parsing flowcell information from Illumina FASTQ headers
7-
//! * High-speed FASTQ I/O (via the `fastq` crate), with careful validation of FASTQ correctness and good error message.
8-
//! * Containers for FASTQ read-pairs (along with index reads), providing access to 'technical' read components like cell barcode and
9-
//! UMI sequences.
7+
//! * High-speed FASTQ I/O (via the `fastq` crate), with careful validation of
8+
//! FASTQ correctness and good error message.
9+
//! * Containers for FASTQ read-pairs (along with index reads), providing access
10+
//! to 'technical' read components like cell barcode and UMI sequences.
1011
//! * Flexible read trimming inspired by `cutadapt`
1112
1213
#![deny(warnings, unused)]
@@ -35,8 +36,7 @@ use crate::read_pair_iter::{AnyReadPairIter, InputFastqs, ReadPairIter};
3536
pub use crate::squality::SQuality;
3637
pub use crate::sseq::SSeq;
3738
use anyhow::Error;
38-
pub use fastq::OwnedRecord;
39-
pub use fastq::Record;
39+
pub use fastq::{OwnedRecord, Record};
4040
pub use read_pair::WhichRead;
4141
use read_pair_iter::FastqError;
4242
use serde::{Deserialize, Serialize};

src/read_pair.rs

+26-34
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
//! including the primary 'R1' and 'R2' and index 'I1' and 'I2' reads.
55
66
use crate::WhichEnd;
7-
use anyhow::{bail, Result};
7+
use anyhow::{bail, ensure, Result};
88
use bytes::{Bytes, BytesMut};
99
use fastq::{OwnedRecord, Record};
1010
use serde::{Deserialize, Serialize};
@@ -186,9 +186,9 @@ impl RpRange {
186186
/// # Args
187187
/// * `read` - Specify `WhichRead`
188188
/// * `offset` - Start of the interval. Must be less than 2^15 (=32,768)
189-
/// * `len` - Optional length that determines the end of the interval. A
190-
/// value `None` indicates everything from `offset` until the end of the
191-
/// `read`. Must be less than 2^15 (=32,768)
189+
/// * `len` - Optional length that determines the end of the interval.
190+
/// A value `None` indicates everything from `offset` until the end of the `read`.
191+
/// Must be less than 2^15 (=32,768)
192192
///
193193
/// # Panics
194194
/// * If `offset` or `len` is >= `2^15`
@@ -205,11 +205,11 @@ impl RpRange {
205205
///
206206
/// # Tests
207207
/// * `test_rprange_invalid_offset()` - Test that this function panics with
208-
/// an offset that is too large
208+
/// an offset that is too large
209209
/// * `test_rprange_invalid_len()` - Test that this function panics with
210-
/// a length that is too large
210+
/// a length that is too large
211211
/// * `prop_test_rprange_representation()` - Test that arbitrary construction of RpRange
212-
/// stores the values correctly.
212+
/// stores the values correctly.
213213
pub fn new(read: WhichRead, offset: usize, len: Option<usize>) -> RpRange {
214214
assert!(offset < (1 << 15));
215215
let len_bits = match len {
@@ -296,7 +296,7 @@ impl RpRange {
296296
///
297297
/// # Tests
298298
/// * `test_rprange_intersect_panic()` - Make sure that this function panics
299-
/// if the reads do not match
299+
/// if the reads do not match
300300
/// * `test_rprange_intersect_both_open()` - Test a case when both lengths are not set
301301
/// * `test_rprange_intersect_self_open()` - Test a case when only self length is set
302302
/// * `test_rprange_intersect_other_open()` - Test a case when only other length is set
@@ -363,7 +363,7 @@ impl RpRange {
363363
/// * `test_shrink_invalid_range_3()`: Test for panic if shrink range start > end
364364
/// * `test_rprange_trivial_shrink()`: Test shrink to an empty range.
365365
/// * `prop_test_rprange_shrink()`: Test shrink for arbitrary values of
366-
/// `RpRange` and valid `shrink_range`
366+
/// `RpRange` and valid `shrink_range`
367367
pub fn shrink(&mut self, shrink_range: &ops::Range<usize>) {
368368
assert!(
369369
shrink_range.start <= shrink_range.end,
@@ -496,14 +496,12 @@ impl<'a> MutReadPair<'a> {
496496

497497
pub fn new<R: Record>(buffer: &'a mut BytesMut, rr: &[Option<R>; 4]) -> MutReadPair<'a> {
498498
let mut rp = MutReadPair::empty(buffer);
499-
500-
for (_rec, which) in rr.iter().zip(WhichRead::read_types().iter()) {
501-
if let Some(ref rec) = *_rec {
502-
rp.push_read(rec, *which)
499+
for (rec, which) in rr.iter().zip(WhichRead::read_types()) {
500+
if let Some(rec) = rec {
501+
rp.push_read(rec, which);
503502
}
504503
// default ReadOffsets is exists = false
505504
}
506-
507505
rp
508506
}
509507

@@ -600,32 +598,26 @@ impl ReadPair {
600598

601599
pub fn check_range(&self, range: &RpRange, region_name: &str) -> Result<()> {
602600
let req_len = range.offset() + range.len().unwrap_or(0);
603-
604-
match self.get(range.read(), ReadPart::Seq) {
605-
Some(read) => {
606-
if read.len() < req_len {
607-
bail!(
608-
"{} is expected in positions {}-{} in Read {}, but read is {} bp long.",
609-
region_name,
610-
range.offset(),
611-
req_len,
612-
range.read(),
613-
read.len()
614-
);
615-
} else {
616-
Ok(())
617-
}
618-
}
619-
None => bail!(
601+
let Some(read) = self.get(range.read(), ReadPart::Seq) else {
602+
bail!(
620603
"{region_name} is missing from FASTQ. Read {} is not present.",
621604
range.read()
622-
),
623-
}
605+
);
606+
};
607+
ensure!(
608+
read.len() >= req_len,
609+
"{region_name} is expected in positions {}-{} in Read {}, but read is {} bp long.",
610+
range.offset(),
611+
req_len,
612+
range.read(),
613+
read.len()
614+
);
615+
Ok(())
624616
}
625617

626618
pub fn to_owned_record(&self) -> HashMap<WhichRead, OwnedRecord> {
627619
let mut result = HashMap::new();
628-
for &which in WhichRead::read_types().iter() {
620+
for &which in &WhichRead::read_types() {
629621
if self.offsets[which as usize].exists {
630622
let w = self.offsets[which as usize];
631623
let rec = OwnedRecord {

0 commit comments

Comments
 (0)