From a7e177586aa363e7dee2d5c311bb79d254d833ab Mon Sep 17 00:00:00 2001 From: Manos Pitsidianakis Date: Sun, 5 Jul 2020 15:28:55 +0300 Subject: [PATCH] Fix clippy lints --- Cargo.lock | 1 - melib/build.rs | 2 +- melib/src/addressbook/vcard.rs | 4 +- melib/src/async_workers.rs | 22 ++-- melib/src/backends.rs | 13 +- melib/src/backends/imap.rs | 18 ++- melib/src/backends/imap/cache.rs | 4 +- melib/src/backends/imap/connection.rs | 9 +- melib/src/backends/imap/operations.rs | 14 +-- melib/src/backends/imap/protocol_parser.rs | 23 ++-- melib/src/backends/imap_async.rs | 21 ++-- melib/src/backends/imap_async/cache.rs | 4 +- melib/src/backends/imap_async/connection.rs | 12 +- melib/src/backends/imap_async/operations.rs | 6 +- .../backends/imap_async/protocol_parser.rs | 8 +- melib/src/backends/imap_async/untagged.rs | 2 +- melib/src/backends/imap_async/watch.rs | 4 +- melib/src/backends/jmap.rs | 9 +- melib/src/backends/jmap/connection.rs | 2 +- melib/src/backends/jmap/protocol.rs | 6 +- melib/src/backends/jmap/rfc8620.rs | 6 +- melib/src/backends/maildir/backend.rs | 55 ++++---- melib/src/backends/maildir/stream.rs | 5 - melib/src/backends/mbox.rs | 73 ++++++----- melib/src/backends/notmuch.rs | 17 +-- melib/src/collection.rs | 6 +- melib/src/datetime.rs | 31 +++-- melib/src/email/compose.rs | 10 +- melib/src/email/compose/mime.rs | 6 +- melib/src/email/list_management.rs | 16 +-- melib/src/email/mailto.rs | 12 +- melib/src/email/parser.rs | 20 +-- melib/src/error.rs | 2 +- melib/src/lib.rs | 2 +- melib/src/text_processing/line_break.rs | 29 +++-- melib/src/text_processing/mod.rs | 2 +- melib/src/text_processing/tables.rs | 2 +- melib/src/text_processing/wcwidth.rs | 6 +- melib/src/thread.rs | 3 +- src/bin.rs | 1 - src/components/mail/compose.rs | 5 +- src/components/mail/listing/compact.rs | 6 +- src/components/mail/listing/conversations.rs | 6 +- src/components/mail/listing/plain.rs | 6 +- src/components/mail/view.rs | 55 +++----- src/components/mail/view/envelope.rs | 9 +- src/components/mail/view/thread.rs | 8 +- src/components/notifications.rs | 1 - src/components/svg.rs | 4 +- src/components/utilities/widgets.rs | 16 +-- src/conf/accounts.rs | 44 +++---- src/conf/themes.rs | 119 +++++++++--------- src/execute.rs | 7 +- src/sqlite3.rs | 4 +- src/state.rs | 2 +- src/terminal.rs | 6 +- src/terminal/cells.rs | 6 +- src/terminal/keys.rs | 2 +- src/types.rs | 1 - src/types/helpers.rs | 1 - 60 files changed, 359 insertions(+), 437 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c59a150e..c4be75e7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -943,7 +943,6 @@ dependencies = [ "nix", "nom", "notify", - "pin-utils", "reqwest", "rusqlite", "serde", diff --git a/melib/build.rs b/melib/build.rs index 27385ddd..ffa9b958 100644 --- a/melib/build.rs +++ b/melib/build.rs @@ -84,7 +84,7 @@ fn main() -> Result<(), std::io::Error> { .unwrap(); file.write_all(b"use crate::types::LineBreakClass;\n\n") .unwrap(); - file.write_all(b"const line_break_rules: &'static [(u32, u32, LineBreakClass)] = &[\n") + file.write_all(b"const LINE_BREAK_RULES: &[(u32, u32, LineBreakClass)] = &[\n") .unwrap(); for l in &line_break_table { file.write_all(format!(" (0x{:X}, 0x{:X}, {:?}),\n", l.0, l.1, l.2).as_bytes()) diff --git a/melib/src/addressbook/vcard.rs b/melib/src/addressbook/vcard.rs index 7999dbfe..da6652d1 100644 --- a/melib/src/addressbook/vcard.rs +++ b/melib/src/addressbook/vcard.rs @@ -45,8 +45,8 @@ impl VCardVersion for VCardVersion3 {} pub struct CardDeserializer; -static HEADER: &'static str = "BEGIN:VCARD\r\n"; //VERSION:4.0\r\n"; -static FOOTER: &'static str = "END:VCARD\r\n"; +static HEADER: &str = "BEGIN:VCARD\r\n"; //VERSION:4.0\r\n"; +static FOOTER: &str = "END:VCARD\r\n"; #[derive(Debug)] pub struct VCard( diff --git a/melib/src/async_workers.rs b/melib/src/async_workers.rs index 37654cab..7b45c09f 100644 --- a/melib/src/async_workers.rs +++ b/melib/src/async_workers.rs @@ -206,21 +206,21 @@ where recv(rx) -> r => { match r { Ok(p @ AsyncStatus::Payload(_)) => { - return Ok(p); + Ok(p) }, Ok(f @ AsyncStatus::Finished) => { self.active = false; - return Ok(f); + Ok(f) }, Ok(a) => { - return Ok(a); + Ok(a) } Err(_) => { - return Err(()); + Err(()) }, } }, - }; + } } /// Polls worker thread and returns result. pub fn poll(&mut self) -> Result, ()> { @@ -231,25 +231,25 @@ where let rx = &self.rx; select! { default => { - return Ok(AsyncStatus::NoUpdate); + Ok(AsyncStatus::NoUpdate) }, recv(rx) -> r => { match r { Ok(p @ AsyncStatus::Payload(_)) => { - return Ok(p); + Ok(p) }, Ok(f @ AsyncStatus::Finished) => { self.active = false; - return Ok(f); + Ok(f) }, Ok(a) => { - return Ok(a); + Ok(a) } Err(_) => { - return Err(()); + Err(()) }, } }, - }; + } } } diff --git a/melib/src/backends.rs b/melib/src/backends.rs index a77d2708..8f353a6a 100644 --- a/melib/src/backends.rs +++ b/melib/src/backends.rs @@ -72,7 +72,6 @@ pub use futures::stream::Stream; use std::future::Future; pub use std::pin::Pin; -use std; use std::collections::HashMap; #[macro_export] @@ -111,10 +110,10 @@ impl Default for Backends { } #[cfg(feature = "notmuch_backend")] -pub const NOTMUCH_ERROR_MSG: &'static str = +pub const NOTMUCH_ERROR_MSG: &str = "libnotmuch5 was not found in your system. Make sure it is installed and in the library paths.\n"; #[cfg(not(feature = "notmuch_backend"))] -pub const NOTMUCH_ERROR_MSG: &'static str = "this version of meli is not compiled with notmuch support. Use an appropriate version and make sure libnotmuch5 is installed and in the library paths.\n"; +pub const NOTMUCH_ERROR_MSG: &str = "this version of meli is not compiled with notmuch support. Use an appropriate version and make sure libnotmuch5 is installed and in the library paths.\n"; impl Backends { pub fn new() -> Self { @@ -306,7 +305,7 @@ pub trait MailBackend: ::std::fmt::Debug + Send + Sync { fn get(&mut self, mailbox: &Mailbox) -> Async>>; fn get_async( &mut self, - mailbox: &Mailbox, + _mailbox: &Mailbox, ) -> Result>> + Send + 'static>>> { Err(MeliError::new("Unimplemented.")) } @@ -329,7 +328,7 @@ pub trait MailBackend: ::std::fmt::Debug + Send + Sync { sender: RefreshEventConsumer, work_context: WorkContext, ) -> Result; - fn watch_async(&self, sender: RefreshEventConsumer) -> ResultFuture<()> { + fn watch_async(&self, _sender: RefreshEventConsumer) -> ResultFuture<()> { Err(MeliError::new("Unimplemented.")) } fn mailboxes(&self) -> Result>; @@ -524,9 +523,7 @@ impl SpecialUsageMailbox { Some(SpecialUsageMailbox::Archive) } else if name.eq_ignore_ascii_case("drafts") { Some(SpecialUsageMailbox::Drafts) - } else if name.eq_ignore_ascii_case("junk") { - Some(SpecialUsageMailbox::Junk) - } else if name.eq_ignore_ascii_case("spam") { + } else if name.eq_ignore_ascii_case("junk") || name.eq_ignore_ascii_case("spam") { Some(SpecialUsageMailbox::Junk) } else if name.eq_ignore_ascii_case("sent") { Some(SpecialUsageMailbox::Sent) diff --git a/melib/src/backends/imap.rs b/melib/src/backends/imap.rs index 8c9f37f7..410828af 100644 --- a/melib/src/backends/imap.rs +++ b/melib/src/backends/imap.rs @@ -52,7 +52,7 @@ use std::sync::{Arc, Mutex, RwLock}; use std::time::Instant; pub type UID = usize; -pub static SUPPORTED_CAPABILITIES: &'static [&'static str] = +pub static SUPPORTED_CAPABILITIES: &[&str] = &["IDLE", "LOGIN", "LOGINDISABLED", "ENABLE", "IMAP4REV1"]; #[derive(Debug, Default)] @@ -412,7 +412,7 @@ impl MailBackend for ImapType { debug!( "fetch response is {} bytes and {} lines", response.len(), - response.lines().collect::>().len() + response.lines().count() ); let (_, v, _) = protocol_parser::uid_fetch_responses(&response)?; debug!("responses len is {}", v.len()); @@ -552,7 +552,7 @@ impl MailBackend for ImapType { .send(RefreshEvent { account_hash: uid_store.account_hash, mailbox_hash, - kind: RefreshEventKind::Failure(err.clone()), + kind: RefreshEventKind::Failure(err), }); return; @@ -655,9 +655,6 @@ impl MailBackend for ImapType { }; Ok(Box::new(ImapOp::new( uid, - self.uid_store.mailboxes.read().unwrap()[&mailbox_hash] - .imap_path() - .to_string(), mailbox_hash, self.connection.clone(), self.uid_store.clone(), @@ -673,10 +670,9 @@ impl MailBackend for ImapType { let path = { let mailboxes = self.uid_store.mailboxes.read().unwrap(); - let mailbox = mailboxes.get(&mailbox_hash).ok_or(MeliError::new(format!( - "Mailbox with hash {} not found.", - mailbox_hash - )))?; + let mailbox = mailboxes.get(&mailbox_hash).ok_or_else(|| { + MeliError::new(format!("Mailbox with hash {} not found.", mailbox_hash)) + })?; if !mailbox.permissions.lock().unwrap().create_messages { return Err(MeliError::new(format!( "You are not allowed to create messages in mailbox {}", @@ -688,7 +684,7 @@ impl MailBackend for ImapType { }; let mut response = String::with_capacity(8 * 1024); let mut conn = try_lock(&self.connection, Some(std::time::Duration::new(5, 0)))?; - let flags = flags.unwrap_or(Flag::empty()); + let flags = flags.unwrap_or_else(Flag::empty); conn.send_command( format!( "APPEND \"{}\" ({}) {{{}}}", diff --git a/melib/src/backends/imap/cache.rs b/melib/src/backends/imap/cache.rs index cf928916..6efff683 100644 --- a/melib/src/backends/imap/cache.rs +++ b/melib/src/backends/imap/cache.rs @@ -35,8 +35,8 @@ pub use sqlite3_m::*; mod sqlite3_m { use super::*; use crate::sqlite3; - const DB_NAME: &'static str = "header_cache.db"; - const INIT_SCRIPT: &'static str = "PRAGMA foreign_keys = true; + const DB_NAME: &str = "header_cache.db"; + const INIT_SCRIPT: &str = "PRAGMA foreign_keys = true; PRAGMA encoding = 'UTF-8'; CREATE TABLE IF NOT EXISTS envelopes ( diff --git a/melib/src/backends/imap/connection.rs b/melib/src/backends/imap/connection.rs index 2d0a4039..e135fc75 100644 --- a/melib/src/backends/imap/connection.rs +++ b/melib/src/backends/imap/connection.rs @@ -274,7 +274,9 @@ impl ImapStream { } } - if capabilities.is_none() { + if let Some(capabilities) = capabilities { + Ok((capabilities, ret)) + } else { /* sending CAPABILITY after LOGIN automatically is an RFC recommendation, so check * for lazy servers */ drop(capabilities); @@ -283,9 +285,6 @@ impl ImapStream { let capabilities = protocol_parser::capabilities(res.as_bytes())?.1; let capabilities = HashSet::from_iter(capabilities.into_iter().map(|s| s.to_vec())); Ok((capabilities, ret)) - } else { - let capabilities = capabilities.unwrap(); - Ok((capabilities, ret)) } } @@ -523,7 +522,7 @@ impl ImapConnection { } } if let Ok(ref mut stream) = self.stream { - if let Ok(_) = action(stream) { + if action(stream).is_ok() { self.uid_store.is_online.lock().unwrap().0 = Instant::now(); return Ok(()); } diff --git a/melib/src/backends/imap/operations.rs b/melib/src/backends/imap/operations.rs index aeeb27b2..0e026d86 100644 --- a/melib/src/backends/imap/operations.rs +++ b/melib/src/backends/imap/operations.rs @@ -37,7 +37,6 @@ pub struct ImapOp { impl ImapOp { pub fn new( uid: usize, - mailbox_path: String, mailbox_hash: MailboxHash, connection: Arc>, uid_store: Arc, @@ -66,7 +65,7 @@ impl BackendOp for ImapOp { debug!( "fetch response is {} bytes and {} lines", response.len(), - response.lines().collect::>().len() + response.lines().count() ); let UidFetchResponse { uid, flags, body, .. @@ -105,7 +104,7 @@ impl BackendOp for ImapOp { debug!( "fetch response is {} bytes and {} lines", response.len(), - response.lines().collect::>().len() + response.lines().count() ); let v = protocol_parser::uid_fetch_flags_response(response.as_bytes()) .map(|(_, v)| v) @@ -131,8 +130,7 @@ impl BackendOp for ImapOp { let val = { let mut bytes_cache = uid_store.byte_cache.lock()?; let cache = bytes_cache.entry(uid).or_default(); - let val = cache.flags; - val + cache.flags }; Ok(val.unwrap()) } @@ -174,11 +172,13 @@ impl BackendOp for ImapOp { Ok(v) => { if v.len() == 1 { debug!("responses len is {}", v.len()); - let (uid, (flags, _)) = v[0]; + let (uid, (_flags, _)) = v[0]; assert_eq!(uid, uid); } } - Err(e) => Err(e)?, + Err(e) => { + return Err(e); + } } let mut bytes_cache = uid_store.byte_cache.lock()?; let cache = bytes_cache.entry(uid).or_default(); diff --git a/melib/src/backends/imap/protocol_parser.rs b/melib/src/backends/imap/protocol_parser.rs index 99794171..d9feaca7 100644 --- a/melib/src/backends/imap/protocol_parser.rs +++ b/melib/src/backends/imap/protocol_parser.rs @@ -190,7 +190,7 @@ ReadWrite => write!(fmt, "This mailbox is selected with read-write permissions." impl ResponseCode { fn from(val: &str) -> ResponseCode { use ResponseCode::*; - if !val.starts_with("[") { + if !val.starts_with('[') { let msg = val.trim(); return Alert(msg.to_string()); } @@ -235,7 +235,8 @@ pub enum ImapResponse { impl> From for ImapResponse { fn from(val: T) -> ImapResponse { - let val: &str = val.as_ref().split_rn().last().unwrap_or(val.as_ref()); + let val_ref = val.as_ref(); + let val: &str = val_ref.split_rn().last().unwrap_or(val_ref); debug!(&val); let mut val = val[val.as_bytes().find(b" ").unwrap() + 1..].trim(); // M12 NO [CANNOT] Invalid mailbox name: Name must not have \'/\' characters (0.000 + 0.098 + 0.097 secs).\r\n @@ -616,7 +617,7 @@ pub fn uid_fetch_responses(mut input: &str) -> ImapParseResult { - alert.extend(el_alert.0.chars()); + alert.push_str(&el_alert.0); } a @ None => *a = Some(el_alert), } @@ -994,13 +995,13 @@ pub fn flags(input: &str) -> IResult<&str, (Flag, Vec)> { let mut keywords = Vec::new(); let mut input = input; - while !input.starts_with(")") && !input.is_empty() { - if input.starts_with("\\") { + while !input.starts_with(')') && !input.is_empty() { + if input.starts_with('\\') { input = &input[1..]; } let mut match_end = 0; while match_end < input.len() { - if input[match_end..].starts_with(" ") || input[match_end..].starts_with(")") { + if input[match_end..].starts_with(' ') || input[match_end..].starts_with(')') { break; } match_end += 1; @@ -1337,13 +1338,13 @@ pub fn quoted(input: &[u8]) -> IResult<&[u8], Vec> { i += 1; } - return Err(nom::Err::Error( + Err(nom::Err::Error( (input, "quoted(): not a quoted phrase").into(), - )); + )) } pub fn quoted_or_nil(input: &[u8]) -> IResult<&[u8], Option>> { - alt((map(tag("NIL"), |_| None), map(quoted, |v| Some(v))))(input.ltrim()) + alt((map(tag("NIL"), |_| None), map(quoted, Some)))(input.ltrim()) /* alt_complete!(map!(ws!(tag!("NIL")), |_| None) | map!(quoted, |v| Some(v)))); */ @@ -1508,9 +1509,9 @@ fn string_token(input: &[u8]) -> IResult<&[u8], &[u8]> { i += 1; } - return Err(nom::Err::Error( + Err(nom::Err::Error( (input, "string_token(): not a quoted phrase").into(), - )); + )) } // ASTRING-CHAR = ATOM-CHAR / resp-specials diff --git a/melib/src/backends/imap_async.rs b/melib/src/backends/imap_async.rs index f1ebe9c9..aff772b4 100644 --- a/melib/src/backends/imap_async.rs +++ b/melib/src/backends/imap_async.rs @@ -56,7 +56,7 @@ use std::sync::{Arc, Mutex, RwLock}; use std::time::Instant; pub type UID = usize; -pub static SUPPORTED_CAPABILITIES: &'static [&'static str] = +pub static SUPPORTED_CAPABILITIES: &[&str] = &["IDLE", "LOGIN", "LOGINDISABLED", "ENABLE", "IMAP4REV1"]; #[derive(Debug, Default)] @@ -387,10 +387,9 @@ impl MailBackend for ImapType { let path = { let mailboxes = uid_store.mailboxes.lock().await; - let mailbox = mailboxes.get(&mailbox_hash).ok_or(MeliError::new(format!( - "Mailbox with hash {} not found.", - mailbox_hash - )))?; + let mailbox = mailboxes.get(&mailbox_hash).ok_or_else(|| { + MeliError::new(format!("Mailbox with hash {} not found.", mailbox_hash)) + })?; if !mailbox.permissions.lock().unwrap().create_messages { return Err(MeliError::new(format!( "You are not allowed to create messages in mailbox {}", @@ -402,7 +401,7 @@ impl MailBackend for ImapType { }; let mut response = String::with_capacity(8 * 1024); let mut conn = connection.lock().await; - let flags = flags.unwrap_or(Flag::empty()); + let flags = flags.unwrap_or_else(Flag::empty); conn.send_command( format!( "APPEND \"{}\" ({}) {{{}}}", @@ -658,10 +657,10 @@ impl MailBackend for ImapType { fn set_mailbox_permissions( &mut self, mailbox_hash: MailboxHash, - val: crate::backends::MailboxPermissions, + _val: crate::backends::MailboxPermissions, ) -> ResultFuture<()> { let uid_store = self.uid_store.clone(); - let connection = self.connection.clone(); + //let connection = self.connection.clone(); Ok(Box::pin(async move { let mailboxes = uid_store.mailboxes.lock().await; let permissions = mailboxes[&mailbox_hash].permissions(); @@ -746,7 +745,7 @@ impl MailBackend for ImapType { } keyword => { s.push_str(" KEYWORD "); - s.extend(keyword.chars()); + s.push_str(keyword); s.push_str(" "); } } @@ -798,7 +797,7 @@ impl MailBackend for ImapType { .map(usize::from_str) .filter_map(std::result::Result::ok) .filter_map(|uid| uid_index.get(&(mailbox_hash, uid))) - .map(|env_hash_ref| *env_hash_ref), + .copied(), )); } } @@ -1210,7 +1209,7 @@ async fn get_hlpr( debug!( "fetch response is {} bytes and {} lines", response.len(), - response.lines().collect::>().len() + response.lines().count() ); let (_, v, _) = protocol_parser::uid_fetch_responses(&response)?; debug!("responses len is {}", v.len()); diff --git a/melib/src/backends/imap_async/cache.rs b/melib/src/backends/imap_async/cache.rs index cf928916..6efff683 100644 --- a/melib/src/backends/imap_async/cache.rs +++ b/melib/src/backends/imap_async/cache.rs @@ -35,8 +35,8 @@ pub use sqlite3_m::*; mod sqlite3_m { use super::*; use crate::sqlite3; - const DB_NAME: &'static str = "header_cache.db"; - const INIT_SCRIPT: &'static str = "PRAGMA foreign_keys = true; + const DB_NAME: &str = "header_cache.db"; + const INIT_SCRIPT: &str = "PRAGMA foreign_keys = true; PRAGMA encoding = 'UTF-8'; CREATE TABLE IF NOT EXISTS envelopes ( diff --git a/melib/src/backends/imap_async/connection.rs b/melib/src/backends/imap_async/connection.rs index dbbf5639..a1658635 100644 --- a/melib/src/backends/imap_async/connection.rs +++ b/melib/src/backends/imap_async/connection.rs @@ -422,11 +422,6 @@ impl ImapStream { self.stream.write_all(b"\r\n").await?; Ok(()) } - - pub async fn set_nonblocking(&mut self, val: bool) -> Result<()> { - //self.stream.set_nonblocking(val).await?; - Ok(()) - } } impl ImapConnection { @@ -552,11 +547,6 @@ impl ImapConnection { Ok(()) } - pub async fn set_nonblocking(&mut self, val: bool) -> Result<()> { - self.stream.as_mut()?.set_nonblocking(val).await?; - Ok(()) - } - pub async fn select_mailbox( &mut self, mailbox_hash: MailboxHash, @@ -699,7 +689,7 @@ impl ImapBlockingConnection { self.err.as_ref().map(String::as_str) } - pub fn into_stream<'a>(&'a mut self) -> impl Future>> + 'a { + pub fn as_stream<'a>(&'a mut self) -> impl Future>> + 'a { self.result.drain(0..self.prev_res_length); self.prev_res_length = 0; let mut break_flag = false; diff --git a/melib/src/backends/imap_async/operations.rs b/melib/src/backends/imap_async/operations.rs index 3be4eb73..d30f2165 100644 --- a/melib/src/backends/imap_async/operations.rs +++ b/melib/src/backends/imap_async/operations.rs @@ -53,7 +53,6 @@ impl ImapOp { impl BackendOp for ImapOp { fn as_bytes(&mut self) -> ResultFuture> { - let mut response = String::with_capacity(8 * 1024); let connection = self.connection.clone(); let mailbox_hash = self.mailbox_hash; let uid = self.uid; @@ -154,8 +153,7 @@ impl BackendOp for ImapOp { let val = { let mut bytes_cache = uid_store.byte_cache.lock()?; let cache = bytes_cache.entry(uid).or_default(); - let val = cache.flags; - val + cache.flags }; Ok(val.unwrap()) } @@ -200,7 +198,7 @@ impl BackendOp for ImapOp { Ok(v) => { if v.len() == 1 { debug!("responses len is {}", v.len()); - let (_uid, (flags, _)) = v[0]; + let (_uid, (_flags, _)) = v[0]; assert_eq!(_uid, uid); } } diff --git a/melib/src/backends/imap_async/protocol_parser.rs b/melib/src/backends/imap_async/protocol_parser.rs index 71f5bc84..7cf69398 100644 --- a/melib/src/backends/imap_async/protocol_parser.rs +++ b/melib/src/backends/imap_async/protocol_parser.rs @@ -1358,9 +1358,9 @@ pub fn quoted(input: &[u8]) -> IResult<&[u8], Vec> { i += 1; } - return Err(nom::Err::Error( + Err(nom::Err::Error( (input, "quoted(): not a quoted phrase").into(), - )); + )) } pub fn quoted_or_nil(input: &[u8]) -> IResult<&[u8], Option>> { @@ -1529,9 +1529,9 @@ fn string_token(input: &[u8]) -> IResult<&[u8], &[u8]> { i += 1; } - return Err(nom::Err::Error( + Err(nom::Err::Error( (input, "string_token(): not a quoted phrase").into(), - )); + )) } // ASTRING-CHAR = ATOM-CHAR / resp-specials diff --git a/melib/src/backends/imap_async/untagged.rs b/melib/src/backends/imap_async/untagged.rs index 1bf7f158..907b085a 100644 --- a/melib/src/backends/imap_async/untagged.rs +++ b/melib/src/backends/imap_async/untagged.rs @@ -304,7 +304,7 @@ impl ImapConnection { Ok(mut v) => { if let Some(uid) = v.pop() { let lck = self.uid_store.uid_index.lock().unwrap(); - let env_hash = lck.get(&(mailbox_hash, uid)).map(|&h| h); + let env_hash = lck.get(&(mailbox_hash, uid)).copied(); drop(lck); if let Some(env_hash) = env_hash { if !flags.0.intersects(crate::email::Flag::SEEN) { diff --git a/melib/src/backends/imap_async/watch.rs b/melib/src/backends/imap_async/watch.rs index 89831b29..bdb7d3b5 100644 --- a/melib/src/backends/imap_async/watch.rs +++ b/melib/src/backends/imap_async/watch.rs @@ -170,7 +170,7 @@ pub async fn idle(kit: ImapWatchKit) -> Result<()> { const _26_MINS: std::time::Duration = std::time::Duration::from_secs(26 * 60); /* duration interval to check other mailboxes for changes */ const _5_MINS: std::time::Duration = std::time::Duration::from_secs(5 * 60); - while let Some(line) = blockn.into_stream().await { + while let Some(line) = blockn.as_stream().await { let now = std::time::Instant::now(); if now.duration_since(beat) >= _26_MINS { let mut main_conn_lck = main_conn.lock().await; @@ -203,7 +203,7 @@ pub async fn idle(kit: ImapWatchKit) -> Result<()> { .map(|(_, v)| v) .map_err(MeliError::from) { - Ok(Some(Recent(r))) => { + Ok(Some(Recent(_r))) => { let mut conn = main_conn.lock().await; /* UID SEARCH RECENT */ exit_on_error!( diff --git a/melib/src/backends/jmap.rs b/melib/src/backends/jmap.rs index 5228c452..71d32f74 100644 --- a/melib/src/backends/jmap.rs +++ b/melib/src/backends/jmap.rs @@ -195,12 +195,11 @@ impl MailBackend for JmapType { } fn connect(&mut self) { - if self.is_online().is_err() { - if Instant::now().duration_since(self.online.lock().unwrap().0) + if self.is_online().is_err() + && Instant::now().duration_since(self.online.lock().unwrap().0) >= std::time::Duration::new(2, 0) - { - let _ = self.mailboxes(); - } + { + let _ = self.mailboxes(); } } diff --git a/melib/src/backends/jmap/connection.rs b/melib/src/backends/jmap/connection.rs index 110d10de..b6a70514 100644 --- a/melib/src/backends/jmap/connection.rs +++ b/melib/src/backends/jmap/connection.rs @@ -58,7 +58,7 @@ impl JmapConnection { }; if server_conf.server_port != 443 { jmap_session_resource_url.push(':'); - jmap_session_resource_url.extend(server_conf.server_port.to_string().chars()); + jmap_session_resource_url.push_str(&server_conf.server_port.to_string()); } jmap_session_resource_url.push_str("/.well-known/jmap"); diff --git a/melib/src/backends/jmap/protocol.rs b/melib/src/backends/jmap/protocol.rs index 1693723e..540ef920 100644 --- a/melib/src/backends/jmap/protocol.rs +++ b/melib/src/backends/jmap/protocol.rs @@ -64,7 +64,7 @@ pub trait Method: Serialize { const NAME: &'static str; } -static USING: &'static [&'static str] = &["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"]; +static USING: &[&str] = &["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"]; #[derive(Serialize)] #[serde(rename_all = "camelCase")] @@ -208,9 +208,7 @@ pub fn get_message_list(conn: &JmapConnection, mailbox: &JmapMailbox) -> Result< pub fn get_message(conn: &JmapConnection, ids: &[String]) -> Result> { let email_call: EmailGet = EmailGet::new( Get::new() - .ids(Some(JmapArgument::value( - ids.iter().cloned().collect::>(), - ))) + .ids(Some(JmapArgument::value(ids.to_vec()))) .account_id(conn.mail_account_id().to_string()), ); diff --git a/melib/src/backends/jmap/rfc8620.rs b/melib/src/backends/jmap/rfc8620.rs index 3d5d8d80..88fbda8c 100644 --- a/melib/src/backends/jmap/rfc8620.rs +++ b/melib/src/backends/jmap/rfc8620.rs @@ -166,10 +166,10 @@ impl Serialize for Get { if !self.account_id.is_empty() { fields_no += 1; } - if !self.ids.is_none() { + if self.ids.is_some() { fields_no += 1; } - if !self.properties.is_none() { + if self.properties.is_some() { fields_no += 1; } @@ -204,7 +204,7 @@ impl Serialize for Get { } } - if !self.properties.is_none() { + if self.properties.is_some() { state.serialize_field("properties", self.properties.as_ref().unwrap())?; } diff --git a/melib/src/backends/maildir/backend.rs b/melib/src/backends/maildir/backend.rs index dbf1726e..39517707 100644 --- a/melib/src/backends/maildir/backend.rs +++ b/melib/src/backends/maildir/backend.rs @@ -283,10 +283,7 @@ impl MailBackend for MaildirType { let op = Box::new(MaildirOp::new(hash, map.clone(), mailbox_hash)); if let Ok(e) = Envelope::from_token(op, hash) { mailbox_index.lock().unwrap().insert(e.hash(), mailbox_hash); - let file_name = PathBuf::from(file) - .strip_prefix(&root_path) - .unwrap() - .to_path_buf(); + let file_name = file.strip_prefix(&root_path).unwrap().to_path_buf(); if let Ok(cached) = cache_dir.place_cache_file(file_name) { /* place result in cache directory */ let f = match fs::File::create(cached) { @@ -449,7 +446,6 @@ impl MailBackend for MaildirType { *v = pathbuf.clone().into(); *k } else { - drop(index_lock); drop(hash_indexes_lock); /* Did we just miss a Create event? In any case, create * envelope. */ @@ -608,7 +604,6 @@ impl MailBackend for MaildirType { .unwrap() .to_path_buf(); debug!("filename = {:?}", file_name); - drop(index_lock); drop(hash_indexes_lock); if let Some(env) = add_path_to_index( &hash_indexes, @@ -813,10 +808,11 @@ impl MaildirType { &settings, ) { f.children = recurse_mailboxes(mailboxes, settings, &path)?; - f.children - .iter() - .map(|c| mailboxes.get_mut(c).map(|f| f.parent = Some(f.hash))) - .count(); + for c in &f.children { + if let Some(f) = mailboxes.get_mut(c) { + f.parent = Some(f.hash); + } + } children.push(f.hash); mailboxes.insert(f.hash, f); } else { @@ -834,14 +830,11 @@ impl MaildirType { true, &settings, ) { - f.children - .iter() - .map(|c| { - mailboxes - .get_mut(c) - .map(|f| f.parent = Some(f.hash)) - }) - .count(); + for c in &f.children { + if let Some(f) = mailboxes.get_mut(c) { + f.parent = Some(f.hash); + } + } children.push(f.hash); mailboxes.insert(f.hash, f); } @@ -881,18 +874,22 @@ impl MaildirType { if mailboxes.is_empty() { let children = recurse_mailboxes(&mut mailboxes, settings, &root_path)?; - children - .iter() - .map(|c| mailboxes.get_mut(c).map(|f| f.parent = None)) - .count(); + for c in &children { + if let Some(f) = mailboxes.get_mut(c) { + f.parent = None; + } + } } else { - let root_hash = *mailboxes.keys().nth(0).unwrap(); + let root_hash = *mailboxes.keys().next().unwrap(); let children = recurse_mailboxes(&mut mailboxes, settings, &root_path)?; - children - .iter() - .map(|c| mailboxes.get_mut(c).map(|f| f.parent = Some(root_hash))) - .count(); - mailboxes.get_mut(&root_hash).map(|f| f.children = children); + for c in &children { + if let Some(f) = mailboxes.get_mut(c) { + f.parent = Some(root_hash); + } + } + if let Some(f) = mailboxes.get_mut(&root_hash) { + f.children = children; + } } for f in mailboxes.values_mut() { if is_subscribed(f.path()) { @@ -1176,7 +1173,7 @@ impl MaildirType { let mut writer = io::BufWriter::new(file); writer.write_all(&bytes).unwrap(); - return Ok(()); + Ok(()) } pub fn validate_config(s: &AccountSettings) -> Result<()> { diff --git a/melib/src/backends/maildir/stream.rs b/melib/src/backends/maildir/stream.rs index 8ad3ebe9..7fe9f98c 100644 --- a/melib/src/backends/maildir/stream.rs +++ b/melib/src/backends/maildir/stream.rs @@ -105,11 +105,6 @@ impl MaildirStream { map: HashIndexes, mailbox_index: Arc>>, ) -> Result> { - let unseen = unseen.clone(); - let total = total.clone(); - let map = map.clone(); - let mailbox_index = mailbox_index.clone(); - let root_path = root_path.clone(); let len = chunk.len(); let size = if len <= 100 { 100 } else { (len / 100) * 100 }; let mut local_r: Vec = Vec::with_capacity(chunk.len()); diff --git a/melib/src/backends/mbox.rs b/melib/src/backends/mbox.rs index 8771600e..e5985daa 100644 --- a/melib/src/backends/mbox.rs +++ b/melib/src/backends/mbox.rs @@ -31,7 +31,6 @@ use crate::email::*; use crate::error::{MeliError, Result}; use crate::get_path_hash; use crate::shellexpand::ShellExpandTrait; -use libc; use memmap::{Mmap, Protection}; use nom::bytes::complete::tag; use nom::character::complete::digit1; @@ -324,33 +323,33 @@ impl MboxReader { Ok(mut env) => { let mut flags = Flag::empty(); if env.other_headers().contains_key("Status") { - if env.other_headers()["Status"].contains("F") { + if env.other_headers()["Status"].contains('F') { flags.set(Flag::FLAGGED, true); } - if env.other_headers()["Status"].contains("A") { + if env.other_headers()["Status"].contains('A') { flags.set(Flag::REPLIED, true); } - if env.other_headers()["Status"].contains("R") { + if env.other_headers()["Status"].contains('R') { flags.set(Flag::SEEN, true); } - if env.other_headers()["Status"].contains("D") { + if env.other_headers()["Status"].contains('D') { flags.set(Flag::TRASHED, true); } } if env.other_headers().contains_key("X-Status") { - if env.other_headers()["X-Status"].contains("F") { + if env.other_headers()["X-Status"].contains('F') { flags.set(Flag::FLAGGED, true); } - if env.other_headers()["X-Status"].contains("A") { + if env.other_headers()["X-Status"].contains('A') { flags.set(Flag::REPLIED, true); } - if env.other_headers()["X-Status"].contains("R") { + if env.other_headers()["X-Status"].contains('R') { flags.set(Flag::SEEN, true); } - if env.other_headers()["X-Status"].contains("D") { + if env.other_headers()["X-Status"].contains('D') { flags.set(Flag::TRASHED, true); } - if env.other_headers()["X-Status"].contains("T") { + if env.other_headers()["X-Status"].contains('T') { flags.set(Flag::DRAFT, true); } } @@ -422,33 +421,33 @@ impl MboxReader { Ok(mut env) => { let mut flags = Flag::empty(); if env.other_headers().contains_key("Status") { - if env.other_headers()["Status"].contains("F") { + if env.other_headers()["Status"].contains('F') { flags.set(Flag::FLAGGED, true); } - if env.other_headers()["Status"].contains("A") { + if env.other_headers()["Status"].contains('A') { flags.set(Flag::REPLIED, true); } - if env.other_headers()["Status"].contains("R") { + if env.other_headers()["Status"].contains('R') { flags.set(Flag::SEEN, true); } - if env.other_headers()["Status"].contains("D") { + if env.other_headers()["Status"].contains('D') { flags.set(Flag::TRASHED, true); } } if env.other_headers().contains_key("X-Status") { - if env.other_headers()["X-Status"].contains("F") { + if env.other_headers()["X-Status"].contains('F') { flags.set(Flag::FLAGGED, true); } - if env.other_headers()["X-Status"].contains("A") { + if env.other_headers()["X-Status"].contains('A') { flags.set(Flag::REPLIED, true); } - if env.other_headers()["X-Status"].contains("R") { + if env.other_headers()["X-Status"].contains('R') { flags.set(Flag::SEEN, true); } - if env.other_headers()["X-Status"].contains("D") { + if env.other_headers()["X-Status"].contains('D') { flags.set(Flag::TRASHED, true); } - if env.other_headers()["X-Status"].contains("T") { + if env.other_headers()["X-Status"].contains('T') { flags.set(Flag::DRAFT, true); } } @@ -471,33 +470,33 @@ impl MboxReader { Ok(mut env) => { let mut flags = Flag::empty(); if env.other_headers().contains_key("Status") { - if env.other_headers()["Status"].contains("F") { + if env.other_headers()["Status"].contains('F') { flags.set(Flag::FLAGGED, true); } - if env.other_headers()["Status"].contains("A") { + if env.other_headers()["Status"].contains('A') { flags.set(Flag::REPLIED, true); } - if env.other_headers()["Status"].contains("R") { + if env.other_headers()["Status"].contains('R') { flags.set(Flag::SEEN, true); } - if env.other_headers()["Status"].contains("D") { + if env.other_headers()["Status"].contains('D') { flags.set(Flag::TRASHED, true); } } if env.other_headers().contains_key("X-Status") { - if env.other_headers()["X-Status"].contains("F") { + if env.other_headers()["X-Status"].contains('F') { flags.set(Flag::FLAGGED, true); } - if env.other_headers()["X-Status"].contains("A") { + if env.other_headers()["X-Status"].contains('A') { flags.set(Flag::REPLIED, true); } - if env.other_headers()["X-Status"].contains("R") { + if env.other_headers()["X-Status"].contains('R') { flags.set(Flag::SEEN, true); } - if env.other_headers()["X-Status"].contains("D") { + if env.other_headers()["X-Status"].contains('D') { flags.set(Flag::TRASHED, true); } - if env.other_headers()["X-Status"].contains("T") { + if env.other_headers()["X-Status"].contains('T') { flags.set(Flag::DRAFT, true); } } @@ -583,9 +582,7 @@ impl MboxReader { Ok((input, env)) } } - Err(_err) => { - return Self::MboxRd.parse(orig_input); - } + Err(_err) => Self::MboxRd.parse(orig_input), } } } @@ -621,7 +618,7 @@ pub fn mbox_parse( offset += 2; } } else { - Err(e)?; + return Err(e); } continue; } @@ -636,7 +633,7 @@ pub fn mbox_parse( envelopes.push(env); } - return Ok((&[], envelopes)); + Ok((&[], envelopes)) } /// Mbox backend @@ -662,7 +659,7 @@ impl MailBackend for MboxType { let mailbox_index = self.mailbox_index.clone(); let mailboxes = self.mailboxes.clone(); let mailbox_path = mailboxes.lock().unwrap()[&mailbox_hash].fs_path.clone(); - let prefer_mbox_type = self.prefer_mbox_type.clone(); + let prefer_mbox_type = self.prefer_mbox_type; let closure = move |_work_context| { let tx = tx.clone(); let file = match std::fs::OpenOptions::new() @@ -691,7 +688,7 @@ impl MailBackend for MboxType { let index = mailboxes_lck[&mailbox_hash].index.clone(); drop(mailboxes_lck); let payload = mbox_parse(index, contents.as_slice(), 0, prefer_mbox_type) - .map_err(|e| MeliError::from(e)) + .map_err(MeliError::from) .map(|(_, v)| { for v in v.iter() { mailbox_index_lck.insert(v.hash(), mailbox_hash); @@ -735,7 +732,7 @@ impl MailBackend for MboxType { hasher.finish() }; let mailboxes = self.mailboxes.clone(); - let prefer_mbox_type = self.prefer_mbox_type.clone(); + let prefer_mbox_type = self.prefer_mbox_type; let handle = std::thread::Builder::new() .name(format!("watching {}", self.account_name,)) .spawn(move || { @@ -813,7 +810,7 @@ impl MailBackend for MboxType { .lock() .unwrap() .values() - .any(|f| &f.fs_path == &pathbuf) + .any(|f| f.fs_path == pathbuf) { let mailbox_hash = get_path_hash!(&pathbuf); sender.send(RefreshEvent { @@ -971,7 +968,7 @@ impl MboxType { .path .file_name() .map(|f| f.to_string_lossy().into()) - .unwrap_or(String::new()); + .unwrap_or_default(); let hash = get_path_hash!(&ret.path); let read_only = if let Ok(metadata) = std::fs::metadata(&ret.path) { diff --git a/melib/src/backends/notmuch.rs b/melib/src/backends/notmuch.rs index 25db8ea8..96b4e5c1 100644 --- a/melib/src/backends/notmuch.rs +++ b/melib/src/backends/notmuch.rs @@ -189,7 +189,7 @@ impl NotmuchDb { _is_subscribed: Box bool>, ) -> Result> { let lib = Arc::new(libloading::Library::new("libnotmuch.so.5")?); - let path = Path::new(s.root_mailbox.as_str()).expand().to_path_buf(); + let path = Path::new(s.root_mailbox.as_str()).expand(); if !path.exists() { return Err(MeliError::new(format!( "\"root_mailbox\" {} for account {} is not a valid path.", @@ -243,7 +243,7 @@ impl NotmuchDb { } pub fn validate_config(s: &AccountSettings) -> Result<()> { - let path = Path::new(s.root_mailbox.as_str()).expand().to_path_buf(); + let path = Path::new(s.root_mailbox.as_str()).expand(); if !path.exists() { return Err(MeliError::new(format!( "\"root_mailbox\" {} for account {} is not a valid path.", @@ -580,7 +580,7 @@ impl MailBackend for NotmuchDb { sender.send(RefreshEvent { account_hash, mailbox_hash: 0, - kind: Failure(err.into()), + kind: Failure(err), }); } })?; @@ -788,13 +788,11 @@ impl BackendOp for NotmuchOp { index_lck[&self.hash] ))); } + let c_tag = CString::new(tag.as_str()).unwrap(); if value { if let Err(err) = try_call!( self.lib, - call!(self.lib, notmuch_message_add_tag)( - message, - CString::new(tag.as_str()).unwrap().as_ptr(), - ) + call!(self.lib, notmuch_message_add_tag)(message, c_tag.as_ptr(),) ) { return Err(MeliError::new("Could not set tag.").set_source(Some(Arc::new(err)))); } @@ -802,10 +800,7 @@ impl BackendOp for NotmuchOp { } else { if let Err(err) = try_call!( self.lib, - call!(self.lib, notmuch_message_remove_tag)( - message, - CString::new(tag.as_str()).unwrap().as_ptr(), - ) + call!(self.lib, notmuch_message_remove_tag)(message, c_tag.as_ptr(),) ) { return Err(MeliError::new("Could not set tag.").set_source(Some(Arc::new(err)))); } diff --git a/melib/src/collection.rs b/melib/src/collection.rs index 159626ac..033b798d 100644 --- a/melib/src/collection.rs +++ b/melib/src/collection.rs @@ -422,12 +422,12 @@ impl Collection { } } - pub fn get_env<'g>(&'g self, env_hash: EnvelopeHash) -> EnvelopeRef<'g> { - let guard: RwLockReadGuard<'g, _> = self.envelopes.read().unwrap(); + pub fn get_env(&'_ self, env_hash: EnvelopeHash) -> EnvelopeRef<'_> { + let guard: RwLockReadGuard<'_, _> = self.envelopes.read().unwrap(); EnvelopeRef { guard, env_hash } } - pub fn get_env_mut<'g>(&'g mut self, env_hash: EnvelopeHash) -> EnvelopeRefMut<'g> { + pub fn get_env_mut(&'_ mut self, env_hash: EnvelopeHash) -> EnvelopeRefMut<'_> { let guard = self.envelopes.write().unwrap(); EnvelopeRefMut { guard, env_hash } } diff --git a/melib/src/datetime.rs b/melib/src/datetime.rs index 0aac21fe..aa267455 100644 --- a/melib/src/datetime.rs +++ b/melib/src/datetime.rs @@ -56,7 +56,7 @@ pub fn timestamp_to_string(timestamp: UnixTimestamp, fmt: Option<&str>) -> Strin localtime_r(&i as *const i64, &mut new_tm as *mut ::libc::tm); } let fmt = fmt - .map(|slice| CString::new(slice)) + .map(CString::new) .map(|res| res.ok()) .and_then(|opt| opt); let format: &CStr = if let Some(ref s) = fmt { @@ -139,13 +139,11 @@ fn year_to_secs(year: i64, is_leap: &mut bool) -> std::result::Result { centuries = 2; rem -= 200; } + } else if rem >= 100 { + centuries = 1; + rem -= 100; } else { - if rem >= 100 { - centuries = 1; - rem -= 100; - } else { - centuries = 0; - } + centuries = 0; } if rem == 0 { *is_leap = false; @@ -159,10 +157,10 @@ fn year_to_secs(year: i64, is_leap: &mut bool) -> std::result::Result { leaps += 97 * cycles + 24 * centuries - if *is_leap { 1 } else { 0 }; - return Ok(match (year - 100).overflowing_mul(31536000) { - (_, true) => return Err(()), - (res, false) => res + leaps * 86400 + 946684800 + 86400, - }); + match (year - 100).overflowing_mul(31536000) { + (_, true) => Err(()), + (res, false) => Ok(res + leaps * 86400 + 946684800 + 86400), + } } fn month_to_secs(month: usize, is_leap: bool) -> i64 { @@ -184,7 +182,7 @@ fn month_to_secs(month: usize, is_leap: bool) -> i64 { if is_leap && month >= 2 { t += 86400; } - return t; + t } pub fn rfc822_to_timestamp(s: T) -> Result @@ -239,7 +237,7 @@ where .unwrap_or(0)); } } - return Ok(0); + Ok(0) } pub fn rfc3339_to_timestamp(s: T) -> Result @@ -292,7 +290,7 @@ where .unwrap_or(0)); } } - return Ok(0); + Ok(0) } // FIXME: Handle non-local timezone? @@ -311,7 +309,7 @@ where if ret.is_null() { return Ok(None); } - return Ok(Some(mktime(&new_tm as *const _) as u64)); + Ok(Some(mktime(&new_tm as *const _) as u64)) } } @@ -443,7 +441,8 @@ fn test_rfcs() { ); } -const TIMEZONE_ABBR: &'static [(&'static [u8], (i8, i8))] = &[ +#[allow(clippy::zero_prefixed_literal)] +const TIMEZONE_ABBR: &[(&[u8], (i8, i8))] = &[ (b"ACDT", (10, 30)), (b"ACST", (09, 30)), (b"ACT", (-05, 0)), diff --git a/melib/src/email/compose.rs b/melib/src/email/compose.rs index 3b820415..c156cf35 100644 --- a/melib/src/email/compose.rs +++ b/melib/src/email/compose.rs @@ -340,15 +340,15 @@ fn build_multipart(ret: &mut String, kind: MultipartType, parts: Vec { - ret.extend(a.build().into_raw().chars()); + ret.push_str(&a.build().into_raw()); ret.push('\n'); } Multipart { @@ -384,7 +384,7 @@ fn print_attachment(ret: &mut String, kind: &MultipartType, a: AttachmentBuilder ret.push('\n'); } MessageRfc822 | PGPSignature => { - ret.extend(format!("Content-Type: {}; charset=\"utf-8\"\n", kind).chars()); + ret.push_str(&format!("Content-Type: {}; charset=\"utf-8\"\n", kind)); ret.push('\n'); ret.push_str(&String::from_utf8_lossy(a.raw())); ret.push('\n'); diff --git a/melib/src/email/compose/mime.rs b/melib/src/email/compose/mime.rs index 381d6090..6ed720d3 100644 --- a/melib/src/email/compose/mime.rs +++ b/melib/src/email/compose/mime.rs @@ -41,16 +41,14 @@ pub fn encode_header(value: &str) -> String { * * Whitespaces inside encoded tokens must be greedily taken, * instead of splitting each non-ascii word into separate encoded tokens. */ - if !g.split_whitespace().collect::>().is_empty() { + if !g.split_whitespace().next().is_none() { ret.push_str(&format!( "=?UTF-8?B?{}?=", BASE64_MIME .encode(value[current_window_start..idx].as_bytes()) .trim() )); - if idx != value.len() - 1 - && (idx == 0 || value[..idx].chars().last() != Some(' ')) - { + if idx != value.len() - 1 && (idx == 0 || !value[..idx].ends_with(' ')) { ret.push(' '); } is_current_window_ascii = true; diff --git a/melib/src/email/list_management.rs b/melib/src/email/list_management.rs index e9517d94..c797395c 100644 --- a/melib/src/email/list_management.rs +++ b/melib/src/email/list_management.rs @@ -61,7 +61,7 @@ impl<'a> ListAction<'a> { }); vec.into_iter() - .map(|elem| ListAction::from(elem)) + .map(ListAction::from) .collect::; 4]>>() }) .ok() @@ -85,20 +85,20 @@ pub struct ListActions<'a> { pub unsubscribe: Option; 4]>>, } -pub fn list_id_header<'a>(envelope: &'a Envelope) -> Option<&'a str> { +pub fn list_id_header(envelope: &'_ Envelope) -> Option<&'_ str> { envelope .other_headers() .get("List-ID") - .or(envelope.other_headers().get("List-Id")) + .or_else(|| envelope.other_headers().get("List-Id")) .map(String::as_str) } -pub fn list_id<'a>(header: Option<&'a str>) -> Option<&'a str> { +pub fn list_id(header: Option<&'_ str>) -> Option<&'_ str> { /* rfc2919 https://tools.ietf.org/html/rfc2919 */ /* list-id-header = "List-ID:" [phrase] "<" list-id ">" CRLF */ header.and_then(|v| { - if let Some(l) = v.rfind("<") { - if let Some(r) = v.rfind(">") { + if let Some(l) = v.rfind('<') { + if let Some(r) = v.rfind('>') { if l < r { return Some(&v[l + 1..r]); } @@ -115,8 +115,8 @@ impl<'a> ListActions<'a> { ret.id = list_id_header(envelope); if let Some(archive) = envelope.other_headers().get("List-Archive") { - if archive.starts_with("<") { - if let Some(pos) = archive.find(">") { + if archive.starts_with('<') { + if let Some(pos) = archive.find('>') { ret.archive = Some(&archive[1..pos]); } else { ret.archive = Some(archive); diff --git a/melib/src/email/mailto.rs b/melib/src/email/mailto.rs index d9ff4bc7..af36cac6 100644 --- a/melib/src/email/mailto.rs +++ b/melib/src/email/mailto.rs @@ -41,10 +41,10 @@ impl From for Draft { bcc, body, } = val; - ret.set_header("Subject", subject.unwrap_or(String::new())); - ret.set_header("Cc", cc.unwrap_or(String::new())); - ret.set_header("Bcc", bcc.unwrap_or(String::new())); - ret.set_body(body.unwrap_or(String::new())); + ret.set_header("Subject", subject.unwrap_or_default()); + ret.set_header("Cc", cc.unwrap_or_default()); + ret.set_header("Bcc", bcc.unwrap_or_default()); + ret.set_body(body.unwrap_or_default()); ret.set_header("To", address.to_string()); debug!(ret) } @@ -55,8 +55,8 @@ impl TryFrom<&[u8]> for Mailto { fn try_from(value: &[u8]) -> std::result::Result { let parse_res = super::parser::generic::mailto(value).map(|(_, v)| v); - if parse_res.is_ok() { - Ok(parse_res.unwrap()) + if let Ok(res) = parse_res { + Ok(res) } else { debug!( "parser::mailto returned error while parsing {}:\n{:?}", diff --git a/melib/src/email/parser.rs b/melib/src/email/parser.rs index 10a14213..8e46fb0e 100644 --- a/melib/src/email/parser.rs +++ b/melib/src/email/parser.rs @@ -998,9 +998,9 @@ pub mod encodings { fn quoted_printable_soft_break(input: &[u8]) -> IResult<&[u8], &[u8]> { if input.len() < 2 { - return Err(nom::Err::Error( + Err(nom::Err::Error( (input, "quoted_printable_soft_break(): found EOF").into(), - )); + )) } else if input[0] == b'=' && input[1] == b'\n' { Ok((&input[2..], &input[0..2])) // `=\n` is an escaped space character. } else if input.len() > 3 && input.starts_with(b"=\r\n") { @@ -1158,7 +1158,7 @@ pub mod address { use crate::email::address::*; pub fn display_addr(input: &[u8]) -> IResult<&[u8], Address> { if input.is_empty() || input.len() < 3 { - return Err(nom::Err::Error((input, "display_addr(): EOF").into())); + Err(nom::Err::Error((input, "display_addr(): EOF").into())) } else if !is_whitespace!(input[0]) { let mut display_name = StrBuilder { offset: 0, @@ -1260,7 +1260,7 @@ pub mod address { fn addr_spec(input: &[u8]) -> IResult<&[u8], Address> { if input.is_empty() || input.len() < 3 { - return Err(nom::Err::Error((input, "addr_spec(): found EOF").into())); + Err(nom::Err::Error((input, "addr_spec(): found EOF").into())) } else if !is_whitespace!(input[0]) { let mut end = input[1..].len(); let mut flag = false; @@ -1394,22 +1394,22 @@ pub mod address { fn message_id_peek(input: &[u8]) -> IResult<&[u8], &[u8]> { let input_length = input.len(); if input.is_empty() { - return Err(nom::Err::Error( + Err(nom::Err::Error( (input, "message_id_peek(): found EOF").into(), - )); + )) } else if input_length == 2 || input[0] != b'<' { - return Err(nom::Err::Error( + Err(nom::Err::Error( (input, "message_id_peek(): expected '<'").into(), - )); + )) } else { for (i, &x) in input.iter().take(input_length).enumerate().skip(1) { if x == b'>' { return Ok((&input[i + 1..], &input[0..=i])); } } - return Err(nom::Err::Error( + Err(nom::Err::Error( (input, "message_id_peek(): expected closing '>'").into(), - )); + )) } } diff --git a/melib/src/error.rs b/melib/src/error.rs index 6b7c497e..bdb5032c 100644 --- a/melib/src/error.rs +++ b/melib/src/error.rs @@ -112,7 +112,7 @@ impl MeliError { impl fmt::Display for MeliError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(summary) = self.summary.as_ref() { - write!(f, "Summary: {}\n", summary)?; + writeln!(f, "Summary: {}", summary)?; } let ret = write!(f, "{}", self.details)?; if let Some(source) = self.source.as_ref() { diff --git a/melib/src/lib.rs b/melib/src/lib.rs index 93cbbda1..aef77c5b 100644 --- a/melib/src/lib.rs +++ b/melib/src/lib.rs @@ -291,7 +291,7 @@ pub mod shellexpand { // the end of the directory listing, right? Unfortunately, no. SYS_getdents64 is finicky. // It sometimes writes a partial list of entries even if the full list would fit." } - return entries; + entries } #[cfg(not(target_os = "linux"))] diff --git a/melib/src/text_processing/line_break.rs b/melib/src/text_processing/line_break.rs index 8e00e47e..6987007e 100644 --- a/melib/src/text_processing/line_break.rs +++ b/melib/src/text_processing/line_break.rs @@ -754,7 +754,7 @@ pub use alg::linear; mod alg { use super::super::grapheme_clusters::TextProcessing; use super::super::*; - fn cost(i: usize, j: usize, width: usize, minima: &Vec, offsets: &Vec) -> usize { + fn cost(i: usize, j: usize, width: usize, minima: &[usize], offsets: &[usize]) -> usize { let w = offsets[j] + j - offsets[i] - i - 1; if w > width { return 65536 * (w - width); @@ -773,7 +773,7 @@ mod alg { let mut stack = Vec::new(); let mut i = 0; while i < rows.len() { - if stack.len() > 0 { + if !stack.is_empty() { let c = columns[stack.len() - 1]; if cost(*stack.iter().last().unwrap(), c, width, minima, offsets) < cost(rows[i], c, width, minima, offsets) @@ -826,12 +826,12 @@ mod alg { { let mut prev = 0; for b in breaks { - if text[prev..b.0].ends_with("\n") && text[b.0..].starts_with("\n") { - words.push(text[prev..b.0].trim_end_matches("\n")); + if text[prev..b.0].ends_with('\n') && text[b.0..].starts_with('\n') { + words.push(text[prev..b.0].trim_end_matches('\n')); words.push("\n\n"); } else if &text[prev..b.0] != "\n" { - words.push(text[prev..b.0].trim_end_matches("\n")); - if text[prev..b.0].ends_with("\n") { + words.push(text[prev..b.0].trim_end_matches('\n')); + if text[prev..b.0].ends_with('\n') { words.push(" "); } } @@ -922,7 +922,7 @@ pub fn split_lines_reflow(text: &str, reflow: Reflow, width: Option) -> V * - Split lines with indices using str::match_indices() * - Iterate and reflow flow regions, and pass fixed regions through */ - let lines_indices: Vec = text.match_indices("\n").map(|(i, _)| i).collect(); + let lines_indices: Vec = text.match_indices('\n').map(|(i, _)| i).collect(); let mut prev_index = 0; let mut in_paragraph = false; let mut paragraph_start = 0; @@ -946,7 +946,7 @@ pub fn split_lines_reflow(text: &str, reflow: Reflow, width: Option) -> V }) .unwrap_or(0); trimmed = &trimmed[p_str..]; - if trimmed.starts_with(" ") { + if trimmed.starts_with(' ') { /* Remove space stuffing before checking for ending space character. * [rfc3676#section-4.4] */ trimmed = &trimmed[1..]; @@ -999,7 +999,6 @@ pub fn split_lines_reflow(text: &str, reflow: Reflow, width: Option) -> V let breaks = LineBreakCandidateIter::new(line) .collect::>(); - &breaks.iter().enumerate().collect::>(); if breaks.len() < 2 { split(&mut ret, line, width); continue; @@ -1021,7 +1020,7 @@ pub fn split_lines_reflow(text: &str, reflow: Reflow, width: Option) -> V }; if !line[prev_line_offset..end_offset].is_empty() { if prev_line_offset == 0 { - ret.push(format!("{}", &line[prev_line_offset..end_offset])); + ret.push(line[prev_line_offset..end_offset].to_string()); } else { ret.push(format!("⤷{}", &line[prev_line_offset..end_offset])); } @@ -1046,7 +1045,7 @@ fn split(ret: &mut Vec, mut line: &str, width: usize) { while !line.is_empty() { let mut chop_index = std::cmp::min(line.len().saturating_sub(1), width); while chop_index > 0 && !line.is_char_boundary(chop_index) { - chop_index = chop_index - 1; + chop_index -= 1; } if chop_index == 0 { ret.push(format!("⤷{}", line)); @@ -1113,11 +1112,11 @@ easy to take MORE than nothing.'"#; for l in split_lines_reflow(text, Reflow::FormatFlowed, Some(30)) { println!("{}", l); } - println!(""); + println!(); for l in split_lines_reflow(text, Reflow::No, Some(30)) { println!("{}", l); } - println!(""); + println!(); let text = r#">>>Take some more tea. >>I've had nothing yet, so I can't take more. >You mean you can't take LESS, it's very easy to take @@ -1125,11 +1124,11 @@ easy to take MORE than nothing.'"#; for l in split_lines_reflow(text, Reflow::FormatFlowed, Some(20)) { println!("{}", l); } - println!(""); + println!(); for l in split_lines_reflow(text, Reflow::No, Some(20)) { println!("{}", l); } - println!(""); + println!(); use super::_ALICE_CHAPTER_1; for l in split_lines_reflow(_ALICE_CHAPTER_1, Reflow::FormatFlowed, Some(72)) { println!("{}", l); diff --git a/melib/src/text_processing/mod.rs b/melib/src/text_processing/mod.rs index e63cf6a4..0c2e3de2 100644 --- a/melib/src/text_processing/mod.rs +++ b/melib/src/text_processing/mod.rs @@ -139,7 +139,7 @@ fn test_globmatch() { assert!(!"INBOX/Lists/".matches_glob("INBOX/Lists/*")); } -pub const _ALICE_CHAPTER_1: &'static str = r#"CHAPTER I. Down the Rabbit-Hole +pub const _ALICE_CHAPTER_1: &str = r#"CHAPTER I. Down the Rabbit-Hole Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the diff --git a/melib/src/text_processing/tables.rs b/melib/src/text_processing/tables.rs index cecfe5cb..2c5081fe 100644 --- a/melib/src/text_processing/tables.rs +++ b/melib/src/text_processing/tables.rs @@ -22,7 +22,7 @@ use super::types::LineBreakClass; use super::types::LineBreakClass::*; -pub const LINE_BREAK_RULES: &'static [(u32, u32, LineBreakClass)] = &[ +pub const LINE_BREAK_RULES: &[(u32, u32, LineBreakClass)] = &[ (0x0, 0x8, CM), (0x9, 0x9, BA), (0xA, 0xA, LF), diff --git a/melib/src/text_processing/wcwidth.rs b/melib/src/text_processing/wcwidth.rs index b7c123c5..e4b41814 100644 --- a/melib/src/text_processing/wcwidth.rs +++ b/melib/src/text_processing/wcwidth.rs @@ -169,7 +169,7 @@ fn bisearch(ucs: WChar, table: &'static [Interval]) -> bool { pub fn wcwidth(ucs: WChar) -> Option { /* sorted list of non-overlapping intervals of non-spacing characters */ - let combining: &'static [Interval] = &[ + const COMBINING: &[Interval] = &[ (0x0300, 0x034E), (0x0360, 0x0362), (0x0483, 0x0486), @@ -285,7 +285,7 @@ pub fn wcwidth(ucs: WChar) -> Option { return Some(2); } /* binary search in table of non-spacing characters */ - if bisearch(ucs, combining) { + if bisearch(ucs, COMBINING) { return Some(1); } @@ -324,7 +324,7 @@ pub fn wcswidth(mut pwcs: WChar, mut n: usize) -> Option { Some(width) } -const EMOJI_RANGES: &'static [Interval] = &[ +const EMOJI_RANGES: &[Interval] = &[ (0x231A, 0x231B), // ; Basic_Emoji ; watch # 1.1 [2] (⌚..⌛) (0x23E9, 0x23EC), // ; Basic_Emoji ; fast-forward button # 6.0 [4] (⏩..⏬) (0x23F0, 0x23F0), // ; Basic_Emoji ; alarm clock # 6.0 [1] (⏰) diff --git a/melib/src/thread.rs b/melib/src/thread.rs index 49ff5c16..aea0cd04 100644 --- a/melib/src/thread.rs +++ b/melib/src/thread.rs @@ -308,7 +308,7 @@ macro_rules! property { pub fn $name(&self) -> $t { (self.$name).into() } - } + }; } impl Thread { @@ -842,7 +842,6 @@ impl Threads { fn inner_subsort_by(&self, _subsort: (SortField, SortOrder), _envelopes: &Envelopes) { //FIXME: self\.thread_nodes needs interior mutability */ - return; /* let Threads { ref tree_index, diff --git a/src/bin.rs b/src/bin.rs index d9ba7fd5..83907c67 100644 --- a/src/bin.rs +++ b/src/bin.rs @@ -84,7 +84,6 @@ pub mod jobs; pub mod mailcap; pub mod plugins; -use nix; use std::os::raw::c_int; fn notify( diff --git a/src/components/mail/compose.rs b/src/components/mail/compose.rs index 16aca95a..b771ebf0 100644 --- a/src/components/mail/compose.rs +++ b/src/components/mail/compose.rs @@ -220,7 +220,7 @@ impl Composer { id, Box::new( results - .into_iter() + .iter() .map(|a| a.to_string()) .collect::>() .join(", "), @@ -244,7 +244,6 @@ impl Composer { ); drop(parent_message); - drop(account); match context.accounts[coordinates.0] .operation(msg) .and_then(|mut op| op.as_bytes()) @@ -262,7 +261,7 @@ impl Composer { .spawn_specialized(fut); context.accounts[coordinates.0] .active_jobs - .insert(job_id.clone(), JobRequest::AsBytes); + .insert(job_id, JobRequest::AsBytes); if let Ok(Some(parent_bytes)) = try_recv_timeout!(&mut rcvr) { match parent_bytes { Err(err) => { diff --git a/src/components/mail/listing/compact.rs b/src/components/mail/listing/compact.rs index f2d1d49f..f9883205 100644 --- a/src/components/mail/listing/compact.rs +++ b/src/components/mail/listing/compact.rs @@ -481,8 +481,8 @@ impl ListingTrait for CompactListing { for c in grid.row_iter(x..(self.data_columns.widths[3] + x), get_y(upper_left)) { grid[c].set_bg(bg_color).set_attrs(attrs); } - return; } + /// Draw the list of `Envelope`s. fn draw_list(&mut self, grid: &mut CellBuffer, area: Area, context: &mut Context) { if self.cursor_pos.1 != self.new_cursor_pos.1 || self.cursor_pos.0 != self.new_cursor_pos.0 @@ -616,8 +616,8 @@ impl ListingTrait for CompactListing { self.data_columns.widths[i] = self.data_columns.segment_tree[i].get_max(top_idx, top_idx + rows) as usize; } - if self.data_columns.widths.iter().fold(0, |acc, &w| acc + w) > width { - let diff = self.data_columns.widths.iter().fold(0, |acc, &w| acc + w) - width; + if self.data_columns.widths.iter().sum::() > width { + let diff = self.data_columns.widths.iter().sum::() - width; if self.data_columns.widths[2] > 2 * diff { self.data_columns.widths[2] -= diff; } else { diff --git a/src/components/mail/listing/conversations.rs b/src/components/mail/listing/conversations.rs index 6c9fee75..7b48fff4 100644 --- a/src/components/mail/listing/conversations.rs +++ b/src/components/mail/listing/conversations.rs @@ -515,8 +515,8 @@ impl ListingTrait for ConversationsListing { .set_attrs(attrs); } } - return; } + /// Draw the list of `Envelope`s. fn draw_list(&mut self, grid: &mut CellBuffer, area: Area, context: &mut Context) { if self.cursor_pos.1 != self.new_cursor_pos.1 || self.cursor_pos.0 != self.new_cursor_pos.0 @@ -708,7 +708,7 @@ impl ListingTrait for ConversationsListing { self.length = 0; self.filtered_selection.clear(); self.filtered_order.clear(); - self.filter_term = filter_term.to_string(); + self.filter_term = filter_term; self.row_updates.clear(); for v in self.selection.values_mut() { *v = false; @@ -1359,7 +1359,7 @@ impl Component for ConversationsListing { .spawn_specialized(job); context.accounts[self.cursor_pos.0] .active_jobs - .insert(job_id.clone(), crate::conf::accounts::JobRequest::Search); + .insert(job_id, crate::conf::accounts::JobRequest::Search); self.search_job = Some((filter_term.to_string(), chan, job_id)); } Err(err) => { diff --git a/src/components/mail/listing/plain.rs b/src/components/mail/listing/plain.rs index 76a21774..539e6be0 100644 --- a/src/components/mail/listing/plain.rs +++ b/src/components/mail/listing/plain.rs @@ -91,7 +91,7 @@ impl MailListingTrait for PlainListing { } fn get_focused_items(&self, _context: &Context) -> SmallVec<[ThreadHash; 8]> { - return SmallVec::new(); + SmallVec::new() /* let is_selection_empty = self.selection.values().cloned().any(std::convert::identity); if is_selection_empty { @@ -365,8 +365,8 @@ impl ListingTrait for PlainListing { for c in grid.row_iter(x..(x + self.data_columns.widths[3]), get_y(upper_left)) { grid[c].set_bg(bg_color).set_attrs(attrs); } - return; } + /// Draw the list of `Envelope`s. fn draw_list(&mut self, grid: &mut CellBuffer, area: Area, context: &mut Context) { if self.cursor_pos.1 != self.new_cursor_pos.1 || self.cursor_pos.0 != self.new_cursor_pos.0 @@ -601,7 +601,7 @@ impl ListingTrait for PlainListing { self.length = 0; self.filtered_selection.clear(); self.filtered_order.clear(); - self.filter_term = filter_term.to_string(); + self.filter_term = filter_term; self.row_updates.clear(); for v in self.selection.values_mut() { *v = false; diff --git a/src/components/mail/view.rs b/src/components/mail/view.rs index 81aab19f..e6516868 100644 --- a/src/components/mail/view.rs +++ b/src/components/mail/view.rs @@ -308,7 +308,6 @@ impl MailView { String::new(), Some(NotificationType::ERROR), )); - return; } } } else if a.is_signed() { @@ -338,7 +337,7 @@ impl MailView { } ViewMode::Source(Source::Raw) => String::from_utf8_lossy(body.body()).into_owned(), ViewMode::Url => { - let mut t = body_text.to_string(); + let mut t = body_text; for (lidx, l) in finder.links(&body.text()).enumerate() { let offset = if lidx < 10 { lidx * 3 @@ -411,26 +410,20 @@ impl MailView { } } else { match u.content_type() { - ContentType::MessageRfc822 => { - match EnvelopeWrapper::new(u.body().to_vec()) { - Ok(wrapper) => { - context.replies.push_back(UIEvent::Action(Tab(New(Some( - Box::new(EnvelopeView::new( - wrapper, - None, - None, - self.coordinates.0, - )), - ))))); - } - Err(e) => { - context.replies.push_back(UIEvent::StatusEvent( - StatusEvent::DisplayMessage(format!("{}", e)), - )); - } + ContentType::MessageRfc822 => match EnvelopeWrapper::new(u.body().to_vec()) { + Ok(wrapper) => { + context + .replies + .push_back(UIEvent::Action(Tab(New(Some(Box::new( + EnvelopeView::new(wrapper, None, None, self.coordinates.0), + )))))); } - return; - } + Err(e) => { + context.replies.push_back(UIEvent::StatusEvent( + StatusEvent::DisplayMessage(format!("{}", e)), + )); + } + }, ContentType::Text { .. } | ContentType::PGPSignature => { self.mode = ViewMode::Attachment(lidx); @@ -443,7 +436,6 @@ impl MailView { "Multipart attachments are not supported yet.".to_string(), ), )); - return; } ContentType::Other { ref name, .. } => { let attachment_type = u.mime_type(); @@ -522,7 +514,6 @@ impl MailView { ) }), )); - return; } } ContentType::OctetStream { ref name } => { @@ -532,7 +523,6 @@ impl MailView { name.as_ref().map(|n| n.as_str()).unwrap_or("file") )), )); - return; } } } @@ -543,7 +533,6 @@ impl MailView { "Attachment `{}` not found.", lidx )))); - return; } } } @@ -770,11 +759,10 @@ impl Component for MailView { let height = height!(area).saturating_sub(y).saturating_sub(1); if self.pager.cursor_pos() >= self.headers_no { get_y(upper_left) - } else if height_p > height && self.headers_cursor < self.headers_no + 1 { - y + 1 - } else if self.headers_cursor == 0 { - y + 1 - } else if height_p < height { + } else if (height_p > height && self.headers_cursor < self.headers_no + 1) + || self.headers_cursor == 0 + || height_p < height + { y + 1 } else { get_y(upper_left) @@ -1226,9 +1214,7 @@ impl Component for MailView { let url = { let finder = LinkFinder::new(); let t = match body { - Ok(body) => { - AttachmentBuilder::new(&body).build().text().to_string() - } + Ok(body) => AttachmentBuilder::new(&body).build().text(), Err(e) => { context.replies.push_back(UIEvent::Notification( Some("Failed to open e-mail".to_string()), @@ -1504,7 +1490,6 @@ impl Component for MailView { * on its own */ drop(detect); drop(envelope); - drop(account); return super::compose::send_draft( ToggleFlag::False, context, @@ -1696,7 +1681,7 @@ fn attachment_tree( attachment_tree( (idx, (depth + 1, &sub_att_vec[i])), branches, - !(iter.peek() == None), + iter.peek() != None, s, ); } diff --git a/src/components/mail/view/envelope.rs b/src/components/mail/view/envelope.rs index 7659fc98..e4b98e05 100644 --- a/src/components/mail/view/envelope.rs +++ b/src/components/mail/view/envelope.rs @@ -134,7 +134,7 @@ impl EnvelopeView { .into_owned(); match self.mode { ViewMode::Normal | ViewMode::Subview => { - let mut t = body_text.to_string(); + let mut t = body_text; if body.count_attachments() > 1 { t = body .attachments() @@ -149,7 +149,7 @@ impl EnvelopeView { } ViewMode::Raw => String::from_utf8_lossy(body.body()).into_owned(), ViewMode::Url => { - let mut t = body_text.to_string(); + let mut t = body_text; for (lidx, l) in finder.links(&body.text()).enumerate() { let offset = if lidx < 10 { lidx * 3 @@ -521,10 +521,7 @@ impl Component for EnvelopeView { let url = { let envelope: &Envelope = self.wrapper.envelope(); let finder = LinkFinder::new(); - let t = envelope - .body_bytes(self.wrapper.buffer()) - .text() - .to_string(); + let t = envelope.body_bytes(self.wrapper.buffer()).text(); let links: Vec = finder.links(&t).collect(); if let Some(u) = links.get(lidx) { u.as_str().to_string() diff --git a/src/components/mail/view/thread.rs b/src/components/mail/view/thread.rs index 715f44a8..3a0a5c71 100644 --- a/src/components/mail/view/thread.rs +++ b/src/components/mail/view/thread.rs @@ -1075,7 +1075,8 @@ impl Component for ThreadView { { let visible_entries: Vec<&usize> = self.visible_entries.iter().flat_map(|v| v.iter()).collect(); - let search_old_cursor_pos = |entries: Vec<&usize>, x: usize| { + /* search_old_cursor_pos */ + self.new_cursor_pos = (|entries: Vec<&usize>, x: usize| { let mut low = 0; let mut high = entries.len() - 1; while low <= high { @@ -1089,9 +1090,8 @@ impl Component for ThreadView { high = mid - 1; } } - return high + 1; //mid - }; - self.new_cursor_pos = search_old_cursor_pos(visible_entries, self.cursor_pos); + high + 1 //mid + })(visible_entries, self.cursor_pos); } self.cursor_pos = self.new_cursor_pos; self.recalc_visible_entries(); diff --git a/src/components/notifications.rs b/src/components/notifications.rs index 6ea54324..7a61bc8a 100644 --- a/src/components/notifications.rs +++ b/src/components/notifications.rs @@ -23,7 +23,6 @@ Notification handling components. */ use crate::types::RateLimit; -use notify_rust; use std::process::{Command, Stdio}; use super::*; diff --git a/src/components/svg.rs b/src/components/svg.rs index e728f552..ff1b4681 100644 --- a/src/components/svg.rs +++ b/src/components/svg.rs @@ -437,9 +437,9 @@ impl Component for SVGScreenshotFilter { fn set_id(&mut self, _id: ComponentId) {} } -const CSS_STYLE: &'static str = r#"#t{font-family:'DejaVu Sans Mono',monospace;font-style:normal;font-size:14px;} text {dominant-baseline: text-before-edge; white-space: pre;} .f{fill:#e5e5e5;} .b{fill:#000;} .c0 {fill:#000;} .c1 {fill:#cd0000;} .c2 {fill:#00cd00;} .c3 {fill:#cdcd00;} .c4 {fill:#00e;} .c5 {fill:#cd00cd;} .c6 {fill:#00cdcd;} .c7 {fill:#e5e5e5;} .c8 {fill:#7f7f7f;} .c9 {fill:#f00;} .c10 {fill:#0f0;} .c11 {fill:#ff0;} .c12 {fill:#5c5cff;} .c13 {fill:#f0f;} .c14 {fill:#0ff;} .c15 {fill:#fff;}"#; +const CSS_STYLE: &str = r#"#t{font-family:'DejaVu Sans Mono',monospace;font-style:normal;font-size:14px;} text {dominant-baseline: text-before-edge; white-space: pre;} .f{fill:#e5e5e5;} .b{fill:#000;} .c0 {fill:#000;} .c1 {fill:#cd0000;} .c2 {fill:#00cd00;} .c3 {fill:#cdcd00;} .c4 {fill:#00e;} .c5 {fill:#cd00cd;} .c6 {fill:#00cdcd;} .c7 {fill:#e5e5e5;} .c8 {fill:#7f7f7f;} .c9 {fill:#f00;} .c10 {fill:#0f0;} .c11 {fill:#ff0;} .c12 {fill:#5c5cff;} .c13 {fill:#f0f;} .c14 {fill:#0ff;} .c15 {fill:#fff;}"#; -const XTERM_COLORS: &'static [(u8, u8, u8)] = &[ +const XTERM_COLORS: &[(u8, u8, u8)] = &[ /*0*/ (0, 0, 0), /*1*/ (128, 0, 0), /*2*/ (0, 128, 0), diff --git a/src/components/utilities/widgets.rs b/src/components/utilities/widgets.rs index 9484778e..5434ee5e 100644 --- a/src/components/utilities/widgets.rs +++ b/src/components/utilities/widgets.rs @@ -86,13 +86,6 @@ impl Field { self.as_str().is_empty() } - pub fn to_string(&self) -> String { - match self { - Text(ref s, _) => s.as_str().to_string(), - Choice(ref v, ref cursor) => v[*cursor].clone(), - } - } - pub fn into_string(self) -> String { match self { Text(s, _) => s.into_string(), @@ -292,7 +285,14 @@ impl Component for Field { impl fmt::Display for Field { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - Display::fmt("field", f) + write!( + f, + "{}", + match self { + Text(ref s, _) => s.as_str().to_string(), + Choice(ref v, ref cursor) => v[*cursor].clone(), + } + ) } } diff --git a/src/conf/accounts.rs b/src/conf/accounts.rs index f925232d..00ce4ad1 100644 --- a/src/conf/accounts.rs +++ b/src/conf/accounts.rs @@ -182,26 +182,26 @@ pub enum JobRequest { impl core::fmt::Debug for JobRequest { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { match self { - JobRequest::Mailboxes(_) => write!(f, "{}", "JobRequest::Mailboxes"), + JobRequest::Mailboxes(_) => write!(f, "JobRequest::Mailboxes"), JobRequest::Get(hash, _) => write!(f, "JobRequest::Get({})", hash), - JobRequest::IsOnline(_) => write!(f, "{}", "JobRequest::IsOnline"), - JobRequest::Refresh(_, _) => write!(f, "{}", "JobRequest::Refresh"), - JobRequest::SetFlags(_, _) => write!(f, "{}", "JobRequest::SetFlags"), - JobRequest::SaveMessage(_, _) => write!(f, "{}", "JobRequest::SaveMessage"), - JobRequest::CopyTo(_, _) => write!(f, "{}", "JobRequest::CopyTo"), - JobRequest::DeleteMessage(_, _) => write!(f, "{}", "JobRequest::DeleteMessage"), - JobRequest::CreateMailbox(_) => write!(f, "{}", "JobRequest::CreateMailbox"), - JobRequest::DeleteMailbox(_) => write!(f, "{}", "JobRequest::DeleteMailbox"), + JobRequest::IsOnline(_) => write!(f, "JobRequest::IsOnline"), + JobRequest::Refresh(_, _) => write!(f, "JobRequest::Refresh"), + JobRequest::SetFlags(_, _) => write!(f, "JobRequest::SetFlags"), + JobRequest::SaveMessage(_, _) => write!(f, "JobRequest::SaveMessage"), + JobRequest::CopyTo(_, _) => write!(f, "JobRequest::CopyTo"), + JobRequest::DeleteMessage(_, _) => write!(f, "JobRequest::DeleteMessage"), + JobRequest::CreateMailbox(_) => write!(f, "JobRequest::CreateMailbox"), + JobRequest::DeleteMailbox(_) => write!(f, "JobRequest::DeleteMailbox"), //JobRequest::RenameMailbox, - JobRequest::Search => write!(f, "{}", "JobRequest::Search"), - JobRequest::AsBytes => write!(f, "{}", "JobRequest::AsBytes"), + JobRequest::Search => write!(f, "JobRequest::Search"), + JobRequest::AsBytes => write!(f, "JobRequest::AsBytes"), JobRequest::SetMailboxPermissions(_, _) => { - write!(f, "{}", "JobRequest::SetMailboxPermissions") + write!(f, "JobRequest::SetMailboxPermissions") } JobRequest::SetMailboxSubscription(_, _) => { - write!(f, "{}", "JobRequest::SetMailboxSubscription") + write!(f, "JobRequest::SetMailboxSubscription") } - JobRequest::Watch(_) => write!(f, "{}", "JobRequest::Watch"), + JobRequest::Watch(_) => write!(f, "JobRequest::Watch"), } } } @@ -501,7 +501,7 @@ impl Account { let (rcvr, job_id) = self.job_executor.spawn_specialized(mailbox_job); self.sender .send(ThreadEvent::UIEvent(UIEvent::StatusEvent( - StatusEvent::NewJob(job_id.clone()), + StatusEvent::NewJob(job_id), ))) .unwrap(); self.active_jobs.insert(job_id, JobRequest::Get(*h, rcvr)); @@ -836,7 +836,7 @@ impl Account { let (rcvr, job_id) = self.job_executor.spawn_specialized(refresh_job); self.sender .send(ThreadEvent::UIEvent(UIEvent::StatusEvent( - StatusEvent::NewJob(job_id.clone()), + StatusEvent::NewJob(job_id), ))) .unwrap(); self.active_jobs @@ -959,7 +959,7 @@ impl Account { self.job_executor.spawn_specialized(mailbox_job); self.sender .send(ThreadEvent::UIEvent(UIEvent::StatusEvent( - StatusEvent::NewJob(job_id.clone()), + StatusEvent::NewJob(job_id), ))) .unwrap(); self.active_jobs.insert( @@ -1150,7 +1150,7 @@ impl Account { let (rcvr, job_id) = self.job_executor.spawn_specialized(job); self.sender .send(ThreadEvent::UIEvent(UIEvent::StatusEvent( - StatusEvent::NewJob(job_id.clone()), + StatusEvent::NewJob(job_id), ))) .unwrap(); self.active_jobs @@ -1465,7 +1465,7 @@ impl Account { JobRequest::Get(mailbox_hash, mut chan) => { self.sender .send(ThreadEvent::UIEvent(UIEvent::StatusEvent( - StatusEvent::JobFinished(job_id.clone()), + StatusEvent::JobFinished(*job_id), ))) .unwrap(); @@ -1491,7 +1491,7 @@ impl Account { let (rcvr, job_id) = self.job_executor.spawn_specialized(rest.into_future()); self.sender .send(ThreadEvent::UIEvent(UIEvent::StatusEvent( - StatusEvent::NewJob(job_id.clone()), + StatusEvent::NewJob(job_id), ))) .unwrap(); self.active_jobs @@ -1561,7 +1561,7 @@ impl Account { } self.sender .send(ThreadEvent::UIEvent(UIEvent::StatusEvent( - StatusEvent::JobFinished(job_id.clone()), + StatusEvent::JobFinished(*job_id), ))) .unwrap(); } @@ -1664,7 +1664,7 @@ impl Account { JobRequest::Search | JobRequest::AsBytes => { self.sender .send(ThreadEvent::UIEvent(UIEvent::StatusEvent( - StatusEvent::JobFinished(job_id.clone()), + StatusEvent::JobFinished(*job_id), ))) .unwrap(); } diff --git a/src/conf/themes.rs b/src/conf/themes.rs index 5ccf5973..95d13248 100644 --- a/src/conf/themes.rs +++ b/src/conf/themes.rs @@ -241,7 +241,7 @@ fn unlink_attrs<'k, 't: 'k>(theme: &'t Theme, mut key: &'k Cow<'static, str>) -> } } -const DEFAULT_KEYS: &'static [&'static str] = &[ +const DEFAULT_KEYS: &[&str] = &[ "theme_default", "status.bar", "status.notification", @@ -504,7 +504,7 @@ mod regexp { use super::*; use crate::terminal::FormatTag; - pub(super) const DEFAULT_TEXT_FORMATTER_KEYS: &'static [&'static str] = + pub(super) const DEFAULT_TEXT_FORMATTER_KEYS: &[&str] = &["pager.envelope.body", "listing.from", "listing.subject"]; #[derive(Clone)] @@ -1582,7 +1582,7 @@ impl Default for Themes { add!("mail.view.thread.indentation.c", light = { bg: Color::Byte(175) }, dark = { bg: Color::Byte(175) }); // Pink3 add!("mail.view.thread.indentation.d", light = { bg: Color::Byte(220) }, dark = { bg: Color::Byte(220) }); // Gold1 add!("mail.view.thread.indentation.e", light = { bg: Color::Byte(172) }, dark = { bg: Color::Byte(172) }); // Orange3 - add!("mail.view.thread.indentation.f", light = { bg: Color::Byte(072) }, dark = { bg: Color::Byte(072) }); // CadetBlue + add!("mail.view.thread.indentation.f", light = { bg: Color::Byte(72) }, dark = { bg: Color::Byte(72) }); // CadetBlue add!( "mail.listing.attachment_flag", @@ -1727,29 +1727,27 @@ fn is_cyclic(theme: &Theme) -> std::result::Result<(), String> { ThemeValue::Link(ref l, ColorField::LikeSelf) | ThemeValue::Link(ref l, ColorField::Fg) => { path.push((l, Course::Fg)); - if !visited[&(l, Course::Fg)] - && is_cyclic_util(course, l, visited, stack, path, theme) + if (!visited[&(l, Course::Fg)] + && is_cyclic_util(course, l, visited, stack, path, theme)) + || stack[&(l, Course::Fg)] { return true; - } else if stack[&(l, Course::Fg)] { - return true; } path.pop(); } ThemeValue::Link(ref l, ColorField::Bg) => { path.push((l, Course::Bg)); - if !visited[&(l, Course::Bg)] - && is_cyclic_util(Course::Bg, l, visited, stack, path, theme) + if (!visited[&(l, Course::Bg)] + && is_cyclic_util(Course::Bg, l, visited, stack, path, theme)) + || stack[&(l, Course::Bg)] { return true; - } else if stack[&(l, Course::Bg)] { - return true; } path.pop(); } ThemeValue::Alias(ref ident) => { path.push((ident, Course::ColorAliasFg)); - if !visited[&(ident, Course::ColorAliasFg)] + if (!visited[&(ident, Course::ColorAliasFg)] && is_cyclic_util( Course::ColorAliasFg, ident, @@ -1757,11 +1755,10 @@ fn is_cyclic(theme: &Theme) -> std::result::Result<(), String> { stack, path, theme, - ) + )) + || stack[&(ident, Course::ColorAliasFg)] { return true; - } else if stack[&(ident, Course::ColorAliasFg)] { - return true; } path.pop(); } @@ -1771,29 +1768,27 @@ fn is_cyclic(theme: &Theme) -> std::result::Result<(), String> { ThemeValue::Link(ref l, ColorField::LikeSelf) | ThemeValue::Link(ref l, ColorField::Bg) => { path.push((l, Course::Bg)); - if !visited[&(l, Course::Bg)] - && is_cyclic_util(Course::Bg, l, visited, stack, path, theme) + if (!visited[&(l, Course::Bg)] + && is_cyclic_util(Course::Bg, l, visited, stack, path, theme)) + || stack[&(l, Course::Bg)] { return true; - } else if stack[&(l, Course::Bg)] { - return true; } path.pop(); } ThemeValue::Link(ref l, ColorField::Fg) => { path.push((l, Course::Fg)); - if !visited[&(l, Course::Fg)] - && is_cyclic_util(Course::Fg, l, visited, stack, path, theme) + if (!visited[&(l, Course::Fg)] + && is_cyclic_util(Course::Fg, l, visited, stack, path, theme)) + || stack[&(l, Course::Fg)] { return true; - } else if stack[&(l, Course::Fg)] { - return true; } path.pop(); } ThemeValue::Alias(ref ident) => { path.push((ident, Course::ColorAliasBg)); - if !visited[&(ident, Course::ColorAliasBg)] + if (!visited[&(ident, Course::ColorAliasBg)] && is_cyclic_util( Course::ColorAliasBg, ident, @@ -1801,11 +1796,10 @@ fn is_cyclic(theme: &Theme) -> std::result::Result<(), String> { stack, path, theme, - ) + )) + || stack[&(ident, Course::ColorAliasBg)] { return true; - } else if stack[&(ident, Course::ColorAliasBg)] { - return true; } path.pop(); } @@ -1814,23 +1808,28 @@ fn is_cyclic(theme: &Theme) -> std::result::Result<(), String> { Course::Attrs => match theme[k].attrs { ThemeValue::Link(ref l, _) => { path.push((l, course)); - if !visited[&(l, course)] - && is_cyclic_util(course, l, visited, stack, path, theme) + if (!visited[&(l, course)] + && is_cyclic_util(course, l, visited, stack, path, theme)) + || stack[&(l, course)] { return true; - } else if stack[&(l, course)] { - return true; } path.pop(); } ThemeValue::Alias(ref ident) => { path.push((ident, Course::AttrAlias)); - if !visited[&(ident, Course::AttrAlias)] - && is_cyclic_util(Course::AttrAlias, ident, visited, stack, path, theme) + if (!visited[&(ident, Course::AttrAlias)] + && is_cyclic_util( + Course::AttrAlias, + ident, + visited, + stack, + path, + theme, + )) + || stack[&(ident, Course::AttrAlias)] { return true; - } else if stack[&(ident, Course::AttrAlias)] { - return true; } path.pop(); } @@ -1848,23 +1847,21 @@ fn is_cyclic(theme: &Theme) -> std::result::Result<(), String> { (_, ColorField::Bg) => Course::Bg, }; path.push((l, course)); - if !visited[&(l, course)] - && is_cyclic_util(course, l, visited, stack, path, theme) + if (!visited[&(l, course)] + && is_cyclic_util(course, l, visited, stack, path, theme)) + || stack[&(l, course)] { return true; - } else if stack[&(l, course)] { - return true; } path.pop(); } ThemeValue::Alias(ref ident) => { path.push((ident, course)); - if !visited[&(ident, course)] - && is_cyclic_util(course, ident, visited, stack, path, theme) + if (!visited[&(ident, course)] + && is_cyclic_util(course, ident, visited, stack, path, theme)) + || stack[&(ident, course)] { return true; - } else if stack[&(ident, course)] { - return true; } path.pop(); } @@ -1873,23 +1870,21 @@ fn is_cyclic(theme: &Theme) -> std::result::Result<(), String> { Course::AttrAlias => match &theme.attr_aliases[k] { ThemeValue::Link(ref l, ()) => { path.push((l, Course::Attrs)); - if !visited[&(l, Course::Attrs)] - && is_cyclic_util(Course::Attrs, l, visited, stack, path, theme) + if (!visited[&(l, Course::Attrs)] + && is_cyclic_util(Course::Attrs, l, visited, stack, path, theme)) + || stack[&(l, Course::Attrs)] { return true; - } else if stack[&(l, Course::Attrs)] { - return true; } path.pop(); } ThemeValue::Alias(ref ident) => { path.push((ident, course)); - if !visited[&(ident, course)] - && is_cyclic_util(course, ident, visited, stack, path, theme) + if (!visited[&(ident, course)] + && is_cyclic_util(course, ident, visited, stack, path, theme)) + || stack[&(ident, course)] { return true; - } else if stack[&(ident, course)] { - return true; } path.pop(); } @@ -1898,7 +1893,7 @@ fn is_cyclic(theme: &Theme) -> std::result::Result<(), String> { } } stack.entry((k, course)).and_modify(|e| *e = false); - return false; + false } let mut path = SmallVec::new(); @@ -1973,7 +1968,7 @@ fn test_theme_parsing() { let def = Themes::default(); assert!(def.validate().is_ok()); /* MUST SUCCEED: new user theme `hunter2`, theme `dark` has user redefinitions */ - const TEST_STR: &'static str = r##"[dark] + const TEST_STR: &str = r##"[dark] "mail.listing.tag_default" = { fg = "White", bg = "HotPink3" } "mail.listing.attachment_flag" = { fg = "mail.listing.tag_default.bg" } "mail.view.headers" = { bg = "mail.listing.tag_default.fg" } @@ -2008,20 +2003,20 @@ fn test_theme_parsing() { ); assert!(parsed.validate().is_ok()); /* MUST FAIL: theme `dark` contains a cycle */ - const HAS_CYCLE: &'static str = r##"[dark] + const HAS_CYCLE: &str = r##"[dark] "mail.listing.compact.even" = { fg = "mail.listing.compact.odd" } "mail.listing.compact.odd" = { fg = "mail.listing.compact.even" } "##; let parsed: Themes = toml::from_str(HAS_CYCLE).unwrap(); assert!(parsed.validate().is_err()); /* MUST FAIL: theme `dark` contains an invalid key */ - const HAS_INVALID_KEYS: &'static str = r##"[dark] + const HAS_INVALID_KEYS: &str = r##"[dark] "asdfsafsa" = { fg = "Black" } "##; let parsed: std::result::Result = toml::from_str(HAS_INVALID_KEYS); assert!(parsed.is_err()); /* MUST SUCCEED: alias $Jebediah resolves to a valid color */ - const TEST_ALIAS_STR: &'static str = r##"[dark] + const TEST_ALIAS_STR: &str = r##"[dark] color_aliases= { "Jebediah" = "#b4da55" } "mail.listing.tag_default" = { fg = "$Jebediah" } "##; @@ -2036,42 +2031,42 @@ color_aliases= { "Jebediah" = "#b4da55" } Color::Rgb(180, 218, 85) ); /* MUST FAIL: Mispell color alias $Jebediah as $Jebedia */ - const TEST_INVALID_ALIAS_STR: &'static str = r##"[dark] + const TEST_INVALID_ALIAS_STR: &str = r##"[dark] color_aliases= { "Jebediah" = "#b4da55" } "mail.listing.tag_default" = { fg = "$Jebedia" } "##; let parsed: Themes = toml::from_str(TEST_INVALID_ALIAS_STR).unwrap(); assert!(parsed.validate().is_err()); /* MUST FAIL: Color alias $Jebediah is defined as itself */ - const TEST_CYCLIC_ALIAS_STR: &'static str = r##"[dark] + const TEST_CYCLIC_ALIAS_STR: &str = r##"[dark] color_aliases= { "Jebediah" = "$Jebediah" } "mail.listing.tag_default" = { fg = "$Jebediah" } "##; let parsed: Themes = toml::from_str(TEST_CYCLIC_ALIAS_STR).unwrap(); assert!(parsed.validate().is_err()); /* MUST FAIL: Attr alias $Jebediah is defined as itself */ - const TEST_CYCLIC_ALIAS_ATTR_STR: &'static str = r##"[dark] + const TEST_CYCLIC_ALIAS_ATTR_STR: &str = r##"[dark] attr_aliases= { "Jebediah" = "$Jebediah" } "mail.listing.tag_default" = { attrs = "$Jebediah" } "##; let parsed: Themes = toml::from_str(TEST_CYCLIC_ALIAS_ATTR_STR).unwrap(); assert!(parsed.validate().is_err()); /* MUST FAIL: alias $Jebediah resolves to a cycle */ - const TEST_CYCLIC_ALIAS_STR_2: &'static str = r##"[dark] + const TEST_CYCLIC_ALIAS_STR_2: &str = r##"[dark] color_aliases= { "Jebediah" = "$JebediahJr", "JebediahJr" = "mail.listing.tag_default" } "mail.listing.tag_default" = { fg = "$Jebediah" } "##; let parsed: Themes = toml::from_str(TEST_CYCLIC_ALIAS_STR_2).unwrap(); assert!(parsed.validate().is_err()); /* MUST SUCCEED: alias $Jebediah resolves to a key's field */ - const TEST_CYCLIC_ALIAS_STR_3: &'static str = r##"[dark] + const TEST_CYCLIC_ALIAS_STR_3: &str = r##"[dark] color_aliases= { "Jebediah" = "$JebediahJr", "JebediahJr" = "mail.listing.tag_default.bg" } "mail.listing.tag_default" = { fg = "$Jebediah", bg = "Black" } "##; let parsed: Themes = toml::from_str(TEST_CYCLIC_ALIAS_STR_3).unwrap(); assert!(parsed.validate().is_ok()); /* MUST FAIL: alias $Jebediah resolves to an invalid key */ - const TEST_INVALID_LINK_KEY_FIELD_STR: &'static str = r##"[dark] + const TEST_INVALID_LINK_KEY_FIELD_STR: &str = r##"[dark] color_aliases= { "Jebediah" = "$JebediahJr", "JebediahJr" = "mail.listing.tag_default.attrs" } "mail.listing.tag_default" = { fg = "$Jebediah", bg = "Black" } "##; diff --git a/src/execute.rs b/src/execute.rs index 2eaf1b63..34b00650 100644 --- a/src/execute.rs +++ b/src/execute.rs @@ -34,7 +34,6 @@ use melib::nom::{ }; pub use melib::thread::{SortField, SortOrder}; use melib::MeliError; -use std; pub mod actions; use actions::MailboxOperation; use std::collections::HashSet; @@ -776,11 +775,7 @@ pub fn command_completion_suggestions(input: &str) -> Vec { } if let Some((s, Filepath)) = _m.last() { let p = std::path::Path::new(s); - sugg.extend( - p.complete(true) - .into_iter() - .map(|m| m.into()), - ); + sugg.extend(p.complete(true).into_iter().map(|m| m.into())); } } sugg.into_iter() diff --git a/src/sqlite3.rs b/src/sqlite3.rs index dbe6e60b..450cae41 100644 --- a/src/sqlite3.rs +++ b/src/sqlite3.rs @@ -40,8 +40,8 @@ use std::convert::TryInto; use std::path::PathBuf; use std::sync::{Arc, RwLock}; -const DB_NAME: &'static str = "index.db"; -const INIT_SCRIPT: &'static str = "CREATE TABLE IF NOT EXISTS envelopes ( +const DB_NAME: &str = "index.db"; +const INIT_SCRIPT: &str = "CREATE TABLE IF NOT EXISTS envelopes ( id INTEGER PRIMARY KEY, account_id INTEGER REFERENCES accounts ON UPDATE CASCADE, hash BLOB NOT NULL UNIQUE, diff --git a/src/state.rs b/src/state.rs index 8ef7949a..0953019d 100644 --- a/src/state.rs +++ b/src/state.rs @@ -679,7 +679,7 @@ impl State { }, ), ); - copy_area(&mut self.overlay_grid, &mut self.grid, area, area); + copy_area(&mut self.overlay_grid, &self.grid, area, area); self.overlay .get_mut(0) .unwrap() diff --git a/src/terminal.rs b/src/terminal.rs index 92f447be..43ada7a4 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -233,7 +233,7 @@ mod braille { for b in iter { print!("{}", b); } - println!(""); + println!(); } println!("fbird: "); @@ -242,7 +242,7 @@ mod braille { for b in iter { print!("{}", b); } - println!(""); + println!(); } println!("ABC QR code: "); for lines in _X_QRCODE.chunks(12) { @@ -250,7 +250,7 @@ mod braille { for b in iter { print!("{}", b); } - println!(""); + println!(); } } } diff --git a/src/terminal/cells.rs b/src/terminal/cells.rs index 442cdfde..bc9121e0 100644 --- a/src/terminal/cells.rs +++ b/src/terminal/cells.rs @@ -283,7 +283,7 @@ impl CellBuffer { } else { scroll_region.right }; - for y in top..=(top + offset - 1) { + for y in top..top + offset { for x in l..r { self[(x, y)] = Cell::default(); } @@ -1103,7 +1103,7 @@ impl Color { _ => u8::from_str_radix(&s, 10) .map_err(|_| de::Error::custom("invalid `color` value"))?, }; - return Ok(Color::Byte(byte)); + Ok(Color::Byte(byte)) } } @@ -2795,7 +2795,7 @@ fn test_cellbuffer_search() { for c in &buf.cellvec()[ind..std::cmp::min(buf.cellvec().len(), ind + 25)] { print!("{}", c.ch()); } - println!(""); + println!(); } } diff --git a/src/terminal/keys.rs b/src/terminal/keys.rs index 6d145b44..28fb8cb9 100644 --- a/src/terminal/keys.rs +++ b/src/terminal/keys.rs @@ -163,7 +163,7 @@ pub fn get_events( mut closure: impl FnMut((Key, Vec)), rx: &Receiver, new_command_fd: RawFd, -) -> () { +) { let stdin = std::io::stdin(); let stdin_fd = PollFd::new(std::io::stdin().as_raw_fd(), PollFlags::POLLIN); let new_command_pollfd = nix::poll::PollFd::new(new_command_fd, nix::poll::PollFlags::POLLIN); diff --git a/src/types.rs b/src/types.rs index 232bc61c..df56e965 100644 --- a/src/types.rs +++ b/src/types.rs @@ -42,7 +42,6 @@ use super::terminal::*; use melib::backends::{AccountHash, MailboxHash}; use melib::{EnvelopeHash, RefreshEvent, ThreadHash}; use nix::unistd::Pid; -use std; use std::fmt; use std::thread; use uuid::Uuid; diff --git a/src/types/helpers.rs b/src/types/helpers.rs index 393ef0e6..8c02896c 100644 --- a/src/types/helpers.rs +++ b/src/types/helpers.rs @@ -19,7 +19,6 @@ * along with meli. If not, see . */ -use std; use std::fs; use std::fs::OpenOptions; use std::io::{Read, Write};