Browse Source

Fix clippy lints

tags/alpha-0.6.0
Manos Pitsidianakis 2 months ago
parent
commit
a7e177586a
WARNING! Although there is a key with this ID in the database it does not verify this commit! This commit is SUSPICIOUS. GPG Key ID: 73627C2F690DF710
60 changed files with 359 additions and 437 deletions
  1. +0
    -1
      Cargo.lock
  2. +1
    -1
      melib/build.rs
  3. +2
    -2
      melib/src/addressbook/vcard.rs
  4. +11
    -11
      melib/src/async_workers.rs
  5. +5
    -8
      melib/src/backends.rs
  6. +7
    -11
      melib/src/backends/imap.rs
  7. +2
    -2
      melib/src/backends/imap/cache.rs
  8. +4
    -5
      melib/src/backends/imap/connection.rs
  9. +7
    -7
      melib/src/backends/imap/operations.rs
  10. +12
    -11
      melib/src/backends/imap/protocol_parser.rs
  11. +10
    -11
      melib/src/backends/imap_async.rs
  12. +2
    -2
      melib/src/backends/imap_async/cache.rs
  13. +1
    -11
      melib/src/backends/imap_async/connection.rs
  14. +2
    -4
      melib/src/backends/imap_async/operations.rs
  15. +4
    -4
      melib/src/backends/imap_async/protocol_parser.rs
  16. +1
    -1
      melib/src/backends/imap_async/untagged.rs
  17. +2
    -2
      melib/src/backends/imap_async/watch.rs
  18. +4
    -5
      melib/src/backends/jmap.rs
  19. +1
    -1
      melib/src/backends/jmap/connection.rs
  20. +2
    -4
      melib/src/backends/jmap/protocol.rs
  21. +3
    -3
      melib/src/backends/jmap/rfc8620.rs
  22. +26
    -29
      melib/src/backends/maildir/backend.rs
  23. +0
    -5
      melib/src/backends/maildir/stream.rs
  24. +35
    -38
      melib/src/backends/mbox.rs
  25. +6
    -11
      melib/src/backends/notmuch.rs
  26. +3
    -3
      melib/src/collection.rs
  27. +15
    -16
      melib/src/datetime.rs
  28. +5
    -5
      melib/src/email/compose.rs
  29. +2
    -4
      melib/src/email/compose/mime.rs
  30. +8
    -8
      melib/src/email/list_management.rs
  31. +6
    -6
      melib/src/email/mailto.rs
  32. +10
    -10
      melib/src/email/parser.rs
  33. +1
    -1
      melib/src/error.rs
  34. +1
    -1
      melib/src/lib.rs
  35. +14
    -15
      melib/src/text_processing/line_break.rs
  36. +1
    -1
      melib/src/text_processing/mod.rs
  37. +1
    -1
      melib/src/text_processing/tables.rs
  38. +3
    -3
      melib/src/text_processing/wcwidth.rs
  39. +1
    -2
      melib/src/thread.rs
  40. +0
    -1
      src/bin.rs
  41. +2
    -3
      src/components/mail/compose.rs
  42. +3
    -3
      src/components/mail/listing/compact.rs
  43. +3
    -3
      src/components/mail/listing/conversations.rs
  44. +3
    -3
      src/components/mail/listing/plain.rs
  45. +20
    -35
      src/components/mail/view.rs
  46. +3
    -6
      src/components/mail/view/envelope.rs
  47. +4
    -4
      src/components/mail/view/thread.rs
  48. +0
    -1
      src/components/notifications.rs
  49. +2
    -2
      src/components/svg.rs
  50. +8
    -8
      src/components/utilities/widgets.rs
  51. +22
    -22
      src/conf/accounts.rs
  52. +57
    -62
      src/conf/themes.rs
  53. +1
    -6
      src/execute.rs
  54. +2
    -2
      src/sqlite3.rs
  55. +1
    -1
      src/state.rs
  56. +3
    -3
      src/terminal.rs
  57. +3
    -3
      src/terminal/cells.rs
  58. +1
    -1
      src/terminal/keys.rs
  59. +0
    -1
      src/types.rs
  60. +0
    -1
      src/types/helpers.rs

+ 0
- 1
Cargo.lock View File

@@ -943,7 +943,6 @@ dependencies = [
"nix",
"nom",
"notify",
"pin-utils",
"reqwest",
"rusqlite",
"serde",


+ 1
- 1
melib/build.rs View File

@@ -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())


+ 2
- 2
melib/src/addressbook/vcard.rs View File

@@ -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<T: VCardVersion>(


+ 11
- 11
melib/src/async_workers.rs View File

@@ -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<AsyncStatus<T>, ()> {
@@ -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(())
},
}
},
};
}
}
}

+ 5
- 8
melib/src/backends.rs View File

