changeset 51120:532e74ad3ff6

rust: run a clippy pass with the latest stable version Our current version of clippy is older than the latest stable. The newest version has new lints that are moslty good advice, so let's apply them ahead of time. This has the added benefit of reducing the noise for developpers like myself that use clippy as an IDE helper, as well as being more prepared for a future clippy upgrade.
author Raphaël Gomès <rgomes@octobus.net>
date Mon, 06 Nov 2023 11:06:08 +0100
parents d58e754f2db0
children 34e0670caf46
files rust/hg-core/src/config/layer.rs rust/hg-core/src/config/mod.rs rust/hg-core/src/dagops.rs rust/hg-core/src/dirstate_tree/dirstate_map.rs rust/hg-core/src/dirstate_tree/status.rs rust/hg-core/src/discovery.rs rust/hg-core/src/filepatterns.rs rust/hg-core/src/matchers.rs rust/hg-core/src/repo.rs rust/hg-core/src/revlog/mod.rs rust/hg-core/src/revlog/node.rs rust/hg-core/src/revlog/nodemap.rs rust/hg-core/src/revlog/nodemap_docket.rs rust/hg-core/src/utils/files.rs rust/hg-core/src/utils/path_auditor.rs rust/hg-cpython/src/dirstate/status.rs rust/hg-cpython/src/revlog.rs rust/rhg/src/commands/cat.rs rust/rhg/src/commands/debugdata.rs rust/rhg/src/commands/root.rs rust/rhg/src/main.rs rust/rhg/src/ui.rs
diffstat 22 files changed, 67 insertions(+), 65 deletions(-) [+]
line wrap: on
line diff
--- a/rust/hg-core/src/config/layer.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/config/layer.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -107,7 +107,7 @@
     ) {
         self.sections
             .entry(section)
-            .or_insert_with(HashMap::new)
+            .or_default()
             .insert(item, ConfigValue { bytes: value, line });
     }
 
@@ -178,7 +178,7 @@
                     .expect("Path::parent fail on a file we’ve read");
                 // `Path::join` with an absolute argument correctly ignores the
                 // base path
