rust: Fix clippy warnings.
authorBen Pfaff <blp@cs.stanford.edu>
Fri, 29 Aug 2025 00:01:58 +0000 (17:01 -0700)
committerBen Pfaff <blp@cs.stanford.edu>
Fri, 29 Aug 2025 00:01:58 +0000 (17:01 -0700)
21 files changed:
rust/pspp/src/convert.rs
rust/pspp/src/crypto/mod.rs
rust/pspp/src/data.rs
rust/pspp/src/data/encoded.rs
rust/pspp/src/dictionary.rs
rust/pspp/src/format/display/mod.rs
rust/pspp/src/hexfloat.rs
rust/pspp/src/lex/command_name.rs
rust/pspp/src/message.rs
rust/pspp/src/output/csv.rs
rust/pspp/src/output/driver.rs
rust/pspp/src/output/mod.rs
rust/pspp/src/output/pivot/mod.rs
rust/pspp/src/output/spv.rs
rust/pspp/src/output/text.rs
rust/pspp/src/sys/cooked.rs
rust/pspp/src/sys/raw.rs
rust/pspp/src/sys/raw/records.rs
rust/pspp/src/sys/write.rs
rust/pspp/src/util.rs
rust/pspp/src/variable.rs

index 879265ff719506078b9c48e8355dfec9834cb1c2..949331282d7691bc03bcddad7baee61b71505ea8 100644 (file)
@@ -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(),
index 8685f938af7d8f14d34e1d5d1e1c0f92d09bd867..c2e86cdea1a31e1ba760cd705a8d9fb21703f2f7 100644 (file)
@@ -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(),
         )
     }
index 0fb311cf5f100c1efd961adaab6844c6aced3931..28ad0521a7c2d0a91ea50d73ac19263a31f3a0c8 100644 (file)
@@ -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<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
     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<B> Datum<B> {
     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<T> Datum<T> {
     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<B> Case<B>
 where
     B: Borrow<[Datum<ByteString>]>,
 {
+    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(),
         }
     }
 }
index 2cc1a22effcee8ec39f966f1cfea65472617083c..a76d85e944585ae676632f0069e28ccfd1185c7c 100644 (file)
@@ -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<ByteCow<'_>> {
-        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<ByteCow<'_>> {
-        WithEncoding::new(ByteCow(encoding.encode(String::as_str(&self)).0), encoding)
+        WithEncoding::new(ByteCow(encoding.encode(String::as_str(self)).0), encoding)
     }
 }
 
index 84d86da3985dfe5f13676c0e3504a144bf365ea1..7a0088a47efa2871ba0b3558d6e1ac1ce0f1a163 100644 (file)
@@ -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<Value> {
         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<usize> 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,
-        }
+            }
+        )
     }
 }
 
index c86e434be861614fbe2b6bba9c76443bd52d3811..5b3bbe2cccc51f7815cb444a8f106f7f6ae8c1ca 100644 (file)
@@ -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),
         }
index a38189e6ef27439cdb70bb52bbeaacc30a6ce267..25bb1d3e4581680235b4ff18ec63f6f6f53cc811 100644 (file)
@@ -32,7 +32,7 @@ impl<T: Float> Display for HexFloat<T> {
             _ => (),
         };
         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;