@@ -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<Result<Vec<Envelope>>>;
fn get_async(
&mut self,
mailbox: &Mailbox,
_mailbox: &Mailbox,
) -> Result<Pin<Box<dyn Stream<Item = Result<Vec<Envelope>>> + Send + 'static>>> {
Err(MeliError::new("Unimplemented."))
}
@@ -329,7 +328,7 @@ pub trait MailBackend: ::std::fmt::Debug + Send + Sync {
sender: RefreshEventConsumer,
work_context: WorkContext,
) -> Result<std::thread::ThreadId>;
fn watch_async(&self, sender: RefreshEventConsumer) -> ResultFuture<()> {
fn watch_async(&self, _sender: RefreshEventConsumer) -> ResultFuture<()> {
Err(MeliError::new("Unimplemented."))
}
fn mailboxes(&self) -> Result<HashMap<MailboxHash, Mailbox>>;
@@ -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)


+ 7
- 11
melib/src/backends/imap.rs View File

@@ -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::<Vec<&str>>().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 \"{}\" ({}) {{{}}}",


+ 2
- 2
melib/src/backends/imap/cache.rs View File

@@ -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 (


+ 4
- 5
melib/src/backends/imap/connection.rs View File

@@ -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(());
}


+ 7
- 7
melib/src/backends/imap/operations.rs View File

@@ -37,7 +37,6 @@ pub struct ImapOp {
impl ImapOp {
pub fn new(
uid: usize,
mailbox_path: String,
mailbox_hash: MailboxHash,
connection: Arc<Mutex<ImapConnection>>,
uid_store: Arc<UIDStore>,
@@ -66,7 +65,7 @@ impl BackendOp for ImapOp {
debug!(
"fetch response is {} bytes and {} lines",
response.len(),
response.lines().collect::<Vec<&str>>().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::<Vec<&str>>().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();


+ 12
- 11
melib/src/backends/imap/protocol_parser.rs View File

@@ -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<T: AsRef<str>> From<T> 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<Vec<UidFetchRespo
if let Some(el_alert) = el_alert {
match &mut alert {
Some(Alert(ref mut alert)) => {
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<String>)> {
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<u8>> {
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<Vec<u8>>> {
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


+ 10
- 11
melib/src/backends/imap_async.rs View File

@@ -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::<Vec<&str>>().len()
response.lines().count()
);
let (_, v, _) = protocol_parser::uid_fetch_responses(&response)?;
debug!("responses len is {}", v.len());


+ 2
- 2
melib/src/backends/imap_async/cache.rs View File

@@ -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 (


+ 1
- 11
melib/src/backends/imap_async/connection.rs View File

@@ -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<Output = Option<Vec<u8>>> + 'a {
pub fn as_stream<'a>(&'a mut self) -> impl Future<Output = Option<Vec<u8>>> + 'a {
self.result.drain(0..self.prev_res_length);
self.prev_res_length = 0;
let mut break_flag = false;


+ 2
- 4
melib/src/backends/imap_async/operations.rs View File

@@ -53,7 +53,6 @@ impl ImapOp {

impl BackendOp for ImapOp {
fn as_bytes(&mut self) -> ResultFuture<Vec<u8>> {
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);
}
}


+ 4
- 4
melib/src/backends/imap_async/protocol_parser.rs View File

@@ -1358,9 +1358,9 @@ pub fn quoted(input: &[u8]) -> IResult<&[u8], Vec<u8>> {
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<Vec<u8>>> {
@@ -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


+ 1
- 1
melib/src/backends/imap_async/untagged.rs View File

@@ -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) {


+ 2
- 2
melib/src/backends/imap_async/watch.rs View File

@@ -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!(


+ 4
- 5
melib/src/backends/jmap.rs View File

@@ -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();
}
}



+ 1
- 1
melib/src/backends/jmap/connection.rs View File

@@ -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");



+ 2
- 4
melib/src/backends/jmap/protocol.rs View File

@@ -64,7 +64,7 @@ pub trait Method<OBJ: Object>: 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<Vec<Envelope>> {
let email_call: EmailGet = EmailGet::new(
Get::new()
.ids(Some(JmapArgument::value(
ids.iter().cloned().collect::<Vec<String>>(),
)))
.ids(Some(JmapArgument::value(ids.to_vec())))
.account_id(conn.mail_account_id().to_string()),
);



+ 3
- 3
melib/src/backends/jmap/rfc8620.rs View File

@@ -166,10 +166,10 @@ impl<OBJ: Object + Serialize + std::fmt::Debug> Serialize for Get<OBJ> {
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<OBJ: Object + Serialize + std::fmt::Debug> Serialize for Get<OBJ> {
}
}

if !self.properties.is_none() {
if self.properties.is_some() {
state.serialize_field("properties", self.properties.as_ref().unwrap())?;
}



+ 26
- 29
melib/src/backends/maildir/backend.rs View File

@@ -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<()> {


+ 0
- 5
melib/src/backends/maildir/stream.rs View File

@@ -105,11 +105,6 @@ impl MaildirStream {
map: HashIndexes,
mailbox_index: Arc<Mutex<HashMap<EnvelopeHash, MailboxHash>>>,
) -> Result<Vec<Envelope>> {
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<Envelope> = Vec::with_capacity(chunk.len());


+ 35
- 38
melib/src/backends/mbox.rs View File

@@ -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) {


+ 6
- 11
melib/src/backends/notmuch.rs View File

@@ -189,7 +189,7 @@ impl NotmuchDb {
_is_subscribed: Box<dyn Fn(&str) -> bool>,
) -> Result<Box<dyn MailBackend>> {
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))));
}


+ 3
- 3
melib/src/collection.rs View File

@@ -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 }
}


+ 15
- 16
melib/src/datetime.rs View File

@@ -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<i64, ()> {
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<i64, ()> {

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<T>(s: T) -> Result<UnixTimestamp>
@@ -239,7 +237,7 @@ where
.unwrap_or(0));
}
}
return Ok(0);
Ok(0)
}

pub fn rfc3339_to_timestamp<T>(s: T) -> Result<UnixTimestamp>
@@ -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)),


+ 5
- 5
melib/src/email/compose.rs View File

@@ -340,15 +340,15 @@ fn build_multipart(ret: &mut String, kind: MultipartType, parts: Vec<AttachmentB
);
ret.push('\n');
/* rfc1341 */
ret.extend("This is a MIME formatted message with attachments. Use a MIME-compliant client to view it properly.\n".chars());
ret.push_str("This is a MIME formatted message with attachments. Use a MIME-compliant client to view it properly.\n");
for sub in parts {
ret.push_str("--");
ret.extend(boundary.chars());
ret.push_str(&boundary);
ret.push('\n');
print_attachment(ret, &kind, sub);
}
ret.push_str("--");
ret.extend(boundary.chars());
ret.push_str(&boundary);
ret.push_str("--\n");
}

@@ -365,7 +365,7 @@ fn print_attachment(ret: &mut String, kind: &MultipartType, a: AttachmentBuilder
ret.push('\n');
}
Text { .. } => {
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');


+ 2
- 4
melib/src/email/compose/mime.rs View File

@@ -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::<Vec<&str>>().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;


+ 8
- 8
melib/src/email/list_management.rs View File

@@ -61,7 +61,7 @@ impl<'a> ListAction<'a> {
});

vec.into_iter()
.map(|elem| ListAction::from(elem))
.map(ListAction::from)
.collect::<SmallVec<[ListAction<'a>; 4]>>()
})
.ok()
@@ -85,20 +85,20 @@ pub struct ListActions<'a> {
pub unsubscribe: Option<SmallVec<[ListAction<'a>; 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);


+ 6
- 6
melib/src/email/mailto.rs View File

@@ -41,10 +41,10 @@ impl From<Mailto> 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<Self, Self::Error> {
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{:?}",


+ 10
- 10
melib/src/email/parser.rs View File

@@ -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(),
));
))
}
}