-                let filename = dir.join(&get_path_from_bytes(&filename_bytes));
+                let filename = dir.join(get_path_from_bytes(&filename_bytes));
                 match std::fs::read(&filename) {
                     Ok(data) => {
                         layers.push(current_layer);
--- a/rust/hg-core/src/config/mod.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/config/mod.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -758,7 +758,7 @@
         let tmpdir = tempfile::tempdir().unwrap();
         let tmpdir_path = tmpdir.path();
         let mut included_file =
-            File::create(&tmpdir_path.join("included.rc")).unwrap();
+            File::create(tmpdir_path.join("included.rc")).unwrap();
 
         included_file.write_all(b"[section]\nitem=value1").unwrap();
         let base_config_path = tmpdir_path.join("base.rc");
--- a/rust/hg-core/src/dagops.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/dagops.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -205,8 +205,7 @@
         graph: &impl Graph,
         revs: &[BaseRevision],
     ) -> Result<Vec<Revision>, GraphError> {
-        let iter_revs: Vec<_> =
-            revs.into_iter().cloned().map(Revision).collect();
+        let iter_revs: Vec<_> = revs.iter().cloned().map(Revision).collect();
         let heads = heads(graph, iter_revs.iter())?;
         let mut as_vec: Vec<Revision> = heads.iter().cloned().collect();
         as_vec.sort_unstable();
--- a/rust/hg-core/src/dirstate_tree/dirstate_map.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/dirstate_tree/dirstate_map.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -178,7 +178,7 @@
             ChildNodes::InMemory(nodes) => Ok(nodes),
             ChildNodes::OnDisk(nodes) => {
                 *unreachable_bytes +=
-                    std::mem::size_of_val::<[on_disk::Node]>(nodes) as u32;
+                    std::mem::size_of_val::<[on_disk::Node]>(*nodes) as u32;
                 let nodes = nodes
                     .iter()
                     .map(|node| {
@@ -764,7 +764,7 @@
     ) -> Result<bool, DirstateV2ParseError> {
         let was_tracked = old_entry_opt.map_or(false, |e| e.tracked());
         let had_entry = old_entry_opt.is_some();
-        let tracked_count_increment = if was_tracked { 0 } else { 1 };
+        let tracked_count_increment = u32::from(!was_tracked);
         let mut new = false;
 
         let node = self.get_or_insert_node(filename, |ancestor| {
--- a/rust/hg-core/src/dirstate_tree/status.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/dirstate_tree/status.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -249,7 +249,7 @@
         }
     }
 
-    fn force<'b>(&self, ignore_fn: &IgnoreFnType<'b>) -> bool {
+    fn force(&self, ignore_fn: &IgnoreFnType<'_>) -> bool {
         match self.parent {
             None => false,
             Some(parent) => {
--- a/rust/hg-core/src/discovery.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/discovery.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -332,7 +332,7 @@
             FastHashMap::default();
         for &rev in self.undecided.as_ref().unwrap() {
             for p in ParentsIterator::graph_parents(&self.graph, rev)? {
-                children.entry(p).or_insert_with(Vec::new).push(rev);
+                children.entry(p).or_default().push(rev);
             }
         }
         self.children_cache = Some(children);
@@ -695,7 +695,7 @@
     #[test]
     fn test_bidirectional_sample() -> Result<(), GraphError> {
         let mut disco = full_disco();
-        disco.undecided = Some((0..=13).into_iter().map(Revision).collect());
+        disco.undecided = Some((0..=13).map(Revision).collect());
 
         let (sample_set, size) = disco.bidirectional_sample(7)?;
         assert_eq!(size, 7);
--- a/rust/hg-core/src/filepatterns.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/filepatterns.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -629,8 +629,7 @@
             normalize_path_bytes(&get_bytes_from_path(source));
 
         let source_root = get_path_from_bytes(&normalized_source);
-        let source_root =
-            source_root.parent().unwrap_or_else(|| source_root.deref());
+        let source_root = source_root.parent().unwrap_or(source_root);
 
         let path = source_root.join(get_path_from_bytes(pattern));
         let new_root = path.parent().unwrap_or_else(|| path.deref());
@@ -682,22 +681,21 @@
         assert_eq!(escape_pattern(untouched), untouched.to_vec());
         // All escape codes
         assert_eq!(
-            escape_pattern(br#"()[]{}?*+-|^$\\.&~#\t\n\r\v\f"#),
-            br#"\(\)\[\]\{\}\?\*\+\-\|\^\$\\\\\.\&\~\#\\t\\n\\r\\v\\f"#
-                .to_vec()
+            escape_pattern(br"()[]{}?*+-|^$\\.&~#\t\n\r\v\f"),
+            br"\(\)\[\]\{\}\?\*\+\-\|\^\$\\\\\.\&\~\#\\t\\n\\r\\v\\f".to_vec()
         );
     }
 
     #[test]
     fn glob_test() {
-        assert_eq!(glob_to_re(br#"?"#), br#"."#);
-        assert_eq!(glob_to_re(br#"*"#), br#"[^/]*"#);
-        assert_eq!(glob_to_re(br#"**"#), br#".*"#);
-        assert_eq!(glob_to_re(br#"**/a"#), br#"(?:.*/)?a"#);
-        assert_eq!(glob_to_re(br#"a/**/b"#), br#"a/(?:.*/)?b"#);
-        assert_eq!(glob_to_re(br#"[a*?!^][^b][!c]"#), br#"[a*?!^][\^b][^c]"#);
-        assert_eq!(glob_to_re(br#"{a,b}"#), br#"(?:a|b)"#);
-        assert_eq!(glob_to_re(br#".\*\?"#), br#"\.\*\?"#);
+        assert_eq!(glob_to_re(br"?"), br".");
+        assert_eq!(glob_to_re(br"*"), br"[^/]*");
+        assert_eq!(glob_to_re(br"**"), br".*");
+        assert_eq!(glob_to_re(br"**/a"), br"(?:.*/)?a");
+        assert_eq!(glob_to_re(br"a/**/b"), br"a/(?:.*/)?b");
+        assert_eq!(glob_to_re(br"[a*?!^][^b][!c]"), br"[a*?!^][\^b][^c]");
+        assert_eq!(glob_to_re(br"{a,b}"), br"(?:a|b)");
+        assert_eq!(glob_to_re(br".\*\?"), br"\.\*\?");
     }
 
     #[test]
--- a/rust/hg-core/src/matchers.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/matchers.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -28,7 +28,6 @@
 use crate::filepatterns::normalize_path_bytes;
 use std::collections::HashSet;
 use std::fmt::{Display, Error, Formatter};
-use std::ops::Deref;
 use std::path::{Path, PathBuf};
 use std::{borrow::ToOwned, collections::BTreeSet};
 
@@ -183,7 +182,7 @@
     pub fn new(files: Vec<HgPathBuf>) -> Result<Self, HgPathError> {
         let dirs = DirsMultiset::from_manifest(&files)?;
         Ok(Self {
-            files: HashSet::from_iter(files.into_iter()),
+            files: HashSet::from_iter(files),
             dirs,
             sorted_visitchildrenset_candidates: OnceCell::new(),
         })
@@ -316,7 +315,7 @@
     pub fn new(ignore_patterns: Vec<IgnorePattern>) -> PatternResult<Self> {
         let (files, _) = roots_and_dirs(&ignore_patterns);
         let dirs = DirsMultiset::from_manifest(&files)?;
-        let files: HashSet<HgPathBuf> = HashSet::from_iter(files.into_iter());
+        let files: HashSet<HgPathBuf> = HashSet::from_iter(files);
 
         let prefix = ignore_patterns.iter().all(|k| {
             matches!(k.syntax, PatternSyntax::Path | PatternSyntax::RelPath)
@@ -773,10 +772,10 @@
 
 /// Returns the regex pattern and a function that matches an `HgPath` against
 /// said regex formed by the given ignore patterns.
-fn build_regex_match<'a, 'b>(
-    ignore_patterns: &'a [IgnorePattern],
+fn build_regex_match<'a>(
+    ignore_patterns: &[IgnorePattern],
     glob_suffix: &[u8],
-) -> PatternResult<(Vec<u8>, IgnoreFnType<'b>)> {
+) -> PatternResult<(Vec<u8>, IgnoreFnType<'a>)> {
     let mut regexps = vec![];
     let mut exact_set = HashSet::new();
 
@@ -958,7 +957,7 @@
                 } else {
                     b"."
                 };
-                dirs.contains(dir.deref())
+                dirs.contains(dir)
             };
             match_funcs.push(Box::new(match_func));
 
--- a/rust/hg-core/src/repo.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/repo.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -686,7 +686,7 @@
                 }
                 file.write_all(&data)?;
                 file.flush()?;
-                file.seek(SeekFrom::Current(0))
+                file.stream_position()
             })()
             .when_writing_file(&data_filename)?;
 
--- a/rust/hg-core/src/revlog/mod.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/revlog/mod.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -248,8 +248,8 @@
     ) -> Result<Self, HgError> {
         let index_path = index_path.as_ref();
         let index = {
-            match store_vfs.mmap_open_opt(&index_path)? {
-                None => Index::new(Box::new(vec![])),
+            match store_vfs.mmap_open_opt(index_path)? {
+                None => Index::new(Box::<Vec<_>>::default()),
                 Some(index_mmap) => {
                     let index = Index::new(Box::new(index_mmap))?;
                     Ok(index)
--- a/rust/hg-core/src/revlog/node.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/revlog/node.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -348,7 +348,7 @@
         assert_eq!(Node::from_hex(SAMPLE_NODE_HEX).unwrap(), SAMPLE_NODE);
         assert!(Node::from_hex(not_hex).is_err());
         assert!(Node::from_hex(too_short).is_err());
-        assert!(Node::from_hex(&too_long).is_err());
+        assert!(Node::from_hex(too_long).is_err());
     }
 
     #[test]
--- a/rust/hg-core/src/revlog/nodemap.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/revlog/nodemap.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -656,7 +656,7 @@
 
 impl fmt::Debug for NodeTree {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        let readonly: &[Block] = &*self.readonly;
+        let readonly: &[Block] = &self.readonly;
         write!(
             f,
             "readonly: {:?}, growable: {:?}, root: {:?}",
@@ -668,7 +668,7 @@
 impl Default for NodeTree {
     /// Create a fully mutable empty NodeTree
     fn default() -> Self {
-        NodeTree::new(Box::new(Vec::new()))
+        NodeTree::new(Box::<Vec<_>>::default())
     }
 }
 
@@ -775,7 +775,7 @@
     /// strings for test data, and brings actual hash size independency.
     #[cfg(test)]
     fn pad_node(hex: &str) -> Node {
-        Node::from_hex(&hex_pad_right(hex)).unwrap()
+        Node::from_hex(hex_pad_right(hex)).unwrap()
     }
 
     /// Pad hexadecimal Node prefix with zeros on the right, then insert
@@ -824,7 +824,7 @@
             nt.find_node(&idx, idx.get(&1.into()).unwrap())?,
             Some(R!(1))
         );
-        let unknown = Node::from_hex(&hex_pad_right("3d")).unwrap();
+        let unknown = Node::from_hex(hex_pad_right("3d")).unwrap();
         assert_eq!(nt.find_node(&idx, &unknown)?, None);
         Ok(())
     }
@@ -900,7 +900,7 @@
             hex: &str,
         ) -> Result<(), NodeMapError> {
             let node = pad_node(hex);
-            return self.insert_node(rev, node);
+            self.insert_node(rev, node)
         }
 
         fn find_hex(
@@ -931,6 +931,12 @@
         }
     }
 
+    impl Default for TestNtIndex {
+        fn default() -> Self {
+            Self::new()
+        }
+    }
+
     #[test]
     fn test_insert_full_mutable() -> Result<(), NodeMapError> {
         let mut idx = TestNtIndex::new();
@@ -1003,7 +1009,7 @@
         let mut node1_hex = hex_pad_right("444444");
         node1_hex.pop();
         node1_hex.push('5');
-        let node0 = Node::from_hex(&node0_hex).unwrap();
+        let node0 = Node::from_hex(node0_hex).unwrap();
         let node1 = Node::from_hex(&node1_hex).unwrap();
 
         idx.insert(0.into(), node0);
--- a/rust/hg-core/src/revlog/nodemap_docket.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/revlog/nodemap_docket.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -75,7 +75,7 @@
         // TODO: use `vfs.read()` here when the `persistent-nodemap.mmap`
         // config is false?
         if let Some(mmap) =
-            store_vfs.mmap_open(&data_path).io_not_found_as_none()?
+            store_vfs.mmap_open(data_path).io_not_found_as_none()?
         {
             if mmap.len() >= data_length {
                 Ok(Some((docket, mmap)))
--- a/rust/hg-core/src/utils/files.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/utils/files.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -192,13 +192,13 @@
     let name = name.as_ref();
 
     let name = if !name.is_absolute() {
-        root.join(&cwd).join(&name)
+        root.join(cwd).join(name)
     } else {
         name.to_owned()
     };
-    let auditor = PathAuditor::new(&root);
-    if name != root && name.starts_with(&root) {
-        let name = name.strip_prefix(&root).unwrap();
+    let auditor = PathAuditor::new(root);
+    if name != root && name.starts_with(root) {
+        let name = name.strip_prefix(root).unwrap();
         auditor.audit_path(path_to_hg_path_buf(name)?)?;
         Ok(name.to_owned())
     } else if name == root {
@@ -210,7 +210,7 @@
         let mut name = name.deref();
         let original_name = name.to_owned();
         loop {
-            let same = is_same_file(&name, &root).unwrap_or(false);
+            let same = is_same_file(name, root).unwrap_or(false);
             if same {
                 if name == original_name {
                     // `name` was actually the same as root (maybe a symlink)
@@ -218,8 +218,8 @@
                 }
                 // `name` is a symlink to root, so `original_name` is under
                 // root
-                let rel_path = original_name.strip_prefix(&name).unwrap();
-                auditor.audit_path(path_to_hg_path_buf(&rel_path)?)?;
+                let rel_path = original_name.strip_prefix(name).unwrap();
+                auditor.audit_path(path_to_hg_path_buf(rel_path)?)?;
                 return Ok(rel_path.to_owned());
             }
             name = match name.parent() {
@@ -429,7 +429,7 @@
             })
         );
         assert_eq!(
-            canonical_path(&root, Path::new(""), &under_repo_symlink),
+            canonical_path(&root, Path::new(""), under_repo_symlink),
             Ok(PathBuf::from("d"))
         );
     }
--- a/rust/hg-core/src/utils/path_auditor.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-core/src/utils/path_auditor.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -117,7 +117,7 @@
             if self.audited_dirs.read().unwrap().contains(prefix) {
                 continue;
             }
-            self.check_filesystem(&prefix, &path)?;
+            self.check_filesystem(prefix, path)?;
             self.audited_dirs.write().unwrap().insert(prefix.to_owned());
         }
 
@@ -203,12 +203,12 @@
             })
         );
 
-        create_dir(&base_dir_path.join("realdir")).unwrap();
-        File::create(&base_dir_path.join("realdir/realfile")).unwrap();
+        create_dir(base_dir_path.join("realdir")).unwrap();
+        File::create(base_dir_path.join("realdir/realfile")).unwrap();
         // TODO make portable
         std::os::unix::fs::symlink(
-            &base_dir_path.join("realdir"),
-            &base_dir_path.join("symlink"),
+            base_dir_path.join("realdir"),
+            base_dir_path.join("symlink"),
         )
         .unwrap();
         let path = HgPath::new(b"symlink/realfile");
--- a/rust/hg-cpython/src/dirstate/status.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-cpython/src/dirstate/status.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -273,7 +273,7 @@
                 py_warnings.append(
                     py,
                     (
-                        PyBytes::new(py, &get_bytes_from_path(&file)),
+                        PyBytes::new(py, &get_bytes_from_path(file)),
                         PyBytes::new(py, syn),
                     )
                         .to_py_object(py)
@@ -282,7 +282,7 @@
             }
             PatternFileWarning::NoSuchFile(file) => py_warnings.append(
                 py,
-                PyBytes::new(py, &get_bytes_from_path(&file)).into_object(),
+                PyBytes::new(py, &get_bytes_from_path(file)).into_object(),
             ),
         }
     }
--- a/rust/hg-cpython/src/revlog.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/hg-cpython/src/revlog.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -348,7 +348,7 @@
         py: Python<'a>,
     ) -> PyResult<&'a RefCell<Option<NodeTree>>> {
         if self.nt(py).borrow().is_none() {
-            let readonly = Box::new(Vec::new());
+            let readonly = Box::<Vec<_>>::default();
             let mut nt = NodeTree::load_bytes(readonly, 0);
             self.fill_nodemap(py, &mut nt)?;
             self.nt(py).borrow_mut().replace(nt);
@@ -382,7 +382,7 @@
         // If there's anything readonly, we need to build the data again from
         // scratch
         let bytes = if readonly.len() > 0 {
-            let mut nt = NodeTree::load_bytes(Box::new(vec![]), 0);
+            let mut nt = NodeTree::load_bytes(Box::<Vec<_>>::default(), 0);
             self.fill_nodemap(py, &mut nt)?;
 
             let (readonly, bytes) = nt.into_readonly_and_added_bytes();
--- a/rust/rhg/src/commands/cat.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/rhg/src/commands/cat.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -62,7 +62,7 @@
             return Err(CommandError::unsupported(message));
         }
 
-        let normalized = cwd.join(&file);
+        let normalized = cwd.join(file);
         // TODO: actually normalize `..` path segments etc?
         let dotted = normalized.components().any(|c| c.as_os_str() == "..");
         if file.as_bytes() == b"." || dotted {
--- a/rust/rhg/src/commands/debugdata.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/rhg/src/commands/debugdata.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -23,7 +23,7 @@
         )
         .group(
             ArgGroup::new("revlog")
-                .args(&["changelog", "manifest"])
+                .args(["changelog", "manifest"])
                 .required(true),
         )
         .arg(
--- a/rust/rhg/src/commands/root.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/rhg/src/commands/root.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -20,7 +20,7 @@
         .with_context(|| {
             IoErrorContext::CanonicalizingPath(working_directory.to_owned())
         })?;
-    let bytes = get_bytes_from_path(&working_directory);
+    let bytes = get_bytes_from_path(working_directory);
     invocation
         .ui
         .write_stdout(&format_bytes!(b"{}\n", bytes.as_slice()))?;
--- a/rust/rhg/src/main.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/rhg/src/main.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -404,8 +404,8 @@
     }
 }
 
-fn exit<'a>(
-    original_args: &'a [OsString],
+fn exit(
+    original_args: &[OsString],
     initial_current_dir: &Option<PathBuf>,
     ui: &Ui,
     mut on_unsupported: OnUnsupported,
--- a/rust/rhg/src/ui.rs	Mon Nov 06 11:02:18 2023 +0100
+++ b/rust/rhg/src/ui.rs	Mon Nov 06 11:06:08 2023 +0100
@@ -251,7 +251,7 @@
         PatternFileWarning::InvalidSyntax(path, syntax) => format_bytes!(
             b"{}: ignoring invalid syntax '{}'\n",
             get_bytes_from_path(path),
-            &*syntax
+            syntax
         ),
         PatternFileWarning::NoSuchFile(path) => {
             let path = if let Ok(relative) =
@@ -259,7 +259,7 @@
             {
                 relative
             } else {
-                &*path
+                path
             };
             format_bytes!(
                 b"skipping unreadable pattern file '{}': \