index 327f7cbf45477d815b8f64f3f5329f412fa4ba62..dfde500adaeb8a951656add1bc7cc426df5a1f43 100644 (file)
@@ -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<Match> {
     let mut command_words = command.split_whitespace();
     let mut string_words = string.split_whitespace();
index 97bcc90b847ed19989e66c398f0b6e1dae95bddb..28d0a9911ab8d4f7e9eba969798049ad0d0ef1bf 100644 (file)
@@ -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 {
index 5e65b0b75e6ddcbe3dce60a8b74e7a9db7a0526b..0626d90eb22c1b8775e4bfd4a8a82267a8d977b8 100644 (file)
@@ -131,7 +131,7 @@ impl CsvDriver {
     pub fn new(config: &CsvConfig) -> std::io::Result<Self> {
         Ok(Self {
             file: BufWriter::new(File::create(&config.file)?),
-            options: config.options.clone(),
+            options: config.options,
             n_items: 0,
         })
     }
index 963661146e0002279a0c94316b685a63fd901153..5d97660126756aabb6c3217ae776b4a00acbddfe 100644 (file)
@@ -67,27 +67,27 @@ pub trait Driver {
 
 impl Driver for Box<dyn Driver> {
     fn name(&self) -> Cow<'static, str> {
-        (&**self).name()
+        (**self).name()
     }
 
     fn write(&mut self, item: &Arc<Item>) {
-        (&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()
     }
 }
 
index 28ab4efdd6eac1cf08a5a714b2bde2c0c2f19640..c1e061ed9bb7c9475efc5fccedbf0b87f4128dd8 100644 (file)
@@ -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)
     }
 }
 
index 6eed68e518905b627cc1099deb4679a708728ba7..92133e2c513e2621d266c581629b105fbac5b4e8 100644 (file)
@@ -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) => {
index 8c44fe18ba781bf444df2daf738388cef60f5d5f..89ae457544974905fc72de7096e6c226398f3a79 100644 (file)
@@ -194,7 +194,7 @@ where
             super::Details::Group(children) => {
                 let mut attributes = Vec::<Attribute>::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<X, F>(
         &mut self,
-        writer: &'a mut XmlWriter<X>,
+        writer: &mut XmlWriter<X>,
         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 {
index 1a5aad6d8e2bf3c527477dec2ed85a5d3c63b551..af00cfcc6829b4aebd7e86e2430aadcb0b9783d7 100644 (file)
@@ -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<TextDriver> {
         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}")?;
                 }
             }
         }
index c4f5878206161de805400dbba86018c79e14c912..abb18fd5996f5c5655786b0a0bc77d7bc143c25f 100644 (file)
@@ -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");
index 147fc6a9c414d5cbefd3c10b472d6da8c4130cbb..a4c9990f21f394de283c5f049f46d8509e5c87d1 100644 (file)
@@ -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<ByteString> {
                 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: Read>(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::<Vec<_>>()).into(),
                     );
             }
@@ -2164,7 +2162,7 @@ impl EncodingReport {
             records: &[Record],
             cases: impl Iterator<Item = Result<RawCase, Error>>,
         ) -> Result<EncodingReport, Error> {
-            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))));
index b54f8d6da3e75d6a2850d153aa9f9226f4fac8bb..a977eddcf4a49555b5091bb9e54fa1f40c282a5a 100644 (file)
@@ -843,7 +843,7 @@ impl ValueLabelRecord<RawDatum, ByteString> {
                      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;
index d67b73575bc4d452f8e1e627e25db5d87a36e6c1..2fe84f2423a901a4b57bb207fc550a96bdcac581 100644 (file)
@@ -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<B>(
         &mut self,
         case: impl Iterator<Item = Datum<B>>,
     ) -> Result<(), BinError>
@@ -940,7 +940,7 @@ where
         }
         Ok(())
     }
-    fn write_case_compressed<'c, B>(
+    fn write_case_compressed<B>(
         &mut self,
         case: impl Iterator<Item = Datum<B>>,
     ) -> 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<B>(
         &mut self,
         case: impl IntoIterator<Item = Datum<B>>,
     ) -> Result<(), BinError>
@@ -1189,7 +1187,7 @@ where
 {
     fn write(&mut self, mut buf: &[u8]) -> Result<usize, IoError> {
         let n = buf.len();
-        while buf.len() > 0 {
+        while !buf.is_empty() {
             if self.encoder.total_in() >= ZBLOCK_SIZE {
                 self.flush_block()?;
             }
index bcb506966a21fdee371d877b652a75c7814378da..1e608d96a3765ce708ef39a9b60f484f0d07fa73 100644 (file)
@@ -12,7 +12,7 @@ where
 {
     fn to_small_string<const N: usize>(&self) -> SmallString<[u8; N]> {
         let mut s = SmallString::new();
-        write!(&mut s, "{}", self).unwrap();
+        write!(&mut s, "{self}").unwrap();
         s
     }
 }
index a596fb02d6e027fda4884c531fb9a550ada12ac7..3c182b35b52069f0b1602f027881fc506e70b71e 100644 (file)
@@ -589,7 +589,7 @@ impl HasIdentifier for Variable {
 #[derive(Clone, Default, PartialEq, Eq)]
 pub struct ValueLabels(pub HashMap<Datum<ByteString>, String>);
 
-impl<'a> Equivalent<Datum<ByteString>> for Datum<&'a ByteStr> {
+impl Equivalent<Datum<ByteString>> for Datum<&ByteStr> {
     fn equivalent(&self, key: &Datum<ByteString>) -> 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}")
     }
 }