diff --git a/src/ansi.rs b/src/ansi.rs index 5edfb485..7ff67167 100644 --- a/src/ansi.rs +++ b/src/ansi.rs @@ -25,21 +25,12 @@ pub trait Escaped: AsRef { 'outer: while let Some(ch) = chars.next() { resultant.push(ch); - if ch == '\u{1b}' && !open_sequence { + if ch == '\u{1b}'{ for code in chars.by_ref() { resultant.push(code); if code == 'm' { - open_sequence = true; - continue 'outer; - } - } - } else if ch == '\u{1b}' && open_sequence { - for code in chars.by_ref() { - resultant.push(code); - - if code == 'm' { - open_sequence = false; + open_sequence = !open_sequence; continue 'outer; } } @@ -66,7 +57,7 @@ fn truncate() { use ansi_term::Color::Red; let control = Red.bold().paint("Hello").to_string(); - let base = format!("{}{}", Red.bold().paint("Hello World"), "!!!"); + let base = format!("{}!!!", Red.bold().paint("Hello World")); let trunc = ::truncate(&base, 5); assert_eq!(control, trunc); diff --git a/src/context/mod.rs b/src/context/mod.rs index fef0f310..a6d13c47 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -58,7 +58,7 @@ pub struct Context { dir: Option, /// Mode of coloring output - #[arg(short = 'C', long, value_enum, default_value_t = Coloring::default())] + #[arg(short = 'C', long, value_enum, default_value_t)] pub color: Coloring, /// Print physical or logical file size @@ -145,7 +145,7 @@ pub struct Context { pub sort: sort::Type, /// Sort directories before or after all other file types - #[arg(long, value_enum, default_value_t = dir::Order::default())] + #[arg(long, value_enum, default_value_t)] pub dir_order: dir::Order, /// Number of threads to use @@ -153,11 +153,11 @@ pub struct Context { pub threads: usize, /// Report disk usage in binary or SI units - #[arg(short, long, value_enum, default_value_t = PrefixKind::default())] + #[arg(short, long, value_enum, default_value_t)] pub unit: PrefixKind, /// Which kind of layout to use when rendering the output - #[arg(short = 'y', long, value_enum, default_value_t = layout::Type::default())] + #[arg(short = 'y', long, value_enum, default_value_t)] pub layout: layout::Type, /// Show hidden files @@ -374,7 +374,7 @@ impl Context { .filter(|pair| pair[1] != "false") .flatten() .filter(|s| s != "true") - .collect::>(); + .collect::>(); args.extend(raw_args); } @@ -395,7 +395,7 @@ impl Context { let file_type = self.file_type(); Ok(match file_type { - file::Type::Dir => Box::new(move |dir_entry: &DirEntry| { + file::Type::Dir => Box::new(move |dir_entry| { let is_dir = dir_entry.file_type().map_or(false, |ft| ft.is_dir()); if is_dir { return Self::ancestor_regex_match(dir_entry.path(), &re, 0); @@ -404,7 +404,7 @@ impl Context { Self::ancestor_regex_match(dir_entry.path(), &re, 1) }), - _ => Box::new(move |dir_entry: &DirEntry| { + _ => Box::new(move |dir_entry| { let entry_type = dir_entry.file_type(); let is_dir = entry_type.map_or(false, |ft| ft.is_dir()); @@ -419,7 +419,7 @@ impl Context { file::Type::Link if entry_type.map_or(true, |ft| !ft.is_symlink()) => { return false } - _ => (), + _ => {} } let file_name = dir_entry.file_name().to_string_lossy(); re.is_match(&file_name) @@ -455,7 +455,7 @@ impl Context { let file_type = self.file_type(); match file_type { - file::Type::Dir => Ok(Box::new(move |dir_entry: &DirEntry| { + file::Type::Dir => Ok(Box::new(move |dir_entry| { let is_dir = dir_entry.file_type().map_or(false, |ft| ft.is_dir()); if is_dir { @@ -473,7 +473,7 @@ impl Context { } })), - _ => Ok(Box::new(move |dir_entry: &DirEntry| { + _ => Ok(Box::new(move |dir_entry| { let entry_type = dir_entry.file_type(); let is_dir = entry_type.map_or(false, |ft| ft.is_dir()); @@ -488,7 +488,7 @@ impl Context { file::Type::Link if entry_type.map_or(true, |ft| !ft.is_symlink()) => { return false } - _ => (), + _ => {}, } let matched = overrides.matched(dir_entry.path(), false); @@ -536,8 +536,7 @@ impl Context { /// Answers whether disk usage is asked to be reported in bytes. pub const fn byte_metric(&self) -> bool { - matches!(self.disk_usage, DiskUsage::Logical) - || matches!(self.disk_usage, DiskUsage::Physical) + matches!(self.disk_usage, DiskUsage::Logical | DiskUsage::Physical) } /// Do any of the components of a path match the provided glob? This is used for ensuring that diff --git a/src/disk_usage/file_size/byte.rs b/src/disk_usage/file_size/byte.rs index 62f52144..37049b32 100644 --- a/src/disk_usage/file_size/byte.rs +++ b/src/disk_usage/file_size/byte.rs @@ -113,7 +113,7 @@ impl Display for Metric { if self.human_readable { let unit = SiPrefix::from(self.value); - if matches!(unit, SiPrefix::Base) { + if unit == SiPrefix::Base { format!("{} {unit}", self.value) } else { let base_value = unit.base_value(); @@ -128,7 +128,7 @@ impl Display for Metric { if self.human_readable { let unit = BinPrefix::from(self.value); - if matches!(unit, BinPrefix::Base) { + if unit == BinPrefix::Base { format!("{} {unit}", self.value) } else { let base_value = unit.base_value(); @@ -158,7 +158,7 @@ fn test_metric() { prefix_kind: PrefixKind::Bin, cached_display: RefCell::::default(), }; - assert_eq!(format!("{}", metric), "100 B"); + assert_eq!(format!("{metric}"), "100 B"); let metric = Metric { value: 1000, @@ -167,7 +167,7 @@ fn test_metric() { prefix_kind: PrefixKind::Si, cached_display: RefCell::::default(), }; - assert_eq!(format!("{}", metric), "1.0 KB"); + assert_eq!(format!("{metric}"), "1.0 KB"); let metric = Metric { value: 1000, @@ -176,7 +176,7 @@ fn test_metric() { prefix_kind: PrefixKind::Bin, cached_display: RefCell::::default(), }; - assert_eq!(format!("{}", metric), "1000 B"); + assert_eq!(format!("{metric}"), "1000 B"); let metric = Metric { value: 1024, @@ -185,7 +185,7 @@ fn test_metric() { prefix_kind: PrefixKind::Bin, cached_display: RefCell::::default(), }; - assert_eq!(format!("{}", metric), "1.0 KiB"); + assert_eq!(format!("{metric}"), "1.0 KiB"); let metric = Metric { value: 2_u64.pow(20), @@ -194,14 +194,14 @@ fn test_metric() { prefix_kind: PrefixKind::Bin, cached_display: RefCell::::default(), }; - assert_eq!(format!("{}", metric), "1.0 MiB"); + assert_eq!(format!("{metric}"), "1.0 MiB"); let metric = Metric { - value: 123454, + value: 123_454, kind: MetricKind::Logical, human_readable: false, prefix_kind: PrefixKind::Bin, cached_display: RefCell::::default(), }; - assert_eq!(format!("{}", metric), "123454 B"); + assert_eq!(format!("{metric}"), "123454 B"); } diff --git a/src/disk_usage/file_size/line_count.rs b/src/disk_usage/file_size/line_count.rs index 1c145315..377a5ea3 100644 --- a/src/disk_usage/file_size/line_count.rs +++ b/src/disk_usage/file_size/line_count.rs @@ -15,7 +15,7 @@ impl Metric { /// Reads in contents of a file given by `path` and attempts to compute the total number of /// lines in that file. If a file is not UTF-8 encoded as in the case of a binary jpeg file /// then `None` will be returned. - pub fn init>(path: P) -> Option { + pub fn init(path: impl AsRef) -> Option { let data = fs::read_to_string(path.as_ref()).ok()?; let lines = data.lines().count(); diff --git a/src/disk_usage/file_size/word_count.rs b/src/disk_usage/file_size/word_count.rs index 92ebf8d1..05abe9b9 100644 --- a/src/disk_usage/file_size/word_count.rs +++ b/src/disk_usage/file_size/word_count.rs @@ -17,7 +17,7 @@ impl Metric { /// then `None` will be returned. /// /// Words are UTF-8 encoded byte sequences delimited by Unicode Derived Core Property `White_Space`. - pub fn init>(path: P) -> Option { + pub fn init(path: impl AsRef) -> Option { let data = fs::read_to_string(path.as_ref()).ok()?; let words = data.split_whitespace().count(); diff --git a/src/disk_usage/units.rs b/src/disk_usage/units.rs index d2100c5e..365668ff 100644 --- a/src/disk_usage/units.rs +++ b/src/disk_usage/units.rs @@ -16,7 +16,7 @@ pub enum PrefixKind { } /// Binary prefixes. -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] pub enum BinPrefix { Base, Kibi, @@ -26,7 +26,7 @@ pub enum BinPrefix { } /// SI prefixes. -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] pub enum SiPrefix { Base, Kilo, diff --git a/src/progress.rs b/src/progress.rs index f8a0da2b..8eb8d2ad 100644 --- a/src/progress.rs +++ b/src/progress.rs @@ -27,7 +27,7 @@ pub struct IndicatorHandle { } /// The different messages that could be sent to the thread that owns the [`Indicator`]. -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] pub enum Message { /// Message that indicates that we are currently reading from disk and that a file was indexed. Index, @@ -41,7 +41,7 @@ pub enum Message { } /// All of the different states the [`Indicator`] can be in during its life cycle. -#[derive(Default)] +#[derive(Default, PartialEq)] enum IndicatorState { /// We are currently reading from disk. #[default] @@ -93,28 +93,26 @@ impl Indicator { /// through its internal states. An [`IndicatorHandle`] is returned as a mechanism to allow the /// outside world to send messages to the worker thread and ultimately to the [`Indicator`]. pub fn measure() -> IndicatorHandle { - let (tx, rx) = mpsc::channel::(); + let (tx, rx) = mpsc::channel(); - let join_handle = thread::spawn(move || -> Result<(), Error> { + let join_handle = thread::spawn(move || { let mut indicator = Self::default(); indicator.stdout.execute(cursor::SavePosition)?; indicator.stdout.execute(cursor::Hide)?; while let Ok(msg) = rx.recv() { - if matches!(indicator.state, IndicatorState::Indexing) { + if indicator.state == IndicatorState::Indexing { match msg { Message::Index => indicator.index()?, Message::DoneIndexing => { indicator.update_state(IndicatorState::Rendering)?; } - Message::RenderReady => (), + Message::RenderReady => {} } } - if matches!(indicator.state, IndicatorState::Rendering) - && matches!(msg, Message::RenderReady) - { + if indicator.state == IndicatorState::Rendering && msg == Message::RenderReady { indicator.update_state(IndicatorState::Done)?; break; } diff --git a/src/render/grid/cell.rs b/src/render/grid/cell.rs index 57858115..73495505 100644 --- a/src/render/grid/cell.rs +++ b/src/render/grid/cell.rs @@ -15,7 +15,6 @@ use std::{ path::Path, }; - #[cfg(unix)] use chrono::{DateTime, Local}; @@ -71,7 +70,7 @@ impl<'a> Cell<'a> { match self.kind { Kind::FileName { prefix } => { - let pre = prefix.unwrap_or(""); + let pre = prefix.unwrap_or_default(); let name = theme::stylize_file_name(node); if !ctx.icons { @@ -103,11 +102,10 @@ impl<'a> Cell<'a> { .display() }; - let formatted_path = if let Some(style) = node.style() { - format!("{}", style.paint(path.to_string())) - } else { - path.to_string() - }; + let formatted_path = node.style().map_or_else( + || path.to_string(), + |style| format!("{}", style.paint(path.to_string())), + ); if !ctx.icons { return write!(f, "{formatted_path}"); @@ -147,10 +145,10 @@ impl<'a> Cell<'a> { let max_width = ctx.max_nlink_width; - let out = node - .nlink() - .map(|num| format!("{num:>max_width$}")) - .unwrap_or(format!("{PLACEHOLDER:>max_width$}")); + let out = node.nlink().map_or_else( + || format!("{PLACEHOLDER:>max_width$}"), + |num| format!("{num:>max_width$}"), + ); let formatted_nlink = if let Ok(style) = styles::get_nlink_style() { style.paint(out).to_string() @@ -170,10 +168,10 @@ impl<'a> Cell<'a> { let max_width = ctx.max_ino_width; - let out = node - .ino() - .map(|num| format!("{num:>max_width$}")) - .unwrap_or(format!("{PLACEHOLDER:>max_width$}")); + let out = node.ino().map_or_else( + || format!("{PLACEHOLDER:>max_width$}"), + |num| format!("{num:>max_width$}"), + ); let formatted_ino = if let Ok(style) = styles::get_ino_style() { style.paint(out).to_string() @@ -190,7 +188,7 @@ impl<'a> Cell<'a> { fn fmt_owner(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let max_owner_width = self.ctx.max_owner_width; - let owner = self.node.owner().map_or(styles::PLACEHOLDER, |o| o); + let owner = self.node.owner().unwrap_or(styles::PLACEHOLDER); if let Ok(style) = styles::get_owner_style() { let formatted_owner = format!("{owner:>max_owner_width$}"); @@ -206,7 +204,7 @@ impl<'a> Cell<'a> { fn fmt_group(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let max_group_width = self.ctx.max_group_width; - let group = self.node.group().map_or(styles::PLACEHOLDER, |o| o); + let group = self.node.group().unwrap_or(styles::PLACEHOLDER); if let Ok(style) = styles::get_group_style() { let formatted_group = format!("{group:>max_group_width$}"); diff --git a/src/render/theme.rs b/src/render/theme.rs index 8b3e0410..926688ae 100644 --- a/src/render/theme.rs +++ b/src/render/theme.rs @@ -9,7 +9,7 @@ type Theme = Box &'static ThemesMap>; /// Returns a closure that retrieves the regular theme. pub fn regular_theme_getter() -> Theme { - Box::new(|_node: &Node| styles::get_tree_theme().unwrap()) + Box::new(|_node| styles::get_tree_theme().unwrap()) } /// Returns a closure that can smartly determine when a symlink is being followed and when it is @@ -18,7 +18,7 @@ pub fn regular_theme_getter() -> Theme { pub fn link_theme_getter() -> Theme { let mut link_depth = None; - Box::new(move |node: &Node| { + Box::new(move |node| { let current_depth = node.depth(); if let Some(ldepth) = link_depth { @@ -90,7 +90,7 @@ pub fn style_sym_permissions(node: &Node) -> String { color.paint(chstr).to_string() }) }) - .collect::() + .collect() } else { symb } diff --git a/src/tree/count.rs b/src/tree/count.rs index 4ad62741..d536222a 100644 --- a/src/tree/count.rs +++ b/src/tree/count.rs @@ -2,6 +2,7 @@ use super::Node; use std::{ convert::From, fmt::{self, Display}, + ops::{Add, AddAssign}, }; /// For keeping track of the number of various file-types of [Node]'s chlidren. @@ -13,42 +14,65 @@ pub struct FileCount { pub num_links: usize, } -impl FileCount { +impl AddAssign<&Node> for FileCount { /// Update [Self] with information from [Node]. - pub fn update(&mut self, node: &Node) { - if node.is_dir() { + fn add_assign(&mut self, rhs: &Node) { + if rhs.is_dir() { self.num_dirs += 1; - } else if node.is_symlink() { + } else if rhs.is_symlink() { self.num_links += 1; } else { self.num_files += 1; } } +} +impl Add<&Node> for FileCount { + type Output = Self; + /// Update [Self] with information from [Node]. + fn add(self, rhs: &Node) -> Self::Output { + if rhs.is_dir() { + Self { + num_dirs: self.num_dirs + 1, + ..self + } + } else if rhs.is_symlink() { + Self { + num_links: self.num_links + 1, + ..self + } + } else { + Self { + num_files: self.num_files + 1, + ..self + } + } + } +} +impl AddAssign for FileCount { /// Update [Self] with information from [Self]. - pub fn update_from_count( - &mut self, + fn add_assign(&mut self, rhs: Self) { + self.num_dirs += rhs.num_dirs; + self.num_links += rhs.num_links; + self.num_files += rhs.num_files; + } +} +impl Add for FileCount { + type Output = Self; + /// Add [Self] with information from another [Self]. + fn add(self, rhs: Self) -> Self::Output { Self { - num_dirs, - num_files, - num_links, - }: Self, - ) { - self.num_dirs += num_dirs; - self.num_links += num_links; - self.num_files += num_files; + num_dirs: self.num_dirs + rhs.num_dirs, + num_links: self.num_links + rhs.num_links, + num_files: self.num_files + rhs.num_files, + } } } impl From> for FileCount { fn from(data: Vec) -> Self { - let mut agg = Self::default(); - - for datum in data { - agg.update_from_count(datum); - } - - agg + data.into_iter() + .fold(Self::default(), |acc, datum| acc + datum) } } @@ -57,31 +81,35 @@ impl Display for FileCount { let mut components = vec![]; if self.num_dirs > 0 { - let output = if self.num_dirs > 1 { - format!("{} {}", self.num_dirs, "directories") - } else { - format!("{} {}", self.num_dirs, "directory") - }; + let output = format!( + "{} {}", + self.num_dirs, + if self.num_dirs > 1 { + "directories" + } else { + "directory" + } + ); components.push(output); } if self.num_files > 0 { - let output = if self.num_files > 1 { - format!("{} {}", self.num_files, "files") - } else { - format!("{} {}", self.num_files, "file") - }; + let output = format!( + "{} {}", + self.num_files, + if self.num_files > 1 { "files" } else { "file" } + ); components.push(output); } if self.num_links > 0 { - let output = if self.num_links > 1 { - format!("{} {}", self.num_links, "links") - } else { - format!("{} {}", self.num_links, "link") - }; + let output = format!( + "{} {}", + self.num_links, + if self.num_links > 1 { "links" } else { "link" } + ); components.push(output); } diff --git a/src/tree/mod.rs b/src/tree/mod.rs index 399de20f..d72083d6 100644 --- a/src/tree/mod.rs +++ b/src/tree/mod.rs @@ -172,7 +172,7 @@ impl Tree { Self::filter_directories(root_id, &mut tree); } - Ok::<(Arena, NodeId), Error>((tree, root_id)) + Ok((tree, root_id)) }); let mut visitor_builder = BranchVisitorBuilder::new(ctx, Sender::clone(&tx)); @@ -257,9 +257,9 @@ impl Tree { #[cfg(not(unix))] Self::update_column_properties(column_properties, dir, ctx); - children.sort_by(|id_a, id_b| { - let node_a = tree[*id_a].get(); - let node_b = tree[*id_b].get(); + children.sort_by(|&id_a, &id_b| { + let node_a = tree[id_a].get(); + let node_b = tree[id_b].get(); node_comparator(node_a, node_b) }); @@ -308,13 +308,10 @@ impl Tree { /// directories. Files are grouped into three categories: directories, regular files, and /// symlinks. pub fn compute_file_count(node_id: NodeId, tree: &Arena) -> FileCount { - let mut count = FileCount::default(); - - for child_id in node_id.children(tree) { - count.update(tree[child_id].get()); - } - - count + node_id + .children(tree) + .map(|child_id| tree[child_id].get()) + .fold(FileCount::default(), |acc, node| acc + node) } /// Updates [`column::Properties`] with provided [`Node`]. diff --git a/src/tree/node/cmp.rs b/src/tree/node/cmp.rs index 9359fcbc..d5301c96 100644 --- a/src/tree/node/cmp.rs +++ b/src/tree/node/cmp.rs @@ -10,16 +10,14 @@ pub fn comparator(ctx: &Context) -> Box { let sort_type = ctx.sort; match ctx.dir_order { - dir::Order::None => (), dir::Order::First => { - return Box::new(move |a, b| dir_first_comparator(a, b, base_comparator(sort_type))); + Box::new(move |a, b| dir_first_comparator(a, b, base_comparator(sort_type))) } dir::Order::Last => { - return Box::new(move |a, b| dir_last_comparator(a, b, base_comparator(sort_type))); + Box::new(move |a, b| dir_last_comparator(a, b, base_comparator(sort_type))) } - }; - - base_comparator(sort_type) + dir::Order::None => base_comparator(sort_type), + } } /// Orders directories first. Provides a fallback if inputs are not directories. diff --git a/src/tree/node/mod.rs b/src/tree/node/mod.rs index fcb799cb..4d09b039 100644 --- a/src/tree/node/mod.rs +++ b/src/tree/node/mod.rs @@ -240,45 +240,42 @@ impl TryFrom<(DirEntry, &Context)> for Node { let metadata = dir_entry.metadata()?; - let style = get_ls_colors().ok().and_then(|ls_colors| { + let style = get_ls_colors().ok().map(|ls_colors| { ls_colors .style_for_path_with_metadata(path, Some(&metadata)) - .map(LS_Style::to_ansi_term_style) - .or_else(|| Some(Style::default())) + .map_or_else(Style::default, LS_Style::to_ansi_term_style) }); let file_type = dir_entry.file_type(); let file_size = match file_type { - Some(ref ft) if !ctx.suppress_size => { - if ft.is_file() || (ft.is_symlink() && !ctx.follow) { - match ctx.disk_usage { - DiskUsage::Logical => { - let metric = byte::Metric::init_logical(&metadata, ctx.unit, ctx.human); - Some(FileSize::Byte(metric)) - } - DiskUsage::Physical => { - let metric = - byte::Metric::init_physical(path, &metadata, ctx.unit, ctx.human); - Some(FileSize::Byte(metric)) - } - DiskUsage::Line => { - let metric = line_count::Metric::init(path); - metric.map(FileSize::Line) - } - DiskUsage::Word => { - let metric = word_count::Metric::init(path); - metric.map(FileSize::Word) - } - - #[cfg(unix)] - DiskUsage::Block => { - let metric = block::Metric::init(&metadata); - Some(FileSize::Block(metric)) - } + Some(ref ft) + if !ctx.suppress_size && (ft.is_file() || ft.is_symlink() && !ctx.follow) => + { + match ctx.disk_usage { + DiskUsage::Logical => { + let metric = byte::Metric::init_logical(&metadata, ctx.unit, ctx.human); + Some(FileSize::Byte(metric)) + } + DiskUsage::Physical => { + let metric = + byte::Metric::init_physical(path, &metadata, ctx.unit, ctx.human); + Some(FileSize::Byte(metric)) + } + DiskUsage::Line => { + let metric = line_count::Metric::init(path); + metric.map(FileSize::Line) + } + DiskUsage::Word => { + let metric = word_count::Metric::init(path); + metric.map(FileSize::Word) + } + + #[cfg(unix)] + DiskUsage::Block => { + let metric = block::Metric::init(&metadata); + Some(FileSize::Block(metric)) } - } else { - None } } _ => None, diff --git a/src/utils.rs b/src/utils.rs index b7356d5e..13786a7e 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,4 +1,4 @@ -use std::{borrow::ToOwned, cmp::Eq, collections::HashSet, hash::Hash}; +use std::{cmp::Eq, collections::HashSet, hash::Hash}; #[macro_export] /// Ruby-like way to crate a hashmap. @@ -25,15 +25,13 @@ macro_rules! hash { #[inline] pub fn uniq(items: Vec) -> Vec where - T: Eq + Hash + ToOwned, - ::Owned: Hash + Eq, + T: Eq + Hash, { - let mut set = HashSet::new(); - items .into_iter() - .filter(|item| set.insert(item.to_owned())) - .collect::>() + .collect::>() + .into_iter() + .collect() } /// How many integral digits are there?