From 214945d6c9b6ea8ee0567540eb56f6249f49d342 Mon Sep 17 00:00:00 2001 From: Ben Pfaff Date: Thu, 28 Aug 2025 17:01:58 -0700 Subject: [PATCH] rust: Fix clippy warnings. --- rust/pspp/src/convert.rs | 10 ++--- rust/pspp/src/crypto/mod.rs | 9 ++-- rust/pspp/src/data.rs | 19 +++++---- rust/pspp/src/data/encoded.rs | 10 ++--- rust/pspp/src/dictionary.rs | 65 ++++++++++++++--------------- rust/pspp/src/format/display/mod.rs | 8 ++-- rust/pspp/src/hexfloat.rs | 2 +- rust/pspp/src/lex/command_name.rs | 4 +- rust/pspp/src/message.rs | 2 +- rust/pspp/src/output/csv.rs | 2 +- rust/pspp/src/output/driver.rs | 12 +++--- rust/pspp/src/output/mod.rs | 7 +--- rust/pspp/src/output/pivot/mod.rs | 10 +++-- rust/pspp/src/output/spv.rs | 21 ++++------ rust/pspp/src/output/text.rs | 10 ++--- rust/pspp/src/sys/cooked.rs | 6 +-- rust/pspp/src/sys/raw.rs | 30 +++++++------ rust/pspp/src/sys/raw/records.rs | 27 ++++++------ rust/pspp/src/sys/write.rs | 26 ++++++------ rust/pspp/src/util.rs | 2 +- rust/pspp/src/variable.rs | 8 ++-- 21 files changed, 144 insertions(+), 146 deletions(-) diff --git a/rust/pspp/src/convert.rs b/rust/pspp/src/convert.rs index 879265ff71..949331282d 100644 --- a/rust/pspp/src/convert.rs +++ b/rust/pspp/src/convert.rs @@ -117,14 +117,14 @@ impl CsvOptions { W: Write, { if self.labels - && let Some(label) = variable.value_labels.get(&datum) + && let Some(label) = variable.value_labels.get(datum) { writer.write_field(label) } else if datum.is_sysmis() { writer.write_field(" ") } else if self.print_formats || datum.is_string() { writer.write_field( - &datum + datum .display(variable.print_format) .with_trimming() .to_small_string::<64>(), @@ -150,7 +150,7 @@ impl CsvOptions { | Type::RBHex | Type::WkDay | Type::Month => writer.write_field( - &number + number .display_plain() .with_decimal(self.decimal) .to_small_string::<64>(), @@ -169,7 +169,7 @@ impl CsvOptions { calendar_offset_to_gregorian(number / 60.0 / 60.0 / 24.0) { writer.write_field( - &format_args!( + format_args!( "{:02}/{:02}/{:04}", date.month(), date.day(), @@ -192,7 +192,7 @@ impl CsvOptions { ) { writer.write_field( - &format_args!( + format_args!( "{:02}/{:02}/{:04} {:02}:{:02}:{:02}", date.month(), date.day(), diff --git a/rust/pspp/src/crypto/mod.rs b/rust/pspp/src/crypto/mod.rs index 8685f938af..c2e86cdea1 100644 --- a/rust/pspp/src/crypto/mod.rs +++ b/rust/pspp/src/crypto/mod.rs @@ -220,7 +220,7 @@ where // Decrypt first block to verify password. let mut out = [0; 16]; aes.decrypt_block_b2b( - &GenericArray::from_slice(&self.first_block), + GenericArray::from_slice(&self.first_block), GenericArray::from_mut_slice(&mut out), ); static MAGIC: &[&[u8]] = &[ @@ -229,13 +229,13 @@ where b"* Encoding", b"PK\x03\x04\x14\0\x08", ]; - if !MAGIC.iter().any(|magic| out.starts_with(*magic)) { + if !MAGIC.iter().any(|magic| out.starts_with(magic)) { return Err(self); } // Decrypt last block to check padding and get final length. aes.decrypt_block_b2b( - &GenericArray::from_slice(&self.last_block), + GenericArray::from_slice(&self.last_block), GenericArray::from_mut_slice(&mut out), ); let Some(padding_length) = parse_padding(&out) else { @@ -537,8 +537,7 @@ impl EncodedPassword { input .iter() .copied() - .map(|byte| [encode_byte(&AH, &AL, byte), encode_byte(&BH, &BL, byte)]) - .flatten() + .flat_map(|byte| [encode_byte(&AH, &AL, byte), encode_byte(&BH, &BL, byte)]) .collect(), ) } diff --git a/rust/pspp/src/data.rs b/rust/pspp/src/data.rs index 0fb311cf5f..28ad0521a7 100644 --- a/rust/pspp/src/data.rs +++ b/rust/pspp/src/data.rs @@ -157,13 +157,13 @@ impl ByteStr { } } -impl<'a> RawString for &'a ByteStr { +impl RawString for &ByteStr { fn raw_string_bytes(&self) -> &[u8] { &self.0 } } -impl<'a> Serialize for &'a ByteStr { +impl Serialize for &ByteStr { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, @@ -353,7 +353,7 @@ impl Debug for ByteString { // (actually bytes interpreted as Unicode code points). fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { let s = - from_utf8(&self.0.borrow()).map_or_else(|_| decode_latin1(self.0.borrow()), Cow::from); + from_utf8(self.0.borrow()).map_or_else(|_| decode_latin1(self.0.borrow()), Cow::from); write!(f, "{s:?}") } } @@ -446,7 +446,7 @@ where match self { Self::Number(Some(number)) => write!(f, "{number:?}"), Self::Number(None) => write!(f, "SYSMIS"), - Self::String(s) => write!(f, "{:?}", s), + Self::String(s) => write!(f, "{s:?}"), } } } @@ -538,7 +538,7 @@ impl Datum { pub fn as_ref(&self) -> Datum<&B> { match self { Datum::Number(number) => Datum::Number(*number), - Datum::String(string) => Datum::String(&string), + Datum::String(string) => Datum::String(string), } } @@ -701,7 +701,9 @@ impl Datum { where T: MutRawString, { - self.as_string_mut().map(|s| s.trim_end()); + if let Some(s) = self.as_string_mut() { + s.trim_end() + } } /// Resizes this datum to the given `width`. Returns an error, without @@ -780,6 +782,9 @@ impl Case where B: Borrow<[Datum]>, { + pub fn is_empty(&self) -> bool { + self.len() == 0 + } pub fn len(&self) -> usize { self.data.borrow().len() } @@ -851,7 +856,7 @@ where fn into_iter(self) -> Self::IntoIter { CaseIter { encoding: self.encoding, - iter: self.data.borrow().into_iter(), + iter: self.data.borrow().iter(), } } } diff --git a/rust/pspp/src/data/encoded.rs b/rust/pspp/src/data/encoded.rs index 2cc1a22eff..a76d85e944 100644 --- a/rust/pspp/src/data/encoded.rs +++ b/rust/pspp/src/data/encoded.rs @@ -126,7 +126,7 @@ pub trait EncodedString: Encoded + RawString + Display + Debug { } } -impl<'a> EncodedString for &'a str { +impl EncodedString for &str { fn as_str(&self) -> Cow<'_, str> { Cow::from(*self) } @@ -138,21 +138,21 @@ impl<'a> EncodedString for &'a str { impl EncodedString for String { fn as_str(&self) -> Cow<'_, str> { - Cow::from(String::as_str(&self)) + Cow::from(String::as_str(self)) } fn to_encoding(&self, encoding: &'static Encoding) -> WithEncoding> { - WithEncoding::new(ByteCow(encoding.encode(&self).0), encoding) + WithEncoding::new(ByteCow(encoding.encode(self).0), encoding) } } impl EncodedString for &'_ String { fn as_str(&self) -> Cow<'_, str> { - Cow::from(String::as_str(&self)) + Cow::from(String::as_str(self)) } fn to_encoding(&self, encoding: &'static Encoding) -> WithEncoding> { - WithEncoding::new(ByteCow(encoding.encode(String::as_str(&self)).0), encoding) + WithEncoding::new(ByteCow(encoding.encode(String::as_str(self)).0), encoding) } } diff --git a/rust/pspp/src/dictionary.rs b/rust/pspp/src/dictionary.rs index 84d86da398..7a0088a47e 100644 --- a/rust/pspp/src/dictionary.rs +++ b/rust/pspp/src/dictionary.rs @@ -101,27 +101,16 @@ impl PartialEq for Dictionary { fn eq(&self, other: &Self) -> bool { // We have to compare the dereferenced versions of fields that use // [ByIdentifier. Otherwise we would just be comparing their names. - self.variables - .iter() - .map(|var| &*var) - .eq(other.variables.iter().map(|var| &*var)) + self.variables.iter().eq(other.variables.iter()) && self.split_file == other.split_file && self.weight == other.weight && self.filter == other.filter && self.case_limit == other.case_limit && self.file_label == other.file_label && self.documents == other.documents - && self - .vectors - .iter() - .map(|vector| &*vector) - .eq(other.vectors.iter().map(|vector| &*vector)) + && self.vectors.iter().eq(other.vectors.iter()) && self.attributes == other.attributes - && self - .mrsets - .iter() - .map(|mrset| &*mrset) - .eq(other.mrsets.iter().map(|mrset| &*mrset)) + && self.mrsets.iter().eq(other.mrsets.iter()) && self.variable_sets == other.variable_sets && self.encoding == other.encoding } @@ -495,7 +484,7 @@ impl Dictionary { values.push( self.file_label .as_ref() - .map(|label| Value::new_user_text(label)) + .map(Value::new_user_text) .unwrap_or_default(), ); @@ -617,7 +606,7 @@ impl Dictionary { for (variable, short_names) in self.variables.iter().zip(short_names.iter_mut()) { if short_names[0].is_none() && let Some(short_name) = variable.short_names.first() - && !used_names.contains(&short_name) + && !used_names.contains(short_name) { used_names.insert(short_name.clone()); short_names[0] = Some(short_name.clone()); @@ -627,7 +616,7 @@ impl Dictionary { for (index, assigned_short_name) in short_names.iter_mut().enumerate().skip(1) { if assigned_short_name.is_none() && let Some(short_name) = variable.short_names.get(index) - && !used_names.contains(&short_name) + && !used_names.contains(short_name) { used_names.insert(short_name.clone()); *assigned_short_name = Some(short_name.clone()); @@ -754,7 +743,7 @@ impl<'a> OutputVariables<'a> { fn get_field_value(index: usize, variable: &Variable, field: VariableField) -> Option { match field { VariableField::Position => Some(Value::new_integer(Some(index as f64 + 1.0))), - VariableField::Label => variable.label().map(|label| Value::new_user_text(label)), + VariableField::Label => variable.label().map(Value::new_user_text), VariableField::Measure => variable .measure .map(|measure| Value::new_text(measure.as_str())), @@ -1153,6 +1142,7 @@ impl<'a> MappedVariables<'a> { Ok(Self::new_unchecked(dictionary, dict_indexes)) } + #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> usize { self.dict_indexes.len() } @@ -1176,7 +1166,7 @@ impl<'a> Index for MappedVariables<'a> { type Output = Variable; fn index(&self, index: usize) -> &Self::Output { - &*self.dictionary.variables[self.dict_indexes[index]] + &self.dictionary.variables[self.dict_indexes[index]] } } @@ -1274,6 +1264,9 @@ impl<'a> Vectors<'a> { fn new(dictionary: &'a Dictionary) -> Self { Self(dictionary) } + pub fn is_empty(&self) -> bool { + self.0.vectors.is_empty() + } pub fn len(&self) -> usize { self.0.vectors.len() } @@ -1281,7 +1274,7 @@ impl<'a> Vectors<'a> { self.0 .vectors .get(&name.0) - .map(|vector| Vector::new_unchecked(self.0, &*vector)) + .map(|vector| Vector::new_unchecked(self.0, vector)) } pub fn iter(&self) -> VectorsIter<'a> { VectorsIter::new(self.0) @@ -1340,6 +1333,9 @@ impl<'a> VariableSets<'a> { fn new(dictionary: &'a Dictionary) -> Self { Self(dictionary) } + pub fn is_empty(&self) -> bool { + self.0.variable_sets.is_empty() + } pub fn len(&self) -> usize { self.0.variable_sets.len() } @@ -1349,7 +1345,7 @@ impl<'a> VariableSets<'a> { .get(index) .map(|variable_set| VariableSet { dictionary: self.0, - variable_set: &*variable_set, + variable_set, }) } pub fn iter(&self) -> VariableSetsIter<'a> { @@ -1460,6 +1456,10 @@ impl<'a> MultipleResponseSets<'a> { Self(dictionary) } + pub fn is_empty(&self) -> bool { + self.0.mrsets.is_empty() + } + pub fn len(&self) -> usize { self.0.mrsets.len() } @@ -1661,26 +1661,25 @@ pub enum MultipleResponseType { impl MultipleResponseType { pub fn supported_before_v14(&self) -> bool { - match self { + !matches!( + self, MultipleResponseType::MultipleDichotomy { labels: CategoryLabels::CountedValues { .. }, datum: _, - } => false, - _ => true, - } + } + ) } pub fn label_from_var_label(&self) -> bool { - match self { + matches!( + self, MultipleResponseType::MultipleDichotomy { - labels: - CategoryLabels::CountedValues { - use_var_label_as_mrset_label: true, - }, + labels: CategoryLabels::CountedValues { + use_var_label_as_mrset_label: true, + }, .. - } => true, - _ => false, - } + } + ) } } diff --git a/rust/pspp/src/format/display/mod.rs b/rust/pspp/src/format/display/mod.rs index c86e434be8..5b3bbe2ccc 100644 --- a/rust/pspp/src/format/display/mod.rs +++ b/rust/pspp/src/format/display/mod.rs @@ -134,7 +134,7 @@ where } } -impl<'a, 'b, B> Display for DisplayDatum<'b, B> +impl<'b, B> Display for DisplayDatum<'b, B> where B: EncodedString, { @@ -275,7 +275,7 @@ where "Unknown" }; let w = if self.trim_spaces { 0 } else { self.format.w() }; - write!(f, "{s:>0$.*}", w) + write!(f, "{s:>w$.w$}") } else { self.overflow(f) } @@ -645,7 +645,7 @@ where } else if excess_width >= 5 { let d = min(self.format.d(), excess_width as usize - 4); let w = d + 3; - write!(&mut output, ":{:02$.*}", d, time, w).unwrap(); + write!(&mut output, ":{time:0w$.d$}").unwrap(); if self.settings.decimal == Decimal::Comma { fix_decimal_point(&mut output); } @@ -695,7 +695,7 @@ where match self.to_binary() { Some(binary) => w.write_all(&binary), None if encoding == UTF_8 => { - write!(&mut w, "{}", self) + write!(&mut w, "{self}") } None => w.write_all(&encoding.encode(&self.to_small_string::<64>()).0), } diff --git a/rust/pspp/src/hexfloat.rs b/rust/pspp/src/hexfloat.rs index a38189e6ef..25bb1d3e45 100644 --- a/rust/pspp/src/hexfloat.rs +++ b/rust/pspp/src/hexfloat.rs @@ -32,7 +32,7 @@ impl Display for HexFloat { _ => (), }; let (significand, mut exponent, _) = self.0.integer_decode(); - let mut hex_sig = format!("{:x}", significand); + let mut hex_sig = format!("{significand:x}"); while hex_sig.ends_with('0') { hex_sig.pop(); exponent += 4; diff --git a/rust/pspp/src/lex/command_name.rs b/rust/pspp/src/lex/command_name.rs index 327f7cbf45..dfde500ada 100644 --- a/rust/pspp/src/lex/command_name.rs +++ b/rust/pspp/src/lex/command_name.rs @@ -67,8 +67,8 @@ pub struct Match { /// function returns `None`. /// /// 4. Otherwise, `string` and `command` match. Returns a [Match] with -/// `missing_words` set to `n - m` and `exact` set based on whether any of -/// the words in the command name were abbreviated. +/// `missing_words` set to `n - m` and `exact` set based on whether any of +/// the words in the command name were abbreviated. pub fn command_match(command: &str, string: &str) -> Option { let mut command_words = command.split_whitespace(); let mut string_words = string.split_whitespace(); diff --git a/rust/pspp/src/message.rs b/rust/pspp/src/message.rs index 97bcc90b84..28d0a9911a 100644 --- a/rust/pspp/src/message.rs +++ b/rust/pspp/src/message.rs @@ -84,7 +84,7 @@ pub struct Location { impl Display for Location { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { if let Some(file_name) = &self.file_name { - write!(f, "{}", file_name)?; + f.write_str(file_name)?; } if let Some(span) = &self.span { diff --git a/rust/pspp/src/output/csv.rs b/rust/pspp/src/output/csv.rs index 5e65b0b75e..0626d90eb2 100644 --- a/rust/pspp/src/output/csv.rs +++ b/rust/pspp/src/output/csv.rs @@ -131,7 +131,7 @@ impl CsvDriver { pub fn new(config: &CsvConfig) -> std::io::Result { Ok(Self { file: BufWriter::new(File::create(&config.file)?), - options: config.options.clone(), + options: config.options, n_items: 0, }) } diff --git a/rust/pspp/src/output/driver.rs b/rust/pspp/src/output/driver.rs index 963661146e..5d97660126 100644 --- a/rust/pspp/src/output/driver.rs +++ b/rust/pspp/src/output/driver.rs @@ -67,27 +67,27 @@ pub trait Driver { impl Driver for Box { fn name(&self) -> Cow<'static, str> { - (&**self).name() + (**self).name() } fn write(&mut self, item: &Arc) { - (&mut **self).write(item); + (**self).write(item); } fn setup(&mut self, page_setup: &PageSetup) -> bool { - (&mut **self).setup(page_setup) + (**self).setup(page_setup) } fn flush(&mut self) { - (&mut **self).flush(); + (**self).flush(); } fn handles_show(&self) -> bool { - (&**self).handles_show() + (**self).handles_show() } fn handles_groups(&self) -> bool { - (&**self).handles_groups() + (**self).handles_groups() } } diff --git a/rust/pspp/src/output/mod.rs b/rust/pspp/src/output/mod.rs index 28ab4efdd6..c1e061ed9b 100644 --- a/rust/pspp/src/output/mod.rs +++ b/rust/pspp/src/output/mod.rs @@ -76,7 +76,7 @@ impl Item { label: None, command_name: details.command_name().cloned(), show: true, - details: details, + details, } } @@ -141,10 +141,7 @@ impl Details { } pub fn is_page_break(&self) -> bool { - match self { - Self::PageBreak => true, - _ => false, - } + matches!(self, Self::PageBreak) } } diff --git a/rust/pspp/src/output/pivot/mod.rs b/rust/pspp/src/output/pivot/mod.rs index 6eed68e518..92133e2c51 100644 --- a/rust/pspp/src/output/pivot/mod.rs +++ b/rust/pspp/src/output/pivot/mod.rs @@ -660,6 +660,10 @@ impl Category { } } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + pub fn len(&self) -> usize { match self { Category::Group(group) => group.len, @@ -1600,7 +1604,7 @@ impl PivotTable { pub fn title(&self) -> &Value { match &self.title { - Some(title) => &*title, + Some(title) => title, None => { static EMPTY: Value = Value::empty(); &EMPTY @@ -1610,7 +1614,7 @@ impl PivotTable { pub fn subtype(&self) -> &Value { match &self.subtype { - Some(subtype) => &*subtype, + Some(subtype) => subtype, None => { static EMPTY: Value = Value::empty(); &EMPTY @@ -2755,7 +2759,7 @@ impl Serialize for MetadataEntry { MetadataValue::Leaf(value) => { let mut map = serializer.serialize_map(Some(1))?; let name = self.name.display(()).to_string(); - map.serialize_entry(&name, &BareValue(&value))?; + map.serialize_entry(&name, &BareValue(value))?; map.end() } MetadataValue::Group(items) => { diff --git a/rust/pspp/src/output/spv.rs b/rust/pspp/src/output/spv.rs index 8c44fe18ba..89ae457544 100644 --- a/rust/pspp/src/output/spv.rs +++ b/rust/pspp/src/output/spv.rs @@ -194,7 +194,7 @@ where super::Details::Group(children) => { let mut attributes = Vec::::new(); if let Some(command_name) = &item.command_name { - attributes.push((("commandName", command_name.as_str())).into()); + attributes.push(("commandName", command_name.as_str()).into()); } if !item.show { attributes.push(("visibility", "collapsed").into()); @@ -218,14 +218,14 @@ where super::Details::PageBreak => { self.needs_page_break = true; } - super::Details::Table(pivot_table) => self.write_table(&*item, pivot_table, structure), + super::Details::Table(pivot_table) => self.write_table(item, pivot_table, structure), super::Details::Text(text) => self.write_text(item, text, structure), } } - fn container<'a, X, F>( + fn container( &mut self, - writer: &'a mut XmlWriter, + writer: &mut XmlWriter, item: &Item, inner_elem: &str, closure: F, @@ -590,7 +590,7 @@ where X: Write, { fn inches<'a>(x: f64) -> Cow<'a, str> { - Cow::from(format!("{:.2}in", x)) + Cow::from(format!("{x:.2}in")) } writer @@ -1222,13 +1222,10 @@ impl<'a> BinWrite for ValueMod<'a> { style .style .as_ref() - .map_or_else( - || StylePair::default(), - |area_style| StylePair { - font_style: Some(&area_style.font_style), - cell_style: Some(&area_style.cell_style), - }, - ) + .map_or_else(StylePair::default, |area_style| StylePair { + font_style: Some(&area_style.font_style), + cell_style: Some(&area_style.cell_style), + }) .write_options(writer, endian, args)?; v3_start.finish_le32(writer) } else { diff --git a/rust/pspp/src/output/text.rs b/rust/pspp/src/output/text.rs index 1a5aad6d8e..af00cfcc68 100644 --- a/rust/pspp/src/output/text.rs +++ b/rust/pspp/src/output/text.rs @@ -51,8 +51,8 @@ pub enum Boxes { impl Boxes { fn box_chars(&self) -> &'static BoxChars { match self { - Boxes::Ascii => &*ASCII_BOX, - Boxes::Unicode => &*UNICODE_BOX, + Boxes::Ascii => &ASCII_BOX, + Boxes::Unicode => &UNICODE_BOX, } } } @@ -366,7 +366,7 @@ impl TextDriver { pub fn new(config: &TextConfig) -> std::io::Result { Ok(Self { file: BufWriter::new(match &config.file { - Some(file) => File::create(&file)?, + Some(file) => File::create(file)?, None => File::options().write(true).open("/dev/stdout")?, }), renderer: TextRenderer::new(&config.options), @@ -393,7 +393,7 @@ impl TextRenderer { } Details::Message(_diagnostic) => todo!(), Details::PageBreak => Ok(()), - Details::Table(pivot_table) => self.render_table(&*pivot_table, writer), + Details::Table(pivot_table) => self.render_table(pivot_table, writer), Details::Text(text) => self.render_table(&PivotTable::from((**text).clone()), writer), } } @@ -411,7 +411,7 @@ impl TextRenderer { while pager.has_next(self) { pager.draw_next(self, usize::MAX); for line in self.lines.drain(..) { - writeln!(writer, "{}", line)?; + writeln!(writer, "{line}")?; } } } diff --git a/rust/pspp/src/sys/cooked.rs b/rust/pspp/src/sys/cooked.rs index c4f5878206..abb18fd599 100644 --- a/rust/pspp/src/sys/cooked.rs +++ b/rust/pspp/src/sys/cooked.rs @@ -820,7 +820,7 @@ impl Records { } }; - if let Some(float_info) = self.float_info.get(0) { + if let Some(float_info) = self.float_info.first() { for (expected, expected2, actual, name) in [ (f64::MIN, None, float_info.sysmis, "SYSMIS"), (f64::MAX, None, float_info.highest, "HIGHEST"), @@ -846,7 +846,7 @@ impl Records { if n_vars != nominal_case_size as usize && self .integer_info - .get(0) + .first() .is_none_or(|info| info.inner.version.0 != 13) { warn(Error::WrongVariablePositions { @@ -1442,7 +1442,7 @@ impl Metadata { values.push( self.product_ext .as_ref() - .map(|product_ext| Value::new_user_text(product_ext)) + .map(Value::new_user_text) .unwrap_or_default(), ); product.push("Version"); diff --git a/rust/pspp/src/sys/raw.rs b/rust/pspp/src/sys/raw.rs index 147fc6a9c4..a4c9990f21 100644 --- a/rust/pspp/src/sys/raw.rs +++ b/rust/pspp/src/sys/raw.rs @@ -626,15 +626,14 @@ impl Record { false, )); } - match &set.mr_type { - records::MultipleResponseType::MultipleDichotomy { value, .. } => { - strings.push(RecordString::new( - "Multiple Response Set Counted Value", - value, - false, - )); - } - _ => (), + if let records::MultipleResponseType::MultipleDichotomy { value, .. } = + &set.mr_type + { + strings.push(RecordString::new( + "Multiple Response Set Counted Value", + value, + false, + )); } } } @@ -1174,7 +1173,7 @@ impl Datum { Some(code) => return Ok(Some(endian.to_bytes(code as f64 - bias))), None => { match try_read_bytes::<8, _>(reader)? { - Some(new_codes) => codes.extend(new_codes.into_iter()), + Some(new_codes) => codes.extend(new_codes), None => return Ok(None), }; } @@ -1747,9 +1746,9 @@ pub struct UntypedDatum(pub [u8; 8]); impl Debug for UntypedDatum { fn fmt(&self, f: &mut Formatter) -> FmtResult { let little: f64 = Endian::Little.parse(self.0); - let little = format!("{:?}", little); + let little = format!("{little:?}"); let big: f64 = Endian::Big.parse(self.0); - let big = format!("{:?}", big); + let big = format!("{big:?}"); let number = if little.len() <= big.len() { little } else { @@ -1761,7 +1760,7 @@ impl Debug for UntypedDatum { fn skip_bytes(r: &mut R, mut n: usize) -> Result<(), IoError> { thread_local! { - static BUF: RefCell<[u8; 256]> = RefCell::new([0u8; 256]); + static BUF: RefCell<[u8; 256]> = const { RefCell::new([0u8; 256]) }; } BUF.with_borrow_mut(|buf| { while n > 0 { @@ -2092,7 +2091,7 @@ impl From<&EncodingReport> for Details { .strings .iter() .enumerate() - .map(|(purpose, rs)| { + .flat_map(|(purpose, rs)| { rs.interpretations .iter() .enumerate() @@ -2103,7 +2102,6 @@ impl From<&EncodingReport> for Details { ) }) }) - .flatten() .collect::>()).into(), ); } @@ -2164,7 +2162,7 @@ impl EncodingReport { records: &[Record], cases: impl Iterator>, ) -> Result { - let (encoding, codepage) = get_encoding_info(&records); + let (encoding, codepage) = get_encoding_info(records); let label = encoding .map(|encoding| (String::from(encoding), get_encoding(Some(encoding), None))); let codepage = codepage.map(|codepage| (codepage, get_encoding(None, Some(codepage)))); diff --git a/rust/pspp/src/sys/raw/records.rs b/rust/pspp/src/sys/raw/records.rs index b54f8d6da3..a977eddcf4 100644 --- a/rust/pspp/src/sys/raw/records.rs +++ b/rust/pspp/src/sys/raw/records.rs @@ -843,7 +843,7 @@ impl ValueLabelRecord { datum: value, label, }| ValueLabel { - datum: value.clone(), + datum: *value, label: decoder.decode(label).to_string(), }, ) @@ -2519,7 +2519,7 @@ impl ZHeader { #[derive(ThisError, Debug)] pub enum ZHeaderError { /// I/O error via [mod@binrw]. - #[error("{}", DisplayBinError(&.0, "ZLIB header"))] + #[error("{}", DisplayBinError(.0, "ZLIB header"))] BinError(#[from] BinError), /// Impossible ztrailer_offset {0:#x}. @@ -2582,6 +2582,7 @@ pub struct RawZTrailer { impl RawZTrailer { /// Returns the length of the trailer when it is written, in bytes. + #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> usize { 24 + self.blocks.len() * 24 } @@ -2666,7 +2667,7 @@ impl<'a> Display for DisplayBinError<'a> { #[derive(ThisError, Debug)] pub enum ZTrailerError { /// I/O error via [mod@binrw]. - #[error("{}", DisplayBinError(&.0, "ZLIB trailer"))] + #[error("{}", DisplayBinError(.0, "ZLIB trailer"))] BinError(#[from] BinError), /// ZLIB trailer bias {actual} is not {} as expected from file header bias. @@ -2856,17 +2857,15 @@ impl ZTrailer { }, )); } - } else { - if block.uncompressed_size > inner.block_size { - warn(Warning::new( - Some(block_offsets), - ZlibTrailerWarning::ZlibTrailerBlockTooBig { - index, - actual: block.uncompressed_size, - max_expected: inner.block_size, - }, - )); - } + } else if block.uncompressed_size > inner.block_size { + warn(Warning::new( + Some(block_offsets), + ZlibTrailerWarning::ZlibTrailerBlockTooBig { + index, + actual: block.uncompressed_size, + max_expected: inner.block_size, + }, + )); } expected_cmp_ofs += block.compressed_size as u64; diff --git a/rust/pspp/src/sys/write.rs b/rust/pspp/src/sys/write.rs index d67b73575b..2fe84f2423 100644 --- a/rust/pspp/src/sys/write.rs +++ b/rust/pspp/src/sys/write.rs @@ -327,7 +327,7 @@ where // Variable label. if let Some(label) = variable.label() { - let label = variable.encoding().encode(&label).0; + let label = variable.encoding().encode(label).0; let len = label.len().min(255) as u32; let padded_len = len.next_multiple_of(4); (len, &*label, Zeros((padded_len - len) as usize)).write_le(self.writer)?; @@ -426,7 +426,7 @@ where (3u32, value_labels.0.len() as u32).write_le(self.writer)?; for (datum, label) in &value_labels.0 { let datum_padding = datum.width().as_string_width().map_or(0, |width| 8 - width); - let label = &*self.dictionary.encoding().encode(&label).0; + let label = &*self.dictionary.encoding().encode(label).0; let label = if label.len() > 255 { &label[..255] } else { @@ -453,7 +453,7 @@ where if !self.dictionary.documents.is_empty() { (6u32, self.dictionary.documents.len() as u32).write_le(self.writer)?; for line in &self.dictionary.documents { - Padded::exact(&*self.dictionary.encoding().encode(&line).0, 80, b' ') + Padded::exact(&self.dictionary.encoding().encode(line).0, 80, b' ') .write_le(self.writer)?; } } @@ -647,7 +647,7 @@ where for (value, label) in &variable.value_labels.0 { let value = value.as_string().unwrap(); - let label = self.dictionary.encoding().encode(&label).0; + let label = self.dictionary.encoding().encode(label).0; ( value.len() as u32, value.raw_string_bytes(), @@ -728,7 +728,7 @@ where } fn write_string_record(&mut self, subtype: u32, s: &str) -> Result<(), BinError> { - self.write_bytes_record(subtype, &self.dictionary.encoding().encode(&s).0) + self.write_bytes_record(subtype, &self.dictionary.encoding().encode(s).0) } } @@ -891,8 +891,8 @@ where fn flush_compressed(&mut self) -> Result<(), BinError> { if !self.opcodes.is_empty() { self.opcodes.resize(8, 0); - self.inner.write_all(&mut self.opcodes)?; - self.inner.write(&mut self.data)?; + self.inner.write_all(self.opcodes)?; + self.inner.write_all(self.data)?; self.opcodes.clear(); self.data.clear(); } @@ -906,7 +906,7 @@ where Ok(()) } - fn write_case_uncompressed<'c, B>( + fn write_case_uncompressed( &mut self, case: impl Iterator>, ) -> Result<(), BinError> @@ -940,7 +940,7 @@ where } Ok(()) } - fn write_case_compressed<'c, B>( + fn write_case_compressed( &mut self, case: impl Iterator>, ) -> Result<(), BinError> @@ -952,9 +952,7 @@ where CaseVar::Numeric => match datum.as_number().unwrap() { None => self.put_opcode(255)?, Some(number) => { - if number >= 1.0 - BIAS - && number <= 251.0 - BIAS - && number == number.trunc() + if (1.0 - BIAS..=251.0 - BIAS).contains(&number) && number == number.trunc() { self.put_opcode((number + BIAS) as u8)? } else { @@ -1073,7 +1071,7 @@ where /// # Panic /// /// Panics if [try_finish](Self::try_finish) has been called. - pub fn write_case<'a, B>( + pub fn write_case( &mut self, case: impl IntoIterator>, ) -> Result<(), BinError> @@ -1189,7 +1187,7 @@ where { fn write(&mut self, mut buf: &[u8]) -> Result { let n = buf.len(); - while buf.len() > 0 { + while !buf.is_empty() { if self.encoder.total_in() >= ZBLOCK_SIZE { self.flush_block()?; } diff --git a/rust/pspp/src/util.rs b/rust/pspp/src/util.rs index bcb506966a..1e608d96a3 100644 --- a/rust/pspp/src/util.rs +++ b/rust/pspp/src/util.rs @@ -12,7 +12,7 @@ where { fn to_small_string(&self) -> SmallString<[u8; N]> { let mut s = SmallString::new(); - write!(&mut s, "{}", self).unwrap(); + write!(&mut s, "{self}").unwrap(); s } } diff --git a/rust/pspp/src/variable.rs b/rust/pspp/src/variable.rs index a596fb02d6..3c182b35b5 100644 --- a/rust/pspp/src/variable.rs +++ b/rust/pspp/src/variable.rs @@ -589,7 +589,7 @@ impl HasIdentifier for Variable { #[derive(Clone, Default, PartialEq, Eq)] pub struct ValueLabels(pub HashMap, String>); -impl<'a> Equivalent> for Datum<&'a ByteStr> { +impl Equivalent> for Datum<&ByteStr> { fn equivalent(&self, key: &Datum) -> bool { self == key } @@ -623,7 +623,9 @@ impl ValueLabels { self.0 = self .0 .drain() - .filter_map(|(mut datum, string)| datum.resize(width).is_ok().then(|| (datum, string))) + .filter_map(|(mut datum, string)| { + datum.resize(width).is_ok().then_some((datum, string)) + }) .collect(); } @@ -749,7 +751,7 @@ pub struct MissingValues { impl Debug for MissingValues { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{}", self) + write!(f, "{self}") } } -- 2.30.2