Skip to content

Commit

Permalink
Clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
mobiusklein committed Nov 18, 2023
1 parent 228c6c1 commit 7556cc9
Show file tree
Hide file tree
Showing 15 changed files with 126 additions and 163 deletions.
4 changes: 1 addition & 3 deletions examples/mzcat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,7 @@ fn scan_file<

fn main() -> io::Result<()> {
let path = path::PathBuf::from(
env::args()
.skip(1)
.next()
env::args().nth(1)
.expect("Please pass an MS data file path"),
);
if let Some(ext) = path.extension() {
Expand Down
6 changes: 3 additions & 3 deletions src/io/infer_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ pub(crate) fn infer_from_path<P: Into<path::PathBuf>,>(path: P) -> (MassSpectrom
/// stream is GZIP compressed. This assumes the stream is seekable.
pub(crate) fn infer_from_stream<R: Read + Seek>(stream: &mut R) -> io::Result<(MassSpectrometryFormat, bool)> {
let mut buf = Vec::with_capacity(100);
let current_pos = stream.seek(io::SeekFrom::Current(0))?;
let current_pos = stream.stream_position()?;
stream.read_exact(buf.as_mut_slice())?;
let is_stream_gzipped = is_gzipped(buf.as_slice());
if is_stream_gzipped {
Expand Down Expand Up @@ -129,7 +129,7 @@ pub fn open_file<P: Into<path::PathBuf>>(path: P) -> io::Result<Box<dyn ScanSour
let reader = MzMLbReader::open_path(path);
match reader {
Ok(reader) => Ok(Box::new(reader)),
Err(e) => Err(e.into()),
Err(e) => Err(e),
}
}
_ => {
Expand Down Expand Up @@ -172,7 +172,7 @@ mod test {
assert_eq!(reader.len(), 48);

if let Some(spec) = reader.get_spectrum_by_index(10) {
let spec: Spectrum = spec.into();
let spec: Spectrum = spec;
assert!(spec.index() == 10);
assert!(spec.id() == "controllerType=0 controllerNumber=1 scan=11");
if let Some(data_arrays) = &spec.arrays {
Expand Down
52 changes: 21 additions & 31 deletions src/io/mgf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,26 +80,26 @@ struct SpectrumBuilderFlex<
deconvoluted_type: PhantomData<D>,
}

impl<C: CentroidPeakAdapting, D: DeconvolutedPeakAdapting> Into<BinaryArrayMap>
for SpectrumBuilderFlex<C, D>
impl<C: CentroidPeakAdapting, D: DeconvolutedPeakAdapting> From<SpectrumBuilderFlex<C, D>>
for BinaryArrayMap
{
fn into(self) -> BinaryArrayMap {
fn from(val: SpectrumBuilderFlex<C, D>) -> Self {
let mut arrays = BinaryArrayMap::new();
arrays.add(DataArray::wrap(
&ArrayType::MZArray,
BinaryDataArrayType::Float64,
vec_as_bytes(self.mz_array),
vec_as_bytes(val.mz_array),
));
arrays.add(DataArray::wrap(
&ArrayType::IntensityArray,
BinaryDataArrayType::Float32,
vec_as_bytes(self.intensity_array),
vec_as_bytes(val.intensity_array),
));
if self.has_charge > 0 {
if val.has_charge > 0 {
arrays.add(DataArray::wrap(
&ArrayType::ChargeArray,
BinaryDataArrayType::Int32,
vec_as_bytes(self.charge_array),
vec_as_bytes(val.charge_array),
));
}
arrays
Expand All @@ -116,8 +116,8 @@ impl<
spectrum.deconvoluted_peaks = Some(
self.mz_array
.into_iter()
.zip(self.intensity_array.into_iter())
.zip(self.charge_array.into_iter())
.zip(self.intensity_array)
.zip(self.charge_array)
.map(|((mz, inten), z)| {
DeconvolutedPeak {
neutral_mass: neutral_mass(mz, if z != 0 { z } else { 1 }),
Expand All @@ -133,7 +133,7 @@ impl<
spectrum.peaks = Some(
self.mz_array
.into_iter()
.zip(self.intensity_array.into_iter())
.zip(self.intensity_array)
.map(|(mz, inten)| {
CentroidPeak {
mz,
Expand Down Expand Up @@ -218,7 +218,7 @@ impl<
if first.is_numeric() {
let parts: Vec<&str> = PEAK_SEPERATOR.split(line).collect();
let nparts = parts.len();
if nparts < 2 || nparts > 3 {
if !(2..=3).contains(&nparts) {
self.state = MGFParserState::Error;
self.error = Some(MGFError::TooManyColumnsForPeakLine);
return None;
Expand Down Expand Up @@ -247,20 +247,17 @@ impl<
line: &str,
builder: &mut SpectrumBuilderFlex<C, D>,
) -> bool {
let peak_line = match self.parse_peak_from_line_flex(line, builder) {
Some(peak) => peak,
None => false,
};
let peak_line = self.parse_peak_from_line_flex(line, builder).unwrap_or(false);
if peak_line {
self.state = MGFParserState::Peaks;
true
} else if line == "END IONS" {
self.state = MGFParserState::Between;
true
} else if line.contains('=') {
let mut parts = line.splitn(2, '=');
let key = parts.next().unwrap();
let value = parts.next().unwrap();
let (key, value) = line.split_once('=').unwrap();


match key {
"TITLE" => builder.description.id = String::from(value),
"RTINSECONDS" => {
Expand All @@ -275,10 +272,7 @@ impl<
let mut parts = value.split_ascii_whitespace();
let mz: f64 = parts.next().unwrap().parse().unwrap();
let intensity: f32 = parts.next().unwrap().parse().unwrap();
let charge: Option<i32> = match parts.next() {
Some(c) => Some(c.parse().unwrap()),
None => None
};
let charge: Option<i32> = parts.next().map(|c| c.parse().unwrap());
builder.description.precursor = Some(Precursor {
ion: SelectedIon {
mz,
Expand Down Expand Up @@ -306,10 +300,7 @@ impl<
}

fn handle_peak_flex(&mut self, line: &str, builder: &mut SpectrumBuilderFlex<C, D>) -> bool {
let peak_line = match self.parse_peak_from_line_flex(line, builder) {
Some(peak) => peak,
None => false,
};
let peak_line = self.parse_peak_from_line_flex(line, builder).unwrap_or(false);
if peak_line {
true
} else if line == "END IONS" {
Expand Down Expand Up @@ -753,7 +744,7 @@ TITLE="#,
for param in precursor
.ion()
.params()
.into_iter()
.iter()
.chain(precursor.activation.params())
{
self.write_param(param)?;
Expand Down Expand Up @@ -827,12 +818,11 @@ impl<
return Ok(0);
}
self.write_header(spectrum)?;
if matches!(&spectrum.deconvoluted_peaks, Some(_)) {
if spectrum.deconvoluted_peaks.is_some() {
self.write_deconvoluted_centroids(spectrum)?;
} else if matches!(&spectrum.peaks, Some(_)) {
} else if spectrum.peaks.is_some() {
self.write_centroids(spectrum)?;
} else {
}
}
self.handle.write_all(b"END IONS\n")?;
Ok(0)
}
Expand Down
32 changes: 16 additions & 16 deletions src/io/mzml/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,7 @@ impl<'inner, 'outer: 'inner, C: CentroidLike + Default, D: DeconvolutedPeakAdapt
.to_string();
}
b"index" => {
self.index = (&String::from_utf8_lossy(&attr.value))
self.index = String::from_utf8_lossy(&attr.value)
.parse::<usize>()
.expect("Failed to parse index");
}
Expand Down Expand Up @@ -810,33 +810,33 @@ impl<'inner, 'outer: 'inner, C: CentroidLike + Default, D: DeconvolutedPeakAdapt
}
}

impl<'a, C: CentroidLike + Default, D: DeconvolutedPeakAdapting> Into<CentroidSpectrumType<C>>
for MzMLSpectrumBuilder<'a, C, D>
impl<'a, C: CentroidLike + Default, D: DeconvolutedPeakAdapting> From<MzMLSpectrumBuilder<'a, C, D>>
for CentroidSpectrumType<C>
where
MZPeakSetType<C>: BuildFromArrayMap + BuildArrayMapFrom,
MassPeakSetType<D>: BuildFromArrayMap + BuildArrayMapFrom,
{
fn into(self) -> CentroidSpectrumType<C> {
fn from(val: MzMLSpectrumBuilder<'a, C, D>) -> Self {
let mut spec = MultiLayerSpectrum::<C, D>::default();
self.into_spectrum(&mut spec);
val.into_spectrum(&mut spec);
spec.try_into().unwrap()
}
}

impl<'a, C: CentroidPeakAdapting, D: DeconvolutedPeakAdapting> Into<MultiLayerSpectrum<C, D>>
for MzMLSpectrumBuilder<'a, C, D>
impl<'a, C: CentroidPeakAdapting, D: DeconvolutedPeakAdapting> From<MzMLSpectrumBuilder<'a, C, D>>
for MultiLayerSpectrum<C, D>
{
fn into(self) -> MultiLayerSpectrum<C, D> {
fn from(val: MzMLSpectrumBuilder<'a, C, D>) -> Self {
let mut spec = MultiLayerSpectrum::<C, D>::default();
self.into_spectrum(&mut spec);
val.into_spectrum(&mut spec);
spec
}
}

impl<'a> Into<RawSpectrum> for MzMLSpectrumBuilder<'a> {
fn into(self) -> RawSpectrum {
impl<'a> From<MzMLSpectrumBuilder<'a>> for RawSpectrum {
fn from(val: MzMLSpectrumBuilder<'a>) -> Self {
let mut spec = Spectrum::default();
self.into_spectrum(&mut spec);
val.into_spectrum(&mut spec);
spec.into()
}
}
Expand Down Expand Up @@ -1021,7 +1021,7 @@ impl<
self.instrument_configurations = accumulator
.instrument_configurations
.into_iter()
.map(|ic| (ic.id.clone(), ic))
.map(|ic| (ic.id, ic))
.collect();
self.softwares = accumulator.softwares;
self.data_processings = accumulator.data_processings;
Expand Down Expand Up @@ -1712,7 +1712,7 @@ mod test {
panic!("Failed to parse out index {:?}", err);
}
};
assert!(reader.index.len() > 0);
assert!(!reader.index.is_empty());
Ok(())
}

Expand Down Expand Up @@ -1745,9 +1745,9 @@ mod test {
<offset idRef="controllerType=0 controllerNumber=1 scan=4">461270</offset>
<offset idRef="controllerType=0 controllerNumber=1 scan=5">476248</offset>
"#;
for line in needle.split("\n") {
for line in needle.split('\n') {
assert!(
decoded.contains(&line),
decoded.contains(line),
"Failed to find {} in {}",
line,
decoded
Expand Down
2 changes: 1 addition & 1 deletion src/io/mzml/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,7 @@ where
let mut keys: Vec<_> = self.instrument_configurations.keys().collect();
keys.sort();
if let Some(ic_ref) = keys.first() {
let inst_id = instrument_id(&ic_ref);
let inst_id = instrument_id(ic_ref);
attrib!("defaultInstrumentConfigurationRef", inst_id, run);
}
if let Some(sf_ref) = self.file_description.source_files.first() {
Expand Down
36 changes: 16 additions & 20 deletions src/io/mzmlb/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,8 @@ impl CacheInterval {

#[inline]
pub fn contains(&self, start: usize, end: usize) -> bool {
if self.start <= start {
if end < self.end {
return true;
}
if self.start <= start && end < self.end {
return true;
}
false
}
Expand Down Expand Up @@ -134,11 +132,11 @@ impl Default for ExternalDataRegistry {

impl ExternalDataRegistry {
pub fn new(chunk_size: usize) -> Self {
let inst = Self {

Self {
chunk_size,
..Default::default()
};
inst
}
}

fn default_chunk_size() -> usize {
Expand Down Expand Up @@ -364,15 +362,15 @@ impl ExternalDataRegistry {
if let Some(dset) = self.registry.get(&range_request.name).as_ref() {
let dtype = dset.dtype()?;
let block_end = (start + self.chunk_size).min(dset.size());
let cache_block = Self::read_slice_to_bytes(&dset, start, block_end)?;
let cache_block = Self::read_slice_to_bytes(dset, start, block_end)?;
let cache_block = DataArray::wrap(&destination.name, dtype.into(), cache_block);
let mut cache_block = CacheInterval::new(start, block_end, cache_block);
let block = if let Some(cache_block) = self
.chunk_cache
.get_mut(&range_request.name)
.and_then(|prev| {
.map(|prev| {
mem::swap(prev, &mut cache_block);
Some(prev)
prev
}) {
debug!(
"Updated {} cache block: {:?}",
Expand Down Expand Up @@ -499,16 +497,14 @@ impl<'a, C: CentroidPeakAdapting, D: DeconvolutedPeakAdapting> MzMLSAX
match param.accession.unwrap() {
// external HDF5 dataset
1002841 => {
if self.current_data_range_query.name.len() == 0
&& !param.value.starts_with("/")
if self.current_data_range_query.name.is_empty()
&& !param.value.starts_with('/')
{
self.current_data_range_query
.name
.extend("/".chars());
.name.push('/');
}
self.current_data_range_query
.name
.extend(param.value.chars());
.name.push_str(&param.value);
}
// external offset
1002842 => {
Expand Down Expand Up @@ -551,7 +547,7 @@ impl<'a, C: CentroidPeakAdapting, D: DeconvolutedPeakAdapting> MzMLSAX
let elt_name = event.name();
let res = match elt_name.as_ref() {
b"binaryDataArray" => {
if self.current_data_range_query.name.len() == 0 {
if self.current_data_range_query.name.is_empty() {
return Err(MzMLParserError::IncompleteElementError(
"The external data array name was missing or empty".to_owned(),
MzMLParserState::BinaryDataArray,
Expand Down Expand Up @@ -711,14 +707,14 @@ impl<'a, 'b: 'a, C: CentroidPeakAdapting, D: DeconvolutedPeakAdapting> MzMLbRead

let inst = Self {
handle,
index: index,
index,
file_description: mzml_parser.file_description.clone(),
instrument_configurations: mzml_parser.instrument_configurations.clone(),
softwares: mzml_parser.softwares.clone(),
data_processings: mzml_parser.data_processings.clone(),
mzml_parser,
schema_version,
data_buffers: data_buffers,
data_buffers,
};

Ok(inst)
Expand Down Expand Up @@ -782,7 +778,7 @@ impl<'a, 'b: 'a, C: CentroidPeakAdapting, D: DeconvolutedPeakAdapting> MzMLbRead
};

idx_splits.zip(offsets).for_each(|(id, off)| {
if id.len() == 0 || off == 0 {
if id.is_empty() || off == 0 {
return;
}
index.insert(
Expand Down
8 changes: 3 additions & 5 deletions src/io/mzmlb/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ impl ToString for BufferName {
ArrayType::RawIonMobilityArray => Cow::Borrowed("raw_ion_mobility"),
ArrayType::DeconvolutedIonMobilityArray => Cow::Borrowed("deconvoluted_ion_mobility"),
ArrayType::NonStandardDataArray { name } => {
Cow::Owned(name.replace("/", "_").replace(" ", "_"))
Cow::Owned(name.replace(['/', ' '], "_"))
}
};
let dtype = match self.dtype {
Expand Down Expand Up @@ -413,7 +413,7 @@ where
handle,
mzml_writer,
buffers: HashMap::new(),
chunk_size: chunk_size,
chunk_size,
filters: Self::zlib_compression(9),
})
}
Expand Down Expand Up @@ -703,9 +703,7 @@ where
fn finalize_data_buffers(&mut self) -> WriterResult {
let result: WriterResult = self
.buffers
.iter_mut()
.map(|(_, v)| -> WriterResult { v.flush(true) })
.collect();
.iter_mut().try_for_each(|(_, v)| -> WriterResult { v.flush(true) });
result?;
Ok(())
}
Expand Down
Loading

0 comments on commit 7556cc9

Please sign in to comment.