diff --git a/bidi/generate/src/main.rs b/bidi/generate/src/main.rs index f786ba6ae0c..2ae64e782ec 100644 --- a/bidi/generate/src/main.rs +++ b/bidi/generate/src/main.rs @@ -19,7 +19,7 @@ fn gen_class() -> anyhow::Result<()> { impl Entry { fn parse(line: &str) -> anyhow::Result> { let line = line.trim(); - if line.starts_with("#") || line.is_empty() { + if line.starts_with('#') || line.is_empty() { return Ok(None); } let fields: Vec<&str> = line.split(';').collect(); @@ -152,7 +152,7 @@ fn gen_brackets() -> anyhow::Result<()> { impl Entry { fn parse(line: &str) -> anyhow::Result> { let line = line.trim(); - if line.starts_with("#") || line.is_empty() { + if line.starts_with('#') || line.is_empty() { return Ok(None); } let fields: Vec<&str> = line.split(';').collect(); diff --git a/bidi/src/bidi_brackets.rs b/bidi/src/bidi_brackets.rs index 00a6a1b16dc..0e70cc3e077 100644 --- a/bidi/src/bidi_brackets.rs +++ b/bidi/src/bidi_brackets.rs @@ -5,7 +5,7 @@ pub enum BracketType { Open, Close, } -pub const BIDI_BRACKETS: &'static [(char, char, BracketType)] = &[ +pub const BIDI_BRACKETS: &[(char, char, BracketType)] = &[ ('\u{28}', '\u{29}', BracketType::Open), // LEFT PARENTHESIS ('\u{29}', '\u{28}', BracketType::Close), // RIGHT PARENTHESIS ('\u{5b}', '\u{5d}', BracketType::Open), // LEFT SQUARE BRACKET diff --git a/bidi/src/bidi_class.rs b/bidi/src/bidi_class.rs index 08db0b3fd29..74a34bad543 100644 --- a/bidi/src/bidi_class.rs +++ b/bidi/src/bidi_class.rs @@ -28,7 +28,7 @@ pub enum BidiClass { WhiteSpace, } -pub const BIDI_CLASS: &'static [(char, char, BidiClass)] = &[ +pub const BIDI_CLASS: &[(char, char, BidiClass)] = &[ ('\u{0}', '\u{8}', BidiClass::BoundaryNeutral), // Cc [9] .. ('\u{9}', '\u{9}', BidiClass::SegmentSeparator), // Cc ('\u{a}', '\u{a}', BidiClass::ParagraphSeparator), // Cc diff --git a/bidi/src/lib.rs b/bidi/src/lib.rs index 1dd68f72be3..607dce80464 100644 --- a/bidi/src/lib.rs +++ b/bidi/src/lib.rs @@ -94,7 +94,7 @@ pub struct BidiRun { } impl BidiRun { - pub fn indices<'a>(&'a self) -> impl Iterator + 'a { + pub fn indices(&self) -> impl Iterator + '_ { struct Iter<'a> { range: Range, removed_by_x9: &'a [usize], @@ -206,7 +206,7 @@ impl BidiContext { /// Produces a sequence of `BidiRun` structs that represent runs of /// text and their direction (and level) across the entire paragraph. - pub fn runs<'a>(&'a self) -> impl Iterator + 'a { + pub fn runs(&self) -> impl Iterator + '_ { RunIter { pos: 0, levels: Cow::Borrowed(&self.levels), @@ -357,7 +357,7 @@ impl BidiContext { // Initial visual order let mut visual = vec![]; - for i in 0..levels.len() { + for (i, _) in levels.iter().enumerate() { if levels[i].removed_by_x9() { visual.push(DELETED); } else { @@ -843,7 +843,7 @@ impl BidiContext { // of the substring in this isolating run sequence // enclosed by those brackets (inclusive // of the brackets). Resolve that individual pair. - self.resolve_one_pair(pair, &iso_run); + self.resolve_one_pair(pair, iso_run); } } } @@ -997,7 +997,6 @@ impl BidiContext { &self.orig_char_types, &self.levels, ); - return; } else { // No strong type matching the oppositedirection was found either // before or after these brackets in this text chain. Resolve the @@ -1010,7 +1009,6 @@ impl BidiContext { &self.orig_char_types, &self.levels, ); - return; } } else { // No strong type was found between the brackets. Leave @@ -1262,7 +1260,7 @@ impl BidiContext { line_range: Range, base_level: Level, orig_char_types: &[BidiClass], - levels: &mut Vec, + levels: &mut [Level], ) { for i in line_range.rev() { if orig_char_types[i] == BidiClass::WhiteSpace @@ -1458,12 +1456,8 @@ impl BidiContext { // Do nothing } else if overflow_embedding > 0 { overflow_embedding -= 1; - } else { - if !stack.isolate_status() { - if stack.depth() >= 2 { - stack.pop(); - } - } + } else if !stack.isolate_status() && stack.depth() >= 2 { + stack.pop(); } } BidiClass::BoundaryNeutral => {} @@ -1709,22 +1703,22 @@ impl BidiContext { impl BidiClass { pub fn is_iso_init(self) -> bool { - match self { + matches!( + self, BidiClass::RightToLeftIsolate - | BidiClass::LeftToRightIsolate - | BidiClass::FirstStrongIsolate => true, - _ => false, - } + | BidiClass::LeftToRightIsolate + | BidiClass::FirstStrongIsolate + ) } pub fn is_iso_control(self) -> bool { - match self { + matches!( + self, BidiClass::RightToLeftIsolate - | BidiClass::LeftToRightIsolate - | BidiClass::PopDirectionalIsolate - | BidiClass::FirstStrongIsolate => true, - _ => false, - } + | BidiClass::LeftToRightIsolate + | BidiClass::PopDirectionalIsolate + | BidiClass::FirstStrongIsolate + ) } pub fn is_neutral(self) -> bool { diff --git a/bintree/src/lib.rs b/bintree/src/lib.rs index 189ac28d672..01550364e8f 100644 --- a/bintree/src/lib.rs +++ b/bintree/src/lib.rs @@ -159,11 +159,11 @@ impl<'a, L, N> std::iter::Iterator for ParentIterator<'a, L, N> { match self.path { Path::Top => None, Path::Left { data, up, .. } => { - self.path = &*up; + self.path = up; Some((PathBranch::IsLeft, data)) } Path::Right { data, up, .. } => { - self.path = &*up; + self.path = up; Some((PathBranch::IsRight, data)) } } @@ -211,7 +211,7 @@ impl Cursor { /// References the subtree at the current cursor position pub fn subtree(&self) -> &Tree { - &*self.it + &self.it } /// Returns true if the current position is a leaf node diff --git a/color-types/src/lib.rs b/color-types/src/lib.rs index bd12a1ae3cd..0d7943b9fab 100644 --- a/color-types/src/lib.rs +++ b/color-types/src/lib.rs @@ -2,6 +2,7 @@ use csscolorparser::Color; #[cfg(feature = "use_serde")] use serde::{Deserialize, Serialize}; use std::collections::HashMap; +use std::fmt::Display; use std::hash::{Hash, Hasher}; use std::str::FromStr; use wezterm_dynamic::{FromDynamic, FromDynamicOptions, ToDynamic, Value}; @@ -407,14 +408,6 @@ impl SrgbaTuple { ) } - pub fn to_string(self) -> String { - if self.3 == 1.0 { - self.to_rgb_string() - } else { - self.to_rgba_string() - } - } - /// Returns a string of the form `#RRGGBB` pub fn to_rgb_string(self) -> String { format!( @@ -551,6 +544,16 @@ impl SrgbaTuple { } } +impl Display for SrgbaTuple { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.3 == 1.0 { + write!(f, "{}", self.to_rgb_string()) + } else { + write!(f, "{}", self.to_rgba_string()) + } + } +} + /// Convert an RGB color space hue angle to an RYB colorspace hue angle /// fn rgb_hue_to_ryb_hue(hue: f64) -> f64 { @@ -631,7 +634,7 @@ fn x_parse_color_component(value: &str) -> Result { for c in value.chars() { num_digits += 1; - component = component << 4; + component <<= 4; let nybble = match c.to_digit(16) { Some(v) => v as u16, @@ -659,7 +662,7 @@ impl FromStr for SrgbaTuple { if !s.is_ascii() { return Err(()); } - if s.len() > 0 && s.as_bytes()[0] == b'#' { + if !s.is_empty() && s.as_bytes()[0] == b'#' { // Probably `#RGB` let digits = (s.len() - 1) / 3; @@ -679,7 +682,7 @@ impl FromStr for SrgbaTuple { let mut component = 0u16; for _ in 0..digits { - component = component << 4; + component <<= 4; let nybble = match chars.next().unwrap().to_digit(16) { Some(v) => v as u16, @@ -730,7 +733,7 @@ impl FromStr for SrgbaTuple { Ok(v / 100.) } else { let v: f32 = s.parse().map_err(|_| ())?; - if v > 255.0 || v < 0. { + if !(0. ..=255.0).contains(&v) { Err(()) } else { Ok(v / 255.) @@ -746,8 +749,8 @@ impl FromStr for SrgbaTuple { } else { Err(()) } - } else if s.starts_with("hsl:") { - let fields: Vec<_> = s[4..].split_ascii_whitespace().collect(); + } else if let Some(stripped) = s.strip_prefix("hsl:") { + let fields: Vec<_> = stripped.split_ascii_whitespace().collect(); if fields.len() == 3 { // Expected to be degrees in range 0-360, but we allow for negative and wrapping let h: i32 = fields[0].parse().map_err(|_| ())?; diff --git a/deps/freetype/build.rs b/deps/freetype/build.rs index b4a8407b83c..ec3f443a0eb 100644 --- a/deps/freetype/build.rs +++ b/deps/freetype/build.rs @@ -230,7 +230,7 @@ fn freetype() { fn git_submodule_update() { let _ = std::process::Command::new("git") - .args(&["submodule", "update", "--init"]) + .args(["submodule", "update", "--init"]) .status(); } diff --git a/deps/freetype/src/lib.rs b/deps/freetype/src/lib.rs index 476412d887c..14ace3fab09 100644 --- a/deps/freetype/src/lib.rs +++ b/deps/freetype/src/lib.rs @@ -40,7 +40,7 @@ impl ::std::default::Default for __BindgenUnionField { impl ::std::clone::Clone for __BindgenUnionField { #[inline] fn clone(&self) -> Self { - Self::new() + *self } } impl ::std::marker::Copy for __BindgenUnionField {} diff --git a/deps/harfbuzz/build.rs b/deps/harfbuzz/build.rs index 98c372e71a5..8e7a3fcc6aa 100644 --- a/deps/harfbuzz/build.rs +++ b/deps/harfbuzz/build.rs @@ -60,7 +60,7 @@ fn harfbuzz() { fn git_submodule_update() { let _ = std::process::Command::new("git") - .args(&["submodule", "update", "--init"]) + .args(["submodule", "update", "--init"]) .status(); } diff --git a/luahelper/src/enumctor.rs b/luahelper/src/enumctor.rs index 1f4d998bf3f..32241288404 100644 --- a/luahelper/src/enumctor.rs +++ b/luahelper/src/enumctor.rs @@ -109,6 +109,12 @@ impl Enum { } } +impl Default for Enum { + fn default() -> Self { + Self::new() + } +} + impl UserData for Enum where T: FromDynamic, @@ -133,14 +139,16 @@ where methods.add_meta_method(MetaMethod::Index, |lua, _myself, field: String| { // Step 1: see if this is a unit variant. // A unit variant will be convertible from string - if let Ok(_) = T::from_dynamic( + if T::from_dynamic( &DynValue::String(field.to_string()), FromDynamicOptions { unknown_fields: UnknownFieldAction::Deny, deprecated_fields: UnknownFieldAction::Ignore, }, - ) { - return Ok(field.into_lua(lua)?); + ) + .is_ok() + { + return field.into_lua(lua); } // Step 2: see if this is a valid variant, and whether we can diff --git a/luahelper/src/lib.rs b/luahelper/src/lib.rs index 80e78432c7d..1d7f57caf22 100644 --- a/luahelper/src/lib.rs +++ b/luahelper/src/lib.rs @@ -9,15 +9,12 @@ use wezterm_dynamic::{FromDynamic, ToDynamic, Value as DynValue}; pub mod enumctor; -pub fn to_lua<'lua, T: ToDynamic>( - lua: &'lua mlua::Lua, - value: T, -) -> Result, mlua::Error> { +pub fn to_lua(lua: &mlua::Lua, value: T) -> Result, mlua::Error> { let value = value.to_dynamic(); dynamic_to_lua_value(lua, value) } -pub fn from_lua<'lua, T: FromDynamic>(value: mlua::Value<'lua>) -> Result { +pub fn from_lua(value: mlua::Value<'_>) -> Result { let lua_type = value.type_name(); let value = lua_value_to_dynamic(value).map_err(|e| mlua::Error::FromLuaConversionError { from: lua_type, @@ -60,10 +57,7 @@ macro_rules! impl_lua_conversion_dynamic { }; } -pub fn dynamic_to_lua_value<'lua>( - lua: &'lua mlua::Lua, - value: DynValue, -) -> mlua::Result { +pub fn dynamic_to_lua_value(lua: &mlua::Lua, value: DynValue) -> mlua::Result { Ok(match value { DynValue::Null => LuaValue::Nil, DynValue::Bool(b) => LuaValue::Boolean(b), @@ -284,9 +278,7 @@ impl<'lua> Eq for ValuePrinterHelper<'lua> {} impl<'lua> PartialOrd for ValuePrinterHelper<'lua> { fn partial_cmp(&self, rhs: &Self) -> Option { - let lhs = lua_value_to_dynamic(self.value.clone()).unwrap_or(DynValue::Null); - let rhs = lua_value_to_dynamic(rhs.value.clone()).unwrap_or(DynValue::Null); - lhs.partial_cmp(&rhs) + Some(self.cmp(rhs)) } } @@ -343,7 +335,7 @@ impl<'lua> std::fmt::Debug for ValuePrinterHelper<'lua> { self.visited .borrow_mut() .insert(self.value.to_pointer() as usize); - if is_array_style_table(&t) { + if is_array_style_table(t) { // Treat as list let mut list = fmt.debug_list(); for value in t.clone().sequence_values() { diff --git a/procinfo/src/linux.rs b/procinfo/src/linux.rs index 5170a2c0dcb..b3f11b516f2 100644 --- a/procinfo/src/linux.rs +++ b/procinfo/src/linux.rs @@ -36,14 +36,12 @@ impl LocalProcessInfo { fn all_pids() -> Vec { let mut pids = vec![]; if let Ok(dir) = std::fs::read_dir("/proc") { - for entry in dir { - if let Ok(entry) = entry { - if let Ok(file_type) = entry.file_type() { - if file_type.is_dir() { - if let Some(name) = entry.file_name().to_str() { - if let Ok(pid) = name.parse::() { - pids.push(pid); - } + for entry in dir.flatten() { + if let Ok(file_type) = entry.file_type() { + if file_type.is_dir() { + if let Some(name) = entry.file_name().to_str() { + if let Ok(pid) = name.parse::() { + pids.push(pid); } } } @@ -78,11 +76,11 @@ impl LocalProcessInfo { } fn exe_for_pid(pid: pid_t) -> PathBuf { - std::fs::read_link(format!("/proc/{}/exe", pid)).unwrap_or_else(|_| PathBuf::new()) + std::fs::read_link(format!("/proc/{}/exe", pid)).unwrap_or_default() } fn cwd_for_pid(pid: pid_t) -> PathBuf { - LocalProcessInfo::current_working_dir(pid as u32).unwrap_or_else(PathBuf::new) + LocalProcessInfo::current_working_dir(pid as u32).unwrap_or_default() } fn parse_cmdline(pid: pid_t) -> Vec { @@ -96,7 +94,7 @@ impl LocalProcessInfo { let data = data.strip_suffix(&[0]).unwrap_or(&data); for arg in data.split(|&c| c == 0) { - args.push(String::from_utf8_lossy(arg).to_owned().to_string()); + args.push(String::from_utf8_lossy(arg).to_string()); } args @@ -130,10 +128,9 @@ impl LocalProcessInfo { } } - if let Some(info) = procs.iter().find(|info| info.pid == pid) { - Some(build_proc(info, &procs)) - } else { - None - } + procs + .iter() + .find(|info| info.pid == pid) + .map(|info| build_proc(info, &procs)) } } diff --git a/procinfo/src/macos.rs b/procinfo/src/macos.rs index 4c2aeedae96..261d9a2d9bd 100644 --- a/procinfo/src/macos.rs +++ b/procinfo/src/macos.rs @@ -220,7 +220,7 @@ fn parse_exe_and_argv_sysctl(buf: Vec) -> Option<(PathBuf, Vec)> { fn consume_cstr(ptr: &mut &[u8]) -> Option { // Parse to the end of a null terminated string let nul = ptr.iter().position(|&c| c == 0)?; - let s = String::from_utf8_lossy(&ptr[0..nul]).to_owned().to_string(); + let s = String::from_utf8_lossy(&ptr[0..nul]).to_string(); *ptr = ptr.get(nul + 1..)?; // Find the position of the first non null byte. `.position()` diff --git a/promise/src/spawn.rs b/promise/src/spawn.rs index 16fc553a8c6..5e5ab6eeaba 100644 --- a/promise/src/spawn.rs +++ b/promise/src/spawn.rs @@ -223,6 +223,12 @@ impl SimpleExecutor { } } +impl Default for SimpleExecutor { + fn default() -> Self { + Self::new() + } +} + pub struct ScopedExecutor {} impl ScopedExecutor { @@ -243,6 +249,12 @@ impl ScopedExecutor { } } +impl Default for ScopedExecutor { + fn default() -> Self { + Self::new() + } +} + impl Drop for ScopedExecutor { fn drop(&mut self) { SCOPED_EXECUTOR.lock().unwrap().take(); diff --git a/pty/src/cmdbuilder.rs b/pty/src/cmdbuilder.rs index 967e081e895..a3da75f4c6a 100644 --- a/pty/src/cmdbuilder.rs +++ b/pty/src/cmdbuilder.rs @@ -306,7 +306,7 @@ impl CommandBuilder { EnvEntry { is_from_base_env: false, preferred_key: key, - value: value, + value, }, ); } @@ -446,7 +446,7 @@ impl CommandBuilder { if let Some(path) = self.resolve_path() { for path in std::env::split_paths(&path) { - let candidate = cwd.join(&path).join(&exe); + let candidate = cwd.join(path).join(exe); if candidate.is_dir() { errors.push(format!("{} exists but is a directory", candidate.display())); @@ -499,8 +499,7 @@ impl CommandBuilder { let home = self.get_home_dir()?; let dir: &OsStr = self .cwd - .as_ref() - .map(|dir| dir.as_os_str()) + .as_deref() .filter(|dir| std::path::Path::new(dir).is_dir()) .unwrap_or(home.as_ref()); let shell = self.get_shell(); @@ -515,7 +514,7 @@ impl CommandBuilder { cmd } else { let resolved = self.search_path(&self.args[0], dir)?; - let mut cmd = std::process::Command::new(&resolved); + let mut cmd = std::process::Command::new(resolved); cmd.arg0(&self.args[0]); cmd.args(&self.args[1..]); cmd @@ -552,7 +551,7 @@ impl CommandBuilder { } } - get_shell().into() + get_shell() } fn get_home_dir(&self) -> anyhow::Result { diff --git a/pty/src/lib.rs b/pty/src/lib.rs index beb232d65c3..fc2bfa4986b 100644 --- a/pty/src/lib.rs +++ b/pty/src/lib.rs @@ -39,8 +39,6 @@ //! use anyhow::Error; use downcast_rs::{impl_downcast, Downcast}; -#[cfg(unix)] -use libc; #[cfg(feature = "serde_support")] use serde_derive::*; use std::io::Result as IoResult; @@ -270,10 +268,7 @@ impl_downcast!(PtySystem); impl Child for std::process::Child { fn try_wait(&mut self) -> IoResult> { - std::process::Child::try_wait(self).map(|s| match s { - Some(s) => Some(s.into()), - None => None, - }) + std::process::Child::try_wait(self).map(|ops| ops.map(|s| s.into())) } fn wait(&mut self) -> IoResult { @@ -398,7 +393,7 @@ impl ChildKiller for std::process::Child { } pub fn native_pty_system() -> Box { - Box::new(NativePtySystem::default()) + Box::::default() } #[cfg(unix)] diff --git a/pty/src/unix.rs b/pty/src/unix.rs index cbe0f76fb12..008574cb053 100644 --- a/pty/src/unix.rs +++ b/pty/src/unix.rs @@ -31,7 +31,7 @@ fn openpty(size: PtySize) -> anyhow::Result<(UnixMasterPty, UnixSlavePty)> { let result = unsafe { // BSDish systems may require mut pointers to some args - #[cfg_attr(feature = "cargo-clippy", allow(clippy::unnecessary_mut_passed))] + #[allow(clippy::unnecessary_mut_passed)] libc::openpty( &mut master, &mut slave, @@ -261,7 +261,7 @@ impl PtyFd { // type::from(), but the size and potentially signedness // are system dependent, which is why we're using `as _`. // Suppress this lint for this section of code. - #[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_lossless))] + #[allow(clippy::cast_lossless)] if controlling_tty { // Set the pty as the controlling terminal. // Failure to do this means that delivery of diff --git a/rangeset/src/lib.rs b/rangeset/src/lib.rs index 167e8f0f345..b6a818f2177 100644 --- a/rangeset/src/lib.rs +++ b/rangeset/src/lib.rs @@ -281,10 +281,8 @@ impl RangeSet { } } if let Some(r) = self.ranges.get(idx + 1) { - if intersects_range(r, range) || r.end == range.start { - if first.is_some() { - return (first, Some(idx + 1)); - } + if intersects_range(r, range) || r.end == range.start && first.is_some() { + return (first, Some(idx + 1)); } } (first, None) @@ -329,7 +327,7 @@ impl RangeSet { /// Returns an iterator over all of the contained values. /// Take care when the range is very large! - pub fn iter_values<'a>(&'a self) -> impl Iterator + 'a { + pub fn iter_values(&self) -> impl Iterator + '_ { self.ranges.iter().flat_map(|r| num::range(r.start, r.end)) } } diff --git a/umask/src/lib.rs b/umask/src/lib.rs index 574b20806d5..a1d09309166 100644 --- a/umask/src/lib.rs +++ b/umask/src/lib.rs @@ -44,6 +44,12 @@ impl UmaskSaver { } } +impl Default for UmaskSaver { + fn default() -> Self { + Self::new() + } +} + impl Drop for UmaskSaver { fn drop(&mut self) { #[cfg(unix)] diff --git a/wezterm-blob-leases/src/lease_id.rs b/wezterm-blob-leases/src/lease_id.rs index d001e729f57..bff7730774c 100644 --- a/wezterm-blob-leases/src/lease_id.rs +++ b/wezterm-blob-leases/src/lease_id.rs @@ -28,7 +28,7 @@ fn get_mac_address() -> [u8; 6] { impl LeaseId { pub fn new() -> Self { static MAC: Lazy<[u8; 6]> = Lazy::new(get_mac_address); - let uuid = Uuid::now_v1(&*MAC); + let uuid = Uuid::now_v1(&MAC); let pid = std::process::id(); Self { uuid, pid } } @@ -37,3 +37,9 @@ impl LeaseId { self.pid } } + +impl Default for LeaseId { + fn default() -> Self { + Self::new() + } +} diff --git a/wezterm-blob-leases/src/simple_tempdir.rs b/wezterm-blob-leases/src/simple_tempdir.rs index 1f504ccf907..3dc3b294770 100644 --- a/wezterm-blob-leases/src/simple_tempdir.rs +++ b/wezterm-blob-leases/src/simple_tempdir.rs @@ -64,10 +64,10 @@ impl BlobStorage for SimpleTempDir { let mut file = tempfile::Builder::new() .prefix("new-") .rand_bytes(5) - .tempfile_in(&self.root.path())?; + .tempfile_in(self.root.path())?; file.write_all(data)?; - file.persist(&path) + file.persist(path) .map_err(|persist_err| persist_err.error)?; *refs.entry(content_id).or_insert(0) += 1; @@ -91,7 +91,7 @@ impl BlobStorage for SimpleTempDir { let _refs = self.refs.lock().unwrap(); let path = self.path_for_content(content_id)?; - Ok(std::fs::read(&path)?) + Ok(std::fs::read(path)?) } fn get_reader(&self, content_id: ContentId, lease_id: LeaseId) -> Result { @@ -133,7 +133,7 @@ impl BlobStorage for SimpleTempDir { } let path = self.path_for_content(content_id)?; - let file = BufReader::new(std::fs::File::open(&path)?); + let file = BufReader::new(std::fs::File::open(path)?); self.add_ref(content_id); Ok(Box::new(Reader { diff --git a/wezterm-dynamic/src/error.rs b/wezterm-dynamic/src/error.rs index 077a3920bd9..401377aca3e 100644 --- a/wezterm-dynamic/src/error.rs +++ b/wezterm-dynamic/src/error.rs @@ -16,13 +16,13 @@ thread_local! { #[derive(Error, Debug)] #[non_exhaustive] pub enum Error { - #[error("`{}` is not a valid {} variant. {}", .variant_name, .type_name, Self::possible_matches(.variant_name, &.possible))] + #[error("`{}` is not a valid {} variant. {}", .variant_name, .type_name, Self::possible_matches(.variant_name, possible))] InvalidVariantForType { variant_name: String, type_name: &'static str, possible: &'static [&'static str], }, - #[error("`{}` is not a valid {} field. {}", .field_name, .type_name, Self::possible_matches(.field_name, &.possible))] + #[error("`{}` is not a valid {} field. {}", .field_name, .type_name, Self::possible_matches(.field_name, possible))] UnknownFieldForStruct { field_name: String, type_name: &'static str, @@ -201,7 +201,7 @@ impl Error { } if options.unknown_fields == UnknownFieldAction::Deny { - for err in errors { + if let Some(err) = errors.into_iter().next() { return Err(err); } } diff --git a/wezterm-dynamic/src/fromdynamic.rs b/wezterm-dynamic/src/fromdynamic.rs index 2186fd683d1..7a13f9779ed 100644 --- a/wezterm-dynamic/src/fromdynamic.rs +++ b/wezterm-dynamic/src/fromdynamic.rs @@ -51,7 +51,7 @@ impl FromDynamic for Value { impl FromDynamic for ordered_float::NotNan { fn from_dynamic(value: &Value, options: FromDynamicOptions) -> Result { let f = f64::from_dynamic(value, options)?; - Ok(ordered_float::NotNan::new(f).map_err(|e| Error::Message(e.to_string()))?) + ordered_float::NotNan::new(f).map_err(|e| Error::Message(e.to_string())) } } diff --git a/wezterm-dynamic/src/object.rs b/wezterm-dynamic/src/object.rs index 9d3c9858acf..667f8028f5b 100644 --- a/wezterm-dynamic/src/object.rs +++ b/wezterm-dynamic/src/object.rs @@ -15,11 +15,11 @@ pub enum BorrowedKey<'a> { } pub trait ObjectKeyTrait { - fn key<'k>(&'k self) -> BorrowedKey<'k>; + fn key(&self) -> BorrowedKey<'_>; } impl ObjectKeyTrait for Value { - fn key<'k>(&'k self) -> BorrowedKey<'k> { + fn key(&self) -> BorrowedKey<'_> { match self { Value::String(s) => BorrowedKey::Str(s.as_str()), v => BorrowedKey::Value(v), @@ -27,8 +27,8 @@ impl ObjectKeyTrait for Value { } } -impl<'a> ObjectKeyTrait for BorrowedKey<'a> { - fn key<'k>(&'k self) -> BorrowedKey<'k> { +impl ObjectKeyTrait for BorrowedKey<'_> { + fn key(&self) -> BorrowedKey<'_> { *self } } @@ -49,7 +49,7 @@ impl<'a> Eq for (dyn ObjectKeyTrait + 'a) {} impl<'a> PartialOrd for (dyn ObjectKeyTrait + 'a) { fn partial_cmp(&self, other: &Self) -> Option { - self.key().partial_cmp(&other.key()) + Some(self.cmp(other)) } } diff --git a/wezterm-input-types/src/lib.rs b/wezterm-input-types/src/lib.rs index b3298bad6aa..c185ace7248 100644 --- a/wezterm-input-types/src/lib.rs +++ b/wezterm-input-types/src/lib.rs @@ -3,7 +3,7 @@ use bitflags::*; use serde::*; use std::collections::HashMap; use std::convert::TryFrom; -use std::fmt::Write; +use std::fmt::{Display, Write}; use std::sync::atomic::AtomicBool; use std::sync::Arc; use wezterm_dynamic::{FromDynamic, ToDynamic}; @@ -112,24 +112,24 @@ pub enum KeyCode { impl KeyCode { /// Return true if the key represents a modifier key. pub fn is_modifier(&self) -> bool { - match self { + matches!( + self, Self::Hyper - | Self::CapsLock - | Self::Super - | Self::Meta - | Self::Shift - | Self::LeftShift - | Self::RightShift - | Self::Control - | Self::LeftControl - | Self::RightControl - | Self::Alt - | Self::LeftAlt - | Self::RightAlt - | Self::LeftWindows - | Self::RightWindows => true, - _ => false, - } + | Self::CapsLock + | Self::Super + | Self::Meta + | Self::Shift + | Self::LeftShift + | Self::RightShift + | Self::Control + | Self::LeftControl + | Self::RightControl + | Self::Alt + | Self::LeftAlt + | Self::RightAlt + | Self::LeftWindows + | Self::RightWindows + ) } pub fn normalize_shift(&self, modifiers: Modifiers) -> (KeyCode, Modifiers) { @@ -415,9 +415,9 @@ impl TryFrom<&str> for KeyCode { return Ok(KeyCode::Numpad(n)); } - // Don't consider "F" to be an invalid F key! + // Don't consider 'F' to be an invalid F key! if s.len() > 1 { - if let Some(n) = s.strip_prefix("F") { + if let Some(n) = s.strip_prefix('F') { let n: u8 = n .parse() .map_err(|err| format!("parsing F: {:#}", err))?; @@ -438,16 +438,16 @@ impl TryFrom<&str> for KeyCode { } } -impl ToString for KeyCode { - fn to_string(&self) -> String { +impl Display for KeyCode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::RawCode(n) => format!("raw:{}", n), - Self::Char(c) => format!("mapped:{}", c), - Self::Physical(phys) => phys.to_string(), - Self::Composed(s) => s.to_string(), - Self::Numpad(n) => format!("Numpad{}", n), - Self::Function(n) => format!("F{}", n), - other => format!("{:?}", other), + Self::RawCode(n) => write!(f, "raw:{}", n), + Self::Char(c) => write!(f, "mapped:{}", c), + Self::Physical(phys) => write!(f, "{}", phys), + Self::Composed(s) => write!(f, "{}", s), + Self::Numpad(n) => write!(f, "Numpad{}", n), + Self::Function(n) => write!(f, "F{}", n), + other => write!(f, "{:?}", other), } } } @@ -460,8 +460,8 @@ bitflags! { } } -impl ToString for KeyboardLedStatus { - fn to_string(&self) -> String { +impl Display for KeyboardLedStatus { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut s = String::new(); if self.contains(Self::CAPS_LOCK) { s.push_str("CAPS_LOCK"); @@ -472,7 +472,7 @@ impl ToString for KeyboardLedStatus { } s.push_str("NUM_LOCK"); } - s + write!(f, "{}", s) } } @@ -518,7 +518,7 @@ impl TryFrom for Modifiers { mods |= Modifiers::SUPER; } else if ele == "LEADER" { mods |= Modifiers::LEADER; - } else if ele == "NONE" || ele == "" { + } else if ele == "NONE" || ele.is_empty() { mods |= Modifiers::NONE; } else { return Err(format!("invalid modifier name {} in {}", ele, s)); @@ -704,13 +704,17 @@ impl Modifiers { } } -impl ToString for Modifiers { - fn to_string(&self) -> String { - self.to_string_with_separator(ModifierToStringArgs { - separator: "|", - want_none: true, - ui_key_cap_rendering: None, - }) +impl Display for Modifiers { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + self.to_string_with_separator(ModifierToStringArgs { + separator: "|", + want_none: true, + ui_key_cap_rendering: None, + }) + ) } } @@ -859,17 +863,17 @@ pub enum PhysKeyCode { impl PhysKeyCode { pub fn is_modifier(&self) -> bool { - match self { + matches!( + self, Self::LeftShift - | Self::LeftControl - | Self::LeftWindows - | Self::LeftAlt - | Self::RightShift - | Self::RightControl - | Self::RightWindows - | Self::RightAlt => true, - _ => false, - } + | Self::LeftControl + | Self::LeftWindows + | Self::LeftAlt + | Self::RightShift + | Self::RightControl + | Self::RightWindows + | Self::RightAlt + ) } pub fn to_key_code(self) -> KeyCode { @@ -1157,12 +1161,12 @@ impl TryFrom<&str> for PhysKeyCode { } } -impl ToString for PhysKeyCode { - fn to_string(&self) -> String { +impl Display for PhysKeyCode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(s) = INV_PHYSKEYCODE_MAP.get(self) { - s.to_string() + write!(f, "{}", s) } else { - format!("{:?}", self) + write!(f, "{:?}", self) } } } @@ -1224,6 +1228,12 @@ impl Handled { } } +impl Default for Handled { + fn default() -> Self { + Self::new() + } +} + impl PartialEq for Handled { fn eq(&self, _: &Self) -> bool { true @@ -1276,7 +1286,7 @@ impl RawKeyEvent { // PrintScreen => 57361, // Pause => 57362, // Menu => 57363, - Function(n) if n >= 13 && n <= 35 => 57376 + n as u32 - 13, + Function(n) if (13..=35).contains(&n) => 57376 + n as u32 - 13, Numpad(n) => n as u32 + 57399, Decimal => 57409, Divide => 57410, @@ -1979,21 +1989,21 @@ bitflags! { } } -impl Into for &WindowDecorations { - fn into(self) -> String { +impl From<&WindowDecorations> for String { + fn from(val: &WindowDecorations) -> Self { let mut s = vec![]; - if self.contains(WindowDecorations::TITLE) { + if val.contains(WindowDecorations::TITLE) { s.push("TITLE"); } - if self.contains(WindowDecorations::RESIZE) { + if val.contains(WindowDecorations::RESIZE) { s.push("RESIZE"); } - if self.contains(WindowDecorations::INTEGRATED_BUTTONS) { + if val.contains(WindowDecorations::INTEGRATED_BUTTONS) { s.push("INTEGRATED_BUTTONS"); } - if self.contains(WindowDecorations::MACOS_FORCE_ENABLE_SHADOW) { + if val.contains(WindowDecorations::MACOS_FORCE_ENABLE_SHADOW) { s.push("MACOS_FORCE_ENABLE_SHADOW"); - } else if self.contains(WindowDecorations::MACOS_FORCE_DISABLE_SHADOW) { + } else if val.contains(WindowDecorations::MACOS_FORCE_DISABLE_SHADOW) { s.push("MACOS_FORCE_DISABLE_SHADOW"); } if s.is_empty() { diff --git a/wezterm-open-url/src/lib.rs b/wezterm-open-url/src/lib.rs index 9a61fd9472b..511b41246ef 100644 --- a/wezterm-open-url/src/lib.rs +++ b/wezterm-open-url/src/lib.rs @@ -46,11 +46,7 @@ pub fn open_with(url: &str, app: &str) { let mut cmd = std::process::Command::new(args[0]); cmd.args(&args[1..]); - if let Ok(status) = cmd.status() { - if status.success() { - return; - } - } + let _ = cmd.status(); }); } diff --git a/wezterm-ssh/src/auth.rs b/wezterm-ssh/src/auth.rs index 22997fcdbee..b279a9bb297 100644 --- a/wezterm-ssh/src/auth.rs +++ b/wezterm-ssh/src/auth.rs @@ -78,7 +78,7 @@ impl crate::sessioninner::SessionInner { }; // We try with no passphrase first, in case the key is unencrypted - match sess.userauth_pubkey_file(user, pubkey, &file, None) { + match sess.userauth_pubkey_file(user, pubkey, file, None) { Ok(_) => { log::info!("pubkey_file immediately ok for {}", file.display()); return Ok(true); @@ -113,7 +113,7 @@ impl crate::sessioninner::SessionInner { let passphrase = &answers[0]; - match sess.userauth_pubkey_file(user, pubkey, &file, Some(passphrase)) { + match sess.userauth_pubkey_file(user, pubkey, file, Some(passphrase)) { Ok(_) => { return Ok(true); } @@ -157,9 +157,8 @@ impl crate::sessioninner::SessionInner { }); use libssh_rs::{AuthMethods, AuthStatus}; - match sess.userauth_none(None)? { - AuthStatus::Success => return Ok(()), - _ => {} + if sess.userauth_none(None)? == AuthStatus::Success { + return Ok(()); } loop { @@ -269,7 +268,7 @@ impl crate::sessioninner::SessionInner { // Re-query the auth methods on each loop as a successful method // may unlock a new method on a subsequent iteration (eg: password // auth may then unlock 2fac) - let methods: HashSet<&str> = sess.auth_methods(&user)?.split(',').collect(); + let methods: HashSet<&str> = sess.auth_methods(user)?.split(',').collect(); log::trace!("ssh auth methods: {:?}", methods); if !sess.authenticated() && methods.contains("publickey") { @@ -314,11 +313,11 @@ impl crate::sessioninner::SessionInner { } impl<'a> ssh2::KeyboardInteractivePrompt for Helper<'a> { - fn prompt<'b>( + fn prompt( &mut self, username: &str, instructions: &str, - prompts: &[ssh2::Prompt<'b>], + prompts: &[ssh2::Prompt<'_>], ) -> Vec { let (reply, answers) = bounded(1); if let Err(err) = self.tx_event.try_send(SessionEvent::Authenticate( @@ -345,7 +344,7 @@ impl crate::sessioninner::SessionInner { "waiting for authentication answers from user: {:#}", err ); - return vec![]; + vec![] } Ok(answers) => answers, } diff --git a/wezterm-ssh/src/config.rs b/wezterm-ssh/src/config.rs index b96c1023748..6f7ded34cf2 100644 --- a/wezterm-ssh/src/config.rs +++ b/wezterm-ssh/src/config.rs @@ -175,7 +175,7 @@ impl ParsedConfigFile { groups: &mut Vec, loaded_files: &mut Vec, ) { - match filenamegen::Glob::new(&pattern) { + match filenamegen::Glob::new(pattern) { Ok(g) => { match cwd .as_ref() @@ -253,8 +253,8 @@ impl ParsedConfigFile { let mut patterns = vec![]; for p in v.split(',') { let p = p.trim(); - if p.starts_with('!') { - patterns.push(Pattern::new(&p[1..], true)); + if let Some(stripped) = p.strip_prefix('!') { + patterns.push(Pattern::new(stripped, true)); } else { patterns.push(Pattern::new(p, false)); } @@ -265,8 +265,8 @@ impl ParsedConfigFile { let mut patterns = vec![]; for p in v.split_ascii_whitespace() { let p = p.trim(); - if p.starts_with('!') { - patterns.push(Pattern::new(&p[1..], true)); + if let Some(stripped) = p.strip_prefix('!') { + patterns.push(Pattern::new(stripped, true)); } else { patterns.push(Pattern::new(p, false)); } @@ -603,11 +603,16 @@ impl Config { /// Return true if a given option name is subject to environment variable /// expansion. fn should_expand_environment(&self, key: &str) -> bool { - match key { - "certificatefile" | "controlpath" | "identityagent" | "identityfile" - | "userknownhostsfile" | "localforward" | "remoteforward" => true, - _ => false, - } + matches!( + key, + "certificatefile" + | "controlpath" + | "identityagent" + | "identityfile" + | "userknownhostsfile" + | "localforward" + | "remoteforward" + ) } /// Returns a set of tokens that should be expanded for a given option name @@ -730,10 +735,11 @@ impl Config { for c in &group.criteria { if let Criteria::Host(patterns) = c { for pattern in patterns { - if pattern.is_literal && !pattern.negated { - if !hosts.contains(&pattern.original) { - hosts.push(pattern.original.clone()); - } + if pattern.is_literal + && !pattern.negated + && !hosts.contains(&pattern.original) + { + hosts.push(pattern.original.clone()); } } } @@ -745,6 +751,12 @@ impl Config { } } +impl Default for Config { + fn default() -> Self { + Self::new() + } +} + #[cfg(test)] mod test { use super::*; diff --git a/wezterm-ssh/src/host.rs b/wezterm-ssh/src/host.rs index bb8d67794cb..052da22ba66 100644 --- a/wezterm-ssh/src/host.rs +++ b/wezterm-ssh/src/host.rs @@ -65,9 +65,8 @@ impl crate::sessioninner::SessionInner { libssh_rs::KnownHosts::Changed => { let mut file = None; if let Some(kh) = self.config.get("userknownhostsfile") { - for candidate in kh.split_whitespace() { + if let Some(candidate) = kh.split_whitespace().next() { file.replace(candidate.into()); - break; } } @@ -121,7 +120,7 @@ impl crate::sessioninner::SessionInner { } known_hosts - .read_file(&file, ssh2::KnownHostFileKind::OpenSSH) + .read_file(file, ssh2::KnownHostFileKind::OpenSSH) .with_context(|| format!("reading known_hosts file {}", file.display()))?; let (key, key_type) = sess @@ -152,7 +151,7 @@ impl crate::sessioninner::SessionInner { }) .ok_or_else(|| anyhow!("failed to get host fingerprint"))?; - match known_hosts.check_port(&remote_host_name, port, key) { + match known_hosts.check_port(remote_host_name, port, key) { ssh2::CheckResult::Match => {} ssh2::CheckResult::NotFound => { let (reply, confirm) = bounded(1); @@ -182,11 +181,11 @@ impl crate::sessioninner::SessionInner { }; known_hosts - .add(&host_and_port, key, &remote_address, key_type.into()) + .add(&host_and_port, key, remote_address, key_type.into()) .context("adding known_hosts entry in memory")?; known_hosts - .write_file(&file, ssh2::KnownHostFileKind::OpenSSH) + .write_file(file, ssh2::KnownHostFileKind::OpenSSH) .with_context(|| format!("writing known_hosts file {}", file.display()))?; } ssh2::CheckResult::Mismatch => { diff --git a/wezterm-ssh/src/sessioninner.rs b/wezterm-ssh/src/sessioninner.rs index a0f30d6461e..6d528e3016c 100644 --- a/wezterm-ssh/src/sessioninner.rs +++ b/wezterm-ssh/src/sessioninner.rs @@ -188,9 +188,8 @@ impl SessionInner { } } if let Some(kh) = self.config.get("userknownhostsfile") { - for file in kh.split_whitespace() { + if let Some(file) = kh.split_whitespace().next() { sess.set_option(libssh_rs::SshOption::KnownHosts(Some(file.to_string())))?; - break; } } if let Some(types) = self.config.get("pubkeyacceptedtypes") { @@ -333,10 +332,10 @@ impl SessionInner { if cfg!(windows) { let comspec = std::env::var("COMSPEC").unwrap_or_else(|_| "cmd".to_string()); cmd = std::process::Command::new(comspec); - cmd.args(&["/c", proxy_command]); + cmd.args(["/c", proxy_command]); } else { cmd = std::process::Command::new("sh"); - cmd.args(&["-c", &format!("exec {}", proxy_command)]); + cmd.args(["-c", &format!("exec {}", proxy_command)]); } let (a, b) = socketpair()?; @@ -363,8 +362,7 @@ impl SessionInner { let addr = (hostname, port) .to_socket_addrs()? - .filter(|addr| self.filter_sock_addr(addr)) - .next() + .find(|addr| self.filter_sock_addr(addr)) .with_context(|| format!("resolving address for {}", hostname))?; if verbose { log::info!("resolved {hostname}:{port} -> {addr:?}"); @@ -373,8 +371,7 @@ impl SessionInner { if let Some(bind_addr) = self.config.get("bindaddress") { let bind_addr = (bind_addr.as_str(), 0) .to_socket_addrs()? - .filter(|addr| self.filter_sock_addr(addr)) - .next() + .find(|addr| self.filter_sock_addr(addr)) .with_context(|| format!("resolving bind address {bind_addr:?}"))?; if verbose { log::info!("binding to {bind_addr:?}"); @@ -474,25 +471,23 @@ impl SessionInner { state.fd.take(); } } + } else if info.exited && state.buf.is_empty() { + log::trace!("channel {channel_id} exited and we have no data to send to fd {fd_num}: close it!"); + state.fd.take(); } else { - if info.exited && state.buf.is_empty() { - log::trace!("channel {channel_id} exited and we have no data to send to fd {fd_num}: close it!"); - state.fd.take(); - } else { - // We can write our buffered output - match write_from_buf(fd, &mut state.buf) { - Ok(_) => {} - Err(err) => { - log::debug!( - "error while writing to channel {} fd {}: {:#}", - channel_id, - fd_num, - err - ); - - // Close it out - state.fd.take(); - } + // We can write our buffered output + match write_from_buf(fd, &mut state.buf) { + Ok(_) => {} + Err(err) => { + log::debug!( + "error while writing to channel {} fd {}: {:#}", + channel_id, + fd_num, + err + ); + + // Close it out + state.fd.take(); } } } diff --git a/wezterm-ssh/src/sftp/file.rs b/wezterm-ssh/src/sftp/file.rs index 4374f39dd99..f5fe4b047e7 100644 --- a/wezterm-ssh/src/sftp/file.rs +++ b/wezterm-ssh/src/sftp/file.rs @@ -172,7 +172,7 @@ impl smol::io::AsyncRead for File { Poll::Ready(Err(x)) => Poll::Ready(Err(x)), Poll::Ready(Ok(data)) => { let n = data.len(); - (&mut buf[..n]).copy_from_slice(&data[..n]); + (buf[..n]).copy_from_slice(&data[..n]); Poll::Ready(Ok(n)) } } diff --git a/wezterm-ssh/src/sftp/types.rs b/wezterm-ssh/src/sftp/types.rs index 00f6ed9ca6b..ef38697698c 100644 --- a/wezterm-ssh/src/sftp/types.rs +++ b/wezterm-ssh/src/sftp/types.rs @@ -394,15 +394,15 @@ mod libssh_impl { } } - impl Into for Metadata { - fn into(self) -> libssh_rs::SetAttributes { - let size = self.size; - let uid_gid = match (self.uid, self.gid) { + impl From for libssh_rs::SetAttributes { + fn from(val: Metadata) -> Self { + let size = val.size; + let uid_gid = match (val.uid, val.gid) { (Some(uid), Some(gid)) => Some((uid, gid)), _ => None, }; - let permissions = self.permissions.map(FilePermissions::to_unix_mode); - let atime_mtime = match (self.accessed, self.modified) { + let permissions = val.permissions.map(FilePermissions::to_unix_mode); + let atime_mtime = match (val.accessed, val.modified) { (Some(a), Some(m)) => { let a = unix_to_sys(a); let m = unix_to_sys(m); diff --git a/wezterm-ssh/src/sftpwrap.rs b/wezterm-ssh/src/sftpwrap.rs index 11939ddecbb..b3800d3b50f 100644 --- a/wezterm-ssh/src/sftpwrap.rs +++ b/wezterm-ssh/src/sftpwrap.rs @@ -16,9 +16,9 @@ pub(crate) enum SftpWrap { fn pathconv(path: std::path::PathBuf) -> SftpChannelResult { use crate::sftp::SftpChannelError; use std::convert::TryFrom; - Ok(Utf8PathBuf::try_from(path).map_err(|x| { + Utf8PathBuf::try_from(path).map_err(|x| { SftpChannelError::from(std::io::Error::new(std::io::ErrorKind::InvalidData, x)) - })?) + }) } impl SftpWrap { diff --git a/wezterm-version/build.rs b/wezterm-version/build.rs index 23b11e0f997..d64ede3da77 100644 --- a/wezterm-version/build.rs +++ b/wezterm-version/build.rs @@ -30,7 +30,7 @@ fn main() { } if let Ok(output) = std::process::Command::new("git") - .args(&[ + .args([ "-c", "core.abbrev=8", "show",