+ 1
- 1
melib/src/error.rs View File

@@ -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() {


+ 1
- 1
melib/src/lib.rs View File

@@ -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"))]


+ 14
- 15
melib/src/text_processing/line_break.rs View File

@@ -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<usize>, offsets: &Vec<usize>) -> 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<usize>) -> V
* - Split lines with indices using str::match_indices()
* - Iterate and reflow flow regions, and pass fixed regions through
*/
let lines_indices: Vec<usize> = text.match_indices("\n").map(|(i, _)| i).collect();
let lines_indices: Vec<usize> = 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<usize>) -> 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<usize>) -> V

let breaks = LineBreakCandidateIter::new(line)
.collect::<Vec<(usize, LineBreakCandidate)>>();
&breaks.iter().enumerate().collect::<Vec<_>>();
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<usize>) -> 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<String>, 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);


+ 1
- 1
melib/src/text_processing/mod.rs View File

@@ -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


+ 1
- 1
melib/src/text_processing/tables.rs View File

@@ -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),


+ 3
- 3
melib/src/text_processing/wcwidth.rs View File

@@ -169,7 +169,7 @@ fn bisearch(ucs: WChar, table: &'static [Interval]) -> bool {

pub fn wcwidth(ucs: WChar) -> Option<usize> {
/* 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<usize> {
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<usize> {
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] (⏰)


+ 1
- 2
melib/src/thread.rs View File

@@ -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,


+ 0
- 1
src/bin.rs View File

@@ -84,7 +84,6 @@ pub mod jobs;
pub mod mailcap;
pub mod plugins;

use nix;
use std::os::raw::c_int;

fn notify(


+ 2
- 3
src/components/mail/compose.rs View File

@@ -220,7 +220,7 @@ impl Composer {
id,
Box::new(
results
.into_iter()
.iter()
.map(|a| a.to_string())
.collect::<Vec<String>>()
.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) => {


+ 3
- 3
src/components/mail/listing/compact.rs View File

@@ -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::<usize>() > width {
let diff = self.data_columns.widths.iter().sum::<usize>() - width;
if self.data_columns.widths[2] > 2 * diff {
self.data_columns.widths[2] -= diff;
} else {


+ 3
- 3
src/components/mail/listing/conversations.rs View File

@@ -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) => {


+ 3
- 3
src/components/mail/listing/plain.rs View File

@@ -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;


+ 20
- 35
src/components/mail/view.rs View File

@@ -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)),
));