From 5e97cf69877d8513bbea1f862672bbca9f543c2a Mon Sep 17 00:00:00 2001 From: Maxime Tricoire Date: Sun, 14 Apr 2024 18:32:47 +0200 Subject: [PATCH] clippy pedantic --- src/bar.rs | 8 ++++-- src/bar_items/battery.rs | 23 +++++++-------- src/bar_items/disk.rs | 2 +- src/bar_items/dunst.rs | 2 +- src/bar_items/light.rs | 2 +- src/bar_items/net_usage.rs | 14 ++++----- src/bar_items/nic.rs | 2 +- src/bar_items/pulse/custom.rs | 5 ++-- src/bar_items/pulse/mod.rs | 49 ++++++++++++++------------------ src/bar_items/pulse/structs.rs | 12 ++++---- src/bar_items/script.rs | 6 ++-- src/config/mod.rs | 4 +-- src/config/parse.rs | 10 +++---- src/context.rs | 9 ++---- src/dbus/notifications.rs | 8 +++--- src/dispatcher.rs | 5 ++-- src/i3/bar_item.rs | 2 +- src/i3/ipc.rs | 2 +- src/ipc/client.rs | 18 ++++++------ src/main.rs | 2 +- src/test_utils.rs | 4 +-- src/util/cell.rs | 2 +- src/util/enum_cycle.rs | 14 +++++---- src/util/format.rs | 2 +- src/util/net/filter.rs | 2 +- src/util/netlink/acpi/ffi.rs | 2 +- src/util/netlink/acpi/mod.rs | 4 +-- src/util/netlink/nl80211/mod.rs | 2 +- src/util/paginator.rs | 12 ++++++-- src/util/urgent.rs | 9 +++--- tests/i3/mod.rs | 50 ++++++++++++++------------------- tests/util.rs | 8 ++---- 32 files changed, 141 insertions(+), 155 deletions(-) diff --git a/src/bar.rs b/src/bar.rs index 545622f..f727afc 100644 --- a/src/bar.rs +++ b/src/bar.rs @@ -9,11 +9,13 @@ use crate::error::Result; use crate::i3::{I3Item, I3Markup}; use crate::theme::Theme; +type ColorAdjusters = HashMap HexColor>>; + pub struct Bar { /// The actual bar items - represents the latest state of each individual bar item items: Vec, /// Cache for any colour adjusters created - color_adjusters: HashMap HexColor>>, + color_adjusters: ColorAdjusters, } impl Debug for Bar { @@ -47,7 +49,7 @@ impl Bar { pub fn new(item_count: usize) -> Bar { Bar { items: vec![I3Item::empty(); item_count], - color_adjusters: HashMap::new(), + color_adjusters: ColorAdjusters::new(), } } @@ -65,7 +67,7 @@ impl Bar { /// Convert the bar to a `Value` pub fn to_value(&mut self, theme: &Theme) -> Result { - Ok(serde_json::to_value(&self.get_items(theme))?) + Ok(serde_json::to_value(self.get_items(theme))?) } fn get_items(&mut self, theme: &Theme) -> Vec { diff --git a/src/bar_items/battery.rs b/src/bar_items/battery.rs index 7a9883d..3b0d1c4 100644 --- a/src/bar_items/battery.rs +++ b/src/bar_items/battery.rs @@ -121,13 +121,11 @@ impl Bat { pub async fn get_info(&self) -> Result { let name = self.name()?.to_owned(); - Ok( - try_join!(self.percent(), self.get_state()).map(|(charge, state)| BatInfo { - name, - charge, - state, - })?, - ) + try_join!(self.percent(), self.get_state()).map(|(charge, state)| BatInfo { + name, + charge, + state, + }) } pub async fn find_all() -> Result> { @@ -188,7 +186,7 @@ impl Battery { let name = if info.name == "BAT0" { icon } else { - info.name.as_str().into() + info.name.as_str() }; I3Item::new(format!("{} {:.0}%", name, info.charge)) .short_text(format!("{:.0}%", info.charge)) @@ -205,14 +203,14 @@ impl BarItem for Battery { let mut show_watts = false; let mut p = Paginator::new(); - if batteries.len() == 0 { + if batteries.is_empty() { bail!("no batteries found"); } else { p.set_len(batteries.len())?; } let dbus = dbus_connection(BusType::Session).await?; - let notifications = NotificationsProxy::new(&dbus).await?; + let notifications = NotificationsProxy::new(dbus).await?; let mut on_acpi_event = battery_acpi_events().await?; let mut sent_critical_notification = false; loop { @@ -314,9 +312,8 @@ async fn battery_acpi_events() -> Result> { _ => continue, }; - if result.is_err() { - // SAFETY: we just checked with `.is_err()` - break result.unwrap_err(); + if let Err(err) = result { + break err; } } }; diff --git a/src/bar_items/disk.rs b/src/bar_items/disk.rs index 934a79e..431d0da 100644 --- a/src/bar_items/disk.rs +++ b/src/bar_items/disk.rs @@ -70,7 +70,7 @@ impl DiskStats { name, ByteSize(self.available_bytes).to_string_as(true) ), - format!("{}", name), + name, ) } } diff --git a/src/bar_items/dunst.rs b/src/bar_items/dunst.rs index 01f899c..548b578 100644 --- a/src/bar_items/dunst.rs +++ b/src/bar_items/dunst.rs @@ -31,7 +31,7 @@ impl BarItem for Dunst { async fn start(&self, mut ctx: Context) -> Result { // get initial state let connection = dbus_connection(BusType::Session).await?; - let dunst_proxy = DunstProxy::new(&connection).await?; + let dunst_proxy = DunstProxy::new(connection).await?; let _ = ctx .update_item(Dunst::item(&ctx.config.theme, dunst_proxy.paused().await?)) .await; diff --git a/src/bar_items/light.rs b/src/bar_items/light.rs index bb6e753..da1cf13 100644 --- a/src/bar_items/light.rs +++ b/src/bar_items/light.rs @@ -90,7 +90,7 @@ impl LightFile { } // sort by max brightness - backlights.sort_unstable_by_key(|ref pair| pair.1); + backlights.sort_unstable_by_key(|pair| pair.1); // return a light for the "brightest" backlight match backlights.last() { diff --git a/src/bar_items/net_usage.rs b/src/bar_items/net_usage.rs index cc675aa..72ec910 100644 --- a/src/bar_items/net_usage.rs +++ b/src/bar_items/net_usage.rs @@ -44,7 +44,7 @@ pub struct NetUsage { impl NetUsage { fn get_color(&self, theme: &Theme, bytes: u64) -> Option { - if self.thresholds.len() == 0 { + if self.thresholds.is_empty() { return None; } @@ -91,7 +91,7 @@ fn format_bytes(bytes: u64, si: bool, as_bits: bool) -> String { impl BarItem for NetUsage { async fn start(&self, mut ctx: Context) -> Result { let fg = |bytes: u64, theme: &Theme| { - self.get_color(&theme, bytes) + self.get_color(theme, bytes) .map(|c| format!(r#" foreground="{}""#, c)) .unwrap_or("".into()) }; @@ -126,7 +126,7 @@ impl BarItem for NetUsage { // this returns the number of bytes since the last refresh let (down, up) = networks.iter().fold((0, 0), |(d, u), (interface, net)| { - if self.ignored_interfaces.contains(&interface) { + if self.ignored_interfaces.contains(interface) { (d, u) } else { (d + net.received(), u + net.transmitted()) @@ -157,11 +157,9 @@ impl BarItem for NetUsage { .await?; // swap between bits and bytes on click - if let Some(event) = ctx.wait_for_event(Some(self.interval)).await { - if let BarEvent::Click(click) = event { - if click.button == I3Button::Left { - display.next(); - } + if let Some(BarEvent::Click(click)) = ctx.wait_for_event(Some(self.interval)).await { + if click.button == I3Button::Left { + display.next(); } } } diff --git a/src/bar_items/nic.rs b/src/bar_items/nic.rs index e62b217..6f62e83 100644 --- a/src/bar_items/nic.rs +++ b/src/bar_items/nic.rs @@ -73,7 +73,7 @@ impl<'a> Connection<'a> { Connection { name: &interface.name, - addr: &addr, + addr, detail: wireless_info.map(|info| match (info.ssid, info.signal) { (Some(ssid), Some(signal)) => { ConnectionDetail::SsidAndSignal(ssid.to_string(), signal) diff --git a/src/bar_items/pulse/custom.rs b/src/bar_items/pulse/custom.rs index 8a99c79..478c00f 100644 --- a/src/bar_items/pulse/custom.rs +++ b/src/bar_items/pulse/custom.rs @@ -126,14 +126,13 @@ impl RcCell { { let mut tx = Some(tx); let mut f = Some(failure_fn); - move |success| match (tx.take(), f.take()) { - (Some(tx), Some(f)) => { + move |success| { + if let (Some(tx), Some(f)) = (tx.take(), f.take()) { let _ = tx.send(CustomResponse::Json(json!(match success { true => PulseResponse::Success, false => PulseResponse::Failure(f()), }))); } - _ => {} } } diff --git a/src/bar_items/pulse/mod.rs b/src/bar_items/pulse/mod.rs index 549cbbd..780c3de 100644 --- a/src/bar_items/pulse/mod.rs +++ b/src/bar_items/pulse/mod.rs @@ -177,7 +177,7 @@ impl RcCell { } // get the next object (that isn't a source monitor) - let next_obj = match dir.cycle(curr_obj_idx, &objects, |o| !o.is_source_monitor) { + let next_obj = match dir.cycle(curr_obj_idx, objects, |o| !o.is_source_monitor) { Some(obj) => obj, None => return, }; @@ -219,7 +219,7 @@ impl RcCell { // groups, etc) let mut inner = self.clone(); let next_obj_index = next_obj.index; - self.set_object_port(what, next_obj_index, &next_prt_name, move |success| { + self.set_object_port(what, next_obj_index, next_prt_name, move |success| { // sometimes setting the active port doesn't change the default, so check for // that and set it ourselves if needed let should_try_set_default = success @@ -252,19 +252,15 @@ impl RcCell { log::trace!("set_{what}_port_by_index {object_idx} {port_name}"); match what { Object::Sink => { - introspect.set_sink_port_by_index(object_idx, &port_name, Some(Box::new(f))); + introspect.set_sink_port_by_index(object_idx, port_name, Some(Box::new(f))); } Object::Source => { - introspect.set_source_port_by_index(object_idx, &port_name, Some(Box::new(f))); + introspect.set_source_port_by_index(object_idx, port_name, Some(Box::new(f))); } } } - fn update_volume<'a, 'b>( - &'a self, - cv: &'b mut ChannelVolumes, - vol: Vol, - ) -> &'b mut ChannelVolumes { + fn update_volume<'b>(&self, cv: &'b mut ChannelVolumes, vol: Vol) -> &'b mut ChannelVolumes { let step = Volume::NORMAL.0 / 100; let current_pct = cv.max().0 / step; match vol { @@ -302,7 +298,7 @@ impl RcCell { F: FnMut(bool) + 'static, { log::trace!("set_volume_{what} {vol}"); - (match what { + if let Some(p) = match what { Object::Sink => self.default_sink().map(|mut p| { self.set_volume_sink(p.index, self.update_volume(&mut p.volume, vol), f); p @@ -311,12 +307,11 @@ impl RcCell { self.set_volume_source(p.index, self.update_volume(&mut p.volume, vol), f); p }), - }) - .map(|p| { + } { // send notification let _ = self.tx.send(p.notify_volume_mute()); self.play_volume_sample_if_enabled(what); - }); + } } fn set_mute(&mut self, what: Object, mute: bool, f: F) @@ -324,7 +319,7 @@ impl RcCell { F: FnMut(bool) + 'static, { log::trace!("set_mute_{what} {mute}"); - (match what { + if let Some(p) = match what { Object::Sink => self.default_sink().map(|mut p| { p.mute = mute; self.set_mute_sink(p.index, p.mute, f); @@ -335,18 +330,17 @@ impl RcCell { self.set_mute_source(p.index, p.mute, f); p }), - }) - .map(|p| { + } { let _ = self.tx.send(p.notify_volume_mute()); self.play_volume_sample_if_enabled(what); - }); + } } fn toggle_mute(&mut self, what: Object, f: F) where F: FnMut(bool) + 'static, { - (match what { + if let Some(p) = match what { Object::Sink => self.default_sink().map(|mut p| { p.mute = !p.mute; self.set_mute_sink(p.index, p.mute, f); @@ -357,11 +351,10 @@ impl RcCell { self.set_mute_source(p.index, p.mute, f); p }), - }) - .map(|p| { + } { let _ = self.tx.send(p.notify_volume_mute()); self.play_volume_sample_if_enabled(what); - }); + } } fn play_volume_sample_if_enabled(&mut self, what: Object) { @@ -516,13 +509,13 @@ impl RcCell { }); }; - info.default_sink_name - .as_ref() - .map(|name| update_if_needed(&mut inner, Object::Sink, name.to_string().into())); + if let Some(name) = info.default_sink_name.as_ref() { + update_if_needed(&mut inner, Object::Sink, name.to_string().into()) + } - info.default_source_name - .as_ref() - .map(|name| update_if_needed(&mut inner, Object::Source, name.to_string().into())); + if let Some(name) = info.default_source_name.as_ref() { + update_if_needed(&mut inner, Object::Source, name.to_string().into()) + } inner.update_item(); }); @@ -639,7 +632,7 @@ impl BarItem for Pulse { }); let dbus = dbus_connection(BusType::Session).await?; - let notifications = NotificationsProxy::new(&dbus).await?; + let notifications = NotificationsProxy::new(dbus).await?; loop { tokio::select! { // handle events diff --git a/src/bar_items/pulse/structs.rs b/src/bar_items/pulse/structs.rs index b94f4c1..7a56cdc 100644 --- a/src/bar_items/pulse/structs.rs +++ b/src/bar_items/pulse/structs.rs @@ -178,10 +178,10 @@ impl InOut { let current_idx = self.current_port_idx(); match dir { Dir::Next => self.ports[current_idx + 1..] - .into_iter() + .iter() .find(|p| p.available()), Dir::Prev => self.ports[..current_idx] - .into_iter() + .iter() .rev() .find(|p| p.available()), } @@ -207,7 +207,7 @@ impl InOut { r#"{} {}%"#, if self.mute { theme.dim } else { theme.fg }, self.port_symbol() - .unwrap_or_else(|| match (what, self.mute) { + .unwrap_or(match (what, self.mute) { (Object::Sink, false) => "", (Object::Sink, true) => "", (Object::Source, false) => "󰍬", @@ -270,20 +270,20 @@ impl Dir { /// Returns `None` if /// * `items` was empty /// * `f` excludes all items - pub fn cycle<'a, 'b, T, F>(&'a self, start: usize, items: &'b [T], f: F) -> Option<&'b T> + pub fn cycle<'b, T, F>(&self, start: usize, items: &'b [T], f: F) -> Option<&'b T> where F: Fn(&&T) -> bool, { let limit = items.len() * 2; match self { Dir::Next => items - .into_iter() + .iter() .cycle() .skip(start + 1) .take(limit) .find(f), Dir::Prev => items - .into_iter() + .iter() .rev() .cycle() .skip(items.len() - start) diff --git a/src/bar_items/script.rs b/src/bar_items/script.rs index d2f2d20..151002d 100644 --- a/src/bar_items/script.rs +++ b/src/bar_items/script.rs @@ -54,9 +54,9 @@ impl BarItem for Script { } BarEvent::Click(c) => { env.remove("I3_SIGNAL"); - c.name.map(|name| { - env.insert("I3_NAME", name.to_string()); - }); + if let Some(name) = c.name { + env.insert("I3_NAME", name); + } env.insert( "I3_MODIFIERS", c.modifiers diff --git a/src/config/mod.rs b/src/config/mod.rs index 6c04552..180d3a8 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -68,7 +68,7 @@ impl AppConfig { } /// Sort the items by reading the index defined in the configuration. - fn sort(mut items: &mut [Item]) { + fn sort(items: &mut [Item]) { let len = items.len(); let max = len.saturating_sub(1); let mut item_order = (0..len).collect::>(); @@ -79,7 +79,7 @@ impl AppConfig { } } - sort_by_indices(&mut items, item_order); + sort_by_indices(items, item_order); } /// Ensure configuration of item names have no duplicates. diff --git a/src/config/parse.rs b/src/config/parse.rs index b7b7643..96104a8 100644 --- a/src/config/parse.rs +++ b/src/config/parse.rs @@ -14,7 +14,7 @@ use crate::error::Result; fn expand_include_path(s: impl AsRef, cfg_dir: impl AsRef) -> Result> { let cfg_dir = cfg_dir.as_ref(); // perform expansion, see: man 3 wordexp - Ok(wordexp(s.as_ref(), Wordexp::new(0), 0)? + wordexp(s.as_ref(), Wordexp::new(0), 0)? .map(|path| -> Result<_> { // convert expansion to path let path = PathBuf::from(path); @@ -30,7 +30,7 @@ fn expand_include_path(s: impl AsRef, cfg_dir: impl AsRef) -> Result< } } }) - .collect::>()?) + .collect::>() } pub fn parse(args: &Cli) -> Result { @@ -39,11 +39,11 @@ pub fn parse(args: &Cli) -> Result { .as_ref() .map(|p| p.to_owned()) .or_else(|| dirs::config_dir().map(|d| d.join("i3stat/config"))) - .ok_or_else(|| "failed to find config file")?; + .ok_or("failed to find config file")?; let cfg_dir = cfg_file .parent() - .ok_or_else(|| "failed to find config dir")?; + .ok_or("failed to find config dir")?; // main configuration file let mut figment = Figment::new() @@ -64,7 +64,7 @@ pub fn parse(args: &Cli) -> Result { Ok(user_paths) => { let mut paths = vec![]; for unexpanded in user_paths { - match expand_include_path(&unexpanded, &cfg_dir) { + match expand_include_path(&unexpanded, cfg_dir) { Ok(path) => paths.extend(path), Err(e) => { log::warn!("failed to include config '{}': {}", unexpanded, e); diff --git a/src/context.rs b/src/context.rs index 9c412e4..62ec6e0 100644 --- a/src/context.rs +++ b/src/context.rs @@ -5,7 +5,7 @@ use clap::builder::StyledStr; use futures::Future; use serde_json::Value; use sysinfo::{System, SystemExt}; -use tokio::sync::mpsc::error::{SendError, TryRecvError}; +use tokio::sync::mpsc::error::SendError; use tokio::sync::{mpsc, oneshot}; use tokio::time::sleep; @@ -97,11 +97,8 @@ impl Context { tokio::select! { Some(event) = self.rx_event.recv() => { closure(event).await; - loop { - match self.rx_event.try_recv() { - Ok(event) => closure(event).await, - Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected)=> break, - } + while let Ok(event) = self.rx_event.try_recv() { + closure(event).await } } _ = sleep(duration) => {} diff --git a/src/dbus/notifications.rs b/src/dbus/notifications.rs index a2b5a04..edd1aba 100644 --- a/src/dbus/notifications.rs +++ b/src/dbus/notifications.rs @@ -16,6 +16,7 @@ type Hints = HashMap<&'static str, Value<'static>>; )] trait Notifications { #[dbus_proxy(name = "Notify")] + #[allow(clippy::too_many_arguments)] fn notify_full( &self, app_name: &str, @@ -106,14 +107,13 @@ impl<'a> NotificationsProxy<'a> { timeout: i32, ) { let cached_id = once_cell.get().cloned(); - match self.notify(cached_id, hints, summary, body, timeout).await { - Some(id) => match cached_id { + if let Some(id) = self.notify(cached_id, hints, summary, body, timeout).await { + match cached_id { Some(_) => { /* do nothing, id already saved */ } None => { let _ = once_cell.set(id); } - }, - None => { /* do nothing, an error occurred */ } + } } } diff --git a/src/dispatcher.rs b/src/dispatcher.rs index 39abf7a..3b27c54 100644 --- a/src/dispatcher.rs +++ b/src/dispatcher.rs @@ -35,7 +35,7 @@ impl Dispatcher { /// Send `BarEvent::Signal` to all bar items pub async fn signal_all(&self) -> Result<()> { - Ok(join_all( + join_all( self.bar_senders .iter() .enumerate() @@ -47,7 +47,8 @@ impl Dispatcher { if let Err(e) = r { log::warn!("{}", e); } - })) + }); + Ok(()) } /// Send the given `BarEvent` to the item at the given index diff --git a/src/i3/bar_item.rs b/src/i3/bar_item.rs index 821985c..b715b55 100644 --- a/src/i3/bar_item.rs +++ b/src/i3/bar_item.rs @@ -51,7 +51,7 @@ impl Serialize for I3MinWidth { match self { I3MinWidth::Pixels(n) => serializer.serialize_u64(*n as u64), I3MinWidth::StringCount(n) => serializer.serialize_str(&"x".repeat(*n)), - I3MinWidth::String(s) => serializer.serialize_str(&s), + I3MinWidth::String(s) => serializer.serialize_str(s), } } } diff --git a/src/i3/ipc.rs b/src/i3/ipc.rs index 4f3258f..6111a6c 100644 --- a/src/i3/ipc.rs +++ b/src/i3/ipc.rs @@ -24,7 +24,7 @@ pub async fn handle_click_events( let mut line = lines .next_line() .await? - .ok_or_else(|| "received unexpected end of STDIN")?; + .ok_or("received unexpected end of STDIN")?; // skip opening array as part of the protocol if line.trim() == "[" { diff --git a/src/ipc/client.rs b/src/ipc/client.rs index 7b8e5ba..c6d578e 100644 --- a/src/ipc/client.rs +++ b/src/ipc/client.rs @@ -68,30 +68,30 @@ async fn handle_ipc_request(stream: &UnixStream, mut ctx: IpcContext, len: usize let msg = serde_json::from_slice::(&buf)?; match msg { IpcMessage::Shutdown => { - send_ipc_response(&stream, &IpcReply::Result(IpcResult::Success(None))).await?; + send_ipc_response(stream, &IpcReply::Result(IpcResult::Success(None))).await?; ctx.token.cancel(); } IpcMessage::GetBar => { send_ipc_response( - &stream, + stream, &IpcReply::Value(ctx.bar.to_value(&ctx.config.theme)?), ) .await?; } IpcMessage::Info => { let info = serde_json::to_value(ctx.config.item_idx_to_name())?; - send_ipc_response(&stream, &IpcReply::Value(info)).await?; + send_ipc_response(stream, &IpcReply::Value(info)).await?; } IpcMessage::GetConfig => { send_ipc_response( - &stream, + stream, &IpcReply::Value(serde_json::to_value(&*ctx.config)?), ) .await?; } IpcMessage::GetTheme => { send_ipc_response( - &stream, + stream, &IpcReply::Value(serde_json::to_value(&ctx.config.theme)?), ) .await?; @@ -104,12 +104,12 @@ async fn handle_ipc_request(stream: &UnixStream, mut ctx: IpcContext, len: usize } Err(e) => IpcReply::Result(IpcResult::Failure(e.to_string())), }; - send_ipc_response(&stream, &reply).await?; + send_ipc_response(stream, &reply).await?; ctx.dispatcher.manual_bar_update().await?; } IpcMessage::RefreshAll => { ctx.dispatcher.signal_all().await?; - send_ipc_response(&stream, &IpcReply::Result(IpcResult::Success(None))).await?; + send_ipc_response(stream, &IpcReply::Result(IpcResult::Success(None))).await?; } IpcMessage::BarEvent { instance, event } => { // NOTE: special considerations here for `instance`: if it's a number, then it maps to the item at the index @@ -137,7 +137,7 @@ async fn handle_ipc_request(stream: &UnixStream, mut ctx: IpcContext, len: usize None => { let err = format!("failed to parse ipc instance property: {}", e); log::warn!("{}", err); - send_ipc_response(&stream, &IpcReply::Result(IpcResult::Failure(err))) + send_ipc_response(stream, &IpcReply::Result(IpcResult::Failure(err))) .await?; return Ok(()); @@ -171,7 +171,7 @@ async fn handle_ipc_request(stream: &UnixStream, mut ctx: IpcContext, len: usize IpcReply::Result(IpcResult::Failure(e.to_string())) } }; - send_ipc_response(&stream, &reply).await?; + send_ipc_response(stream, &reply).await?; } } diff --git a/src/main.rs b/src/main.rs index 7c56520..cc0e72f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -81,7 +81,7 @@ async fn async_main(args: Cli) -> Result { // if we reach here, then something went wrong, so clean up signal_handle.close(); - return result; + result } fn setup_i3_bar(config: &RcCell) -> Result<(RcCell, RcCell)> { diff --git a/src/test_utils.rs b/src/test_utils.rs index 9c79b5d..c624c6a 100644 --- a/src/test_utils.rs +++ b/src/test_utils.rs @@ -28,11 +28,11 @@ fn m( None => format!("{}.1", cmd_name), }; - create_dir_all(&dir)?; + create_dir_all(dir)?; write(dir.join(&file_name), buf)?; for sub in cmd.get_subcommands() { - m(sub, dir, Some(&cmd_name))?; + m(sub, dir, Some(cmd_name))?; } Ok(()) diff --git a/src/util/cell.rs b/src/util/cell.rs index 77ded13..0916930 100644 --- a/src/util/cell.rs +++ b/src/util/cell.rs @@ -39,7 +39,7 @@ impl Deref for RcCell { type Target = T; fn deref(&self) -> &Self::Target { - &self.get() + self.get() } } diff --git a/src/util/enum_cycle.rs b/src/util/enum_cycle.rs index 9202ff2..20c4244 100644 --- a/src/util/enum_cycle.rs +++ b/src/util/enum_cycle.rs @@ -9,6 +9,15 @@ pub struct EnumCycle { inner: Peekable>>, } +impl Iterator for EnumCycle { + type Item = T; + + fn next(&mut self) -> Option { + // SAFETY: `self.inner` is a cycling iterator that has at least one variant + self.inner.next() + } +} + impl EnumCycle { /// Creates a new `EnumCycle` for the given type. /// Returns an error if the enum doesn't have at least one variant. @@ -27,11 +36,6 @@ impl EnumCycle { // SAFETY: `self.inner` is a cycling iterator that has at least one variant self.inner.peek().unwrap() } - - pub fn next(&mut self) -> T { - // SAFETY: `self.inner` is a cycling iterator that has at least one variant - self.inner.next().unwrap() - } } impl EnumCycle { diff --git a/src/util/format.rs b/src/util/format.rs index d01e824..0a3047f 100644 --- a/src/util/format.rs +++ b/src/util/format.rs @@ -50,7 +50,7 @@ pub fn float(n: F, fmt: &FloatFormat) -> String { let pad_char = fmt.pad.unwrap_or(' '); let precision = fmt.precision.unwrap_or(0); - let pad_count = fmt.pad_count.unwrap_or_else(|| { + let pad_count = fmt.pad_count.unwrap_or({ if precision > 0 { // three digits (e.g., 100%) + decimal separator 3 + 1 diff --git a/src/util/net/filter.rs b/src/util/net/filter.rs index 2f95369..37bced4 100644 --- a/src/util/net/filter.rs +++ b/src/util/net/filter.rs @@ -151,7 +151,7 @@ mod tests { #[test] fn interface_filter_ser() { - let to_s = |i| serde_json::to_value(&i).unwrap(); + let to_s = |i| serde_json::to_value(i).unwrap(); assert_eq!(to_s(InterfaceFilter::new("foo", None)), "foo"); assert_eq!( diff --git a/src/util/netlink/acpi/ffi.rs b/src/util/netlink/acpi/ffi.rs index 4c25bbe..b6fc201 100644 --- a/src/util/netlink/acpi/ffi.rs +++ b/src/util/netlink/acpi/ffi.rs @@ -59,7 +59,7 @@ fn get_u8_bytes(slice: &[c_char]) -> Result> { // `TypeId` returns a constant value, so it's just as good as a compile-time check. if TypeId::of::() == TypeId::of::() { slice - .into_iter() + .iter() .take_while(|c| **c != 0) .map(|c| -> Result { #[allow(unused_comparisons)] diff --git a/src/util/netlink/acpi/mod.rs b/src/util/netlink/acpi/mod.rs index 34c78e1..7c1c935 100644 --- a/src/util/netlink/acpi/mod.rs +++ b/src/util/netlink/acpi/mod.rs @@ -92,9 +92,9 @@ static ACPI_EVENT_IDS: OnceCell<(u16, u32)> = OnceCell::const_new(); /// Initialises local cache of the required ACPI netlink ids /// You can see these with the tool `genl-ctrl-list`. async fn init_ids() -> Result<&'static (u16, u32)> { - Ok(ACPI_EVENT_IDS + ACPI_EVENT_IDS .get_or_try_init(get_acpi_id_from_netlink) - .await?) + .await } async fn event_family_id() -> Result { diff --git a/src/util/netlink/nl80211/mod.rs b/src/util/netlink/nl80211/mod.rs index f6ff9c8..761af1f 100644 --- a/src/util/netlink/nl80211/mod.rs +++ b/src/util/netlink/nl80211/mod.rs @@ -357,7 +357,7 @@ async fn get_scan( // extract the bssid itself let bssid = match bss_attrs .get_attr_payload_as_with_len_borrowed::<&[u8]>(Nl80211Bss::Bssid) - .map(|bytes| MacAddr::try_from(bytes)) + .map(MacAddr::try_from) { Ok(Ok(mac_addr)) => mac_addr, // if we can't find a bssid, then keep looking for another one diff --git a/src/util/paginator.rs b/src/util/paginator.rs index 88764ed..7ea74d0 100644 --- a/src/util/paginator.rs +++ b/src/util/paginator.rs @@ -11,11 +11,19 @@ pub struct Paginator { len: usize, } +impl Default for Paginator { + fn default() -> Self { + Self { idx: 0, len: 1 } + } +} + impl Paginator { - pub fn new() -> Paginator { - Paginator { idx: 0, len: 1 } + #[inline] + pub fn new() -> Self { + Self::default() } + #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> usize { self.len } diff --git a/src/util/urgent.rs b/src/util/urgent.rs index f5f2398..a915335 100644 --- a/src/util/urgent.rs +++ b/src/util/urgent.rs @@ -1,5 +1,6 @@ use std::time::{Duration, Instant}; +#[derive(Default)] pub struct UrgentTimer { /// If set, then the timer is active. Marks the start of the timer. started: Option, @@ -8,11 +9,9 @@ pub struct UrgentTimer { } impl UrgentTimer { + #[inline] pub fn new() -> UrgentTimer { - UrgentTimer { - started: None, - swapped: false, - } + UrgentTimer::default() } pub fn swapped(&self) -> bool { @@ -22,7 +21,7 @@ impl UrgentTimer { pub fn toggle(&mut self, on: bool) { match on { true => { - if let None = self.started { + if self.started.is_none() { self.reset_timer(); self.swapped = false; } diff --git a/tests/i3/mod.rs b/tests/i3/mod.rs index e9345af..ae02c63 100644 --- a/tests/i3/mod.rs +++ b/tests/i3/mod.rs @@ -11,15 +11,8 @@ use serde_json::Value; use self::util::x_click; use crate::i3::util::MouseButton; use crate::util::{ - find_object_containing, - get_current_exe, - get_exe, - get_fakeroot_lib, - get_faketime_lib, - wait_for_file, - LogOnDropChild, - Test, - FAKE_TIME, + find_object_containing, get_current_exe, get_exe, get_fakeroot_lib, get_faketime_lib, + wait_for_file, LogOnDropChild, Test, FAKE_TIME, }; // start nested x server displays at 10 @@ -156,7 +149,7 @@ impl<'a> X11Test<'a> { wait_for_file(&i3_socket, MAX_WAIT_TIME); // wait for i3stat's socket to appear - wait_for_file(&i3stat_socket, MAX_WAIT_TIME); + wait_for_file(i3stat_socket, MAX_WAIT_TIME); let screenshots_dir = PathBuf::from(SCREENSHOTS_DIR); fs::create_dir_all(&screenshots_dir).unwrap(); @@ -184,7 +177,7 @@ impl<'a> X11Test<'a> { .env("FAKEROOT", &self.test.fakeroot) .env("FAKEROOT_DIRS", "1") .arg("-c") - .arg(format!("{}", cmd.as_ref())) + .arg(cmd.as_ref()) .output() .unwrap() } @@ -265,24 +258,23 @@ impl<'a> X11Test<'a> { self.screenshot_file.with_file_name(name) }; - self.cmd(format!( - "{scrot} | {convert} > {file}", - scrot = format!( - "scrot --autoselect {x},{y},{w},{h} -", - x = x, - y = y, - w = w, - h = h - ), - convert = format!( - "convert - -crop {w}x{h}+{x}+{y} -", - w = w, - h = h, - x = w / 2, - y = y, - ), - file = file.display() - )); + let scrot = format!( + "scrot --autoselect {x},{y},{w},{h} -", + x = x, + y = y, + w = w, + h = h + ); + let convert = format!( + "convert - -crop {w}x{h}+{x}+{y} -", + w = w, + h = h, + x = w / 2, + y = y, + ); + let file = file.display(); + + self.cmd(format!("{scrot} | {convert} > {file}")); } } diff --git a/tests/util.rs b/tests/util.rs index 7337294..6df2edb 100644 --- a/tests/util.rs +++ b/tests/util.rs @@ -26,7 +26,7 @@ const FAKE_TIME_LIB_PATHS: &[&str] = &[ pub fn get_faketime_lib() -> &'static str { for path in FAKE_TIME_LIB_PATHS { if PathBuf::from(path).exists() { - return *path; + return path; } } @@ -217,11 +217,7 @@ impl Test { pub fn add_fake_file(&self, name: impl AsRef, contents: impl AsRef) { let name = name.as_ref(); - let name = if name.starts_with("/") { - &name[1..] - } else { - name - }; + let name = name.strip_prefix('/').unwrap_or(name); let path = self.fakeroot.join(name); fs::create_dir_all(path.parent().unwrap()).unwrap();