melib: fix some clippy lints

issue-133
Manos Pitsidianakis 2022-09-18 00:09:23 +03:00
parent 787c64c2da
commit b138d9bc61
32 changed files with 975 additions and 1362 deletions

View File

@ -161,7 +161,7 @@ fn main() -> Result<(), std::io::Error> {
}
}
fn set_general_categories<'u>(codepoints: &mut Vec<Codepoint<'u>>, unicode_data: &'u str) {
fn set_general_categories<'u>(codepoints: &mut [Codepoint<'u>], unicode_data: &'u str) {
for line in unicode_data.lines() {
let fields = line.trim().split(';').collect::<Vec<_>>();
if fields.len() > FIELD_CATEGORY {
@ -172,7 +172,7 @@ fn main() -> Result<(), std::io::Error> {
}
}
fn set_eaw_widths(codepoints: &mut Vec<Codepoint<'_>>, eaw_data_lines: &str) {
fn set_eaw_widths(codepoints: &mut [Codepoint<'_>], eaw_data_lines: &str) {
// Read from EastAsianWidth.txt, set width values on the codepoints
for line in eaw_data_lines.lines() {
let line = line.trim().split('#').next().unwrap_or(line);
@ -220,7 +220,8 @@ fn main() -> Result<(), std::io::Error> {
}
}
}
fn set_emoji_widths(codepoints: &mut Vec<Codepoint<'_>>, emoji_data_lines: &str) {
fn set_emoji_widths(codepoints: &mut [Codepoint<'_>], emoji_data_lines: &str) {
// Read from emoji-data.txt, set codepoint widths
for line in emoji_data_lines.lines() {
if !line.contains('#') || line.trim().starts_with('#') {
@ -302,7 +303,7 @@ fn main() -> Result<(), std::io::Error> {
}
}
}
fn set_hardcoded_ranges(codepoints: &mut Vec<Codepoint<'_>>) {
fn set_hardcoded_ranges(codepoints: &mut [Codepoint<'_>]) {
// Mark private use and surrogate codepoints
// Private use can be determined awkwardly from UnicodeData.txt,
// but we just hard-code them.

View File

@ -52,7 +52,6 @@ use futures::stream::Stream;
use std::collections::hash_map::DefaultHasher;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::convert::TryFrom;
use std::convert::TryInto;
use std::hash::Hasher;
use std::pin::Pin;
use std::str::FromStr;
@ -192,7 +191,7 @@ impl UIDStore {
#[derive(Debug)]
pub struct ImapType {
is_subscribed: Arc<IsSubscribedFn>,
_is_subscribed: Arc<IsSubscribedFn>,
connection: Arc<FutureMutex<ImapConnection>>,
server_conf: ImapServerConf,
uid_store: Arc<UIDStore>,
@ -274,7 +273,7 @@ impl MailBackend for ImapType {
_ => {
if SUPPORTED_CAPABILITIES
.iter()
.any(|c| c.eq_ignore_ascii_case(&name.as_str()))
.any(|c| c.eq_ignore_ascii_case(name.as_str()))
{
*status = MailBackendExtensionStatus::Enabled { comment: None };
}
@ -1121,32 +1120,32 @@ impl MailBackend for ImapType {
Subject(t) => {
s.push_str(" SUBJECT \"");
s.extend(escape_double_quote(t).chars());
s.push_str("\"");
s.push('"');
}
From(t) => {
s.push_str(" FROM \"");
s.extend(escape_double_quote(t).chars());
s.push_str("\"");
s.push('"');
}
To(t) => {
s.push_str(" TO \"");
s.extend(escape_double_quote(t).chars());
s.push_str("\"");
s.push('"');
}
Cc(t) => {
s.push_str(" CC \"");
s.extend(escape_double_quote(t).chars());
s.push_str("\"");
s.push('"');
}
Bcc(t) => {
s.push_str(" BCC \"");
s.extend(escape_double_quote(t).chars());
s.push_str("\"");
s.push('"');
}
AllText(t) => {
s.push_str(" TEXT \"");
s.extend(escape_double_quote(t).chars());
s.push_str("\"");
s.push('"');
}
Flags(v) => {
for f in v {
@ -1280,7 +1279,7 @@ impl ImapType {
};
let server_port = get_conf_val!(s["server_port"], 143)?;
let use_tls = get_conf_val!(s["use_tls"], true)?;
let use_starttls = use_tls && get_conf_val!(s["use_starttls"], !(server_port == 993))?;
let use_starttls = use_tls && get_conf_val!(s["use_starttls"], server_port != 993)?;
let danger_accept_invalid_certs: bool =
get_conf_val!(s["danger_accept_invalid_certs"], false)?;
#[cfg(feature = "sqlite3")]
@ -1338,7 +1337,7 @@ impl ImapType {
Ok(Box::new(ImapType {
server_conf,
is_subscribed: Arc::new(IsSubscribedFn(is_subscribed)),
_is_subscribed: Arc::new(IsSubscribedFn(is_subscribed)),
connection: Arc::new(FutureMutex::new(connection)),
uid_store,
}))
@ -1459,7 +1458,7 @@ impl ImapType {
} else {
mailboxes.insert(mailbox.hash, mailbox);
}
} else if let Ok(status) = protocol_parser::status_response(&l).map(|(_, v)| v) {
} else if let Ok(status) = protocol_parser::status_response(l).map(|(_, v)| v) {
if let Some(mailbox_hash) = status.mailbox {
if mailboxes.contains_key(&mailbox_hash) {
let entry = mailboxes.entry(mailbox_hash).or_default();
@ -1484,7 +1483,7 @@ impl ImapType {
if !l.starts_with(b"*") {
continue;
}
if let Ok(subscription) = protocol_parser::list_mailbox_result(&l).map(|(_, v)| v) {
if let Ok(subscription) = protocol_parser::list_mailbox_result(l).map(|(_, v)| v) {
if let Some(f) = mailboxes.get_mut(&subscription.hash()) {
if f.special_usage() == SpecialUsageMailbox::Normal
&& subscription.special_usage() != SpecialUsageMailbox::Normal
@ -1862,7 +1861,7 @@ async fn fetch_hlpr(state: &mut FetchState) -> Result<Vec<Envelope>> {
.unwrap()
.entry(mailbox_hash)
.or_default()
.insert((message_sequence_number - 1).try_into().unwrap(), uid);
.insert(message_sequence_number - 1, uid);
uid_store
.hash_index
.lock()

View File

@ -178,7 +178,7 @@ mod sqlite3_m {
let mut ret: Vec<UID> = stmt
.query_map(sqlite3::params![mailbox_hash as i64], |row| {
Ok(row.get(0).map(|i: Sqlite3UID| i as UID)?)
row.get(0).map(|i: Sqlite3UID| i as UID)
})?
.collect::<std::result::Result<_, _>>()?;
Ok(ret.pop().unwrap_or(0))
@ -231,7 +231,7 @@ mod sqlite3_m {
.unwrap()
.entry(mailbox_hash)
.and_modify(|entry| *entry = highestmodseq.ok_or(()))
.or_insert(highestmodseq.ok_or(()));
.or_insert_with(|| highestmodseq.ok_or(()));
self.uid_store
.uidvalidity
.lock()
@ -483,7 +483,7 @@ mod sqlite3_m {
for (uid, event) in refresh_events {
match &event.kind {
RefreshEventKind::Remove(env_hash) => {
hash_index_lck.remove(&env_hash);
hash_index_lck.remove(env_hash);
tx.execute(
"DELETE FROM envelopes WHERE mailbox_hash = ?1 AND uid = ?2;",
sqlite3::params![mailbox_hash as i64, *uid as Sqlite3UID],
@ -503,7 +503,7 @@ mod sqlite3_m {
let mut ret: Vec<Envelope> = stmt
.query_map(
sqlite3::params![mailbox_hash as i64, *uid as Sqlite3UID],
|row| Ok(row.get(0)?),
|row| row.get(0),
)?
.collect::<std::result::Result<_, _>>()?;
if let Some(mut env) = ret.pop() {
@ -592,12 +592,12 @@ mod sqlite3_m {
return Ok(None);
}
let (uid, inner, modsequence) = ret.pop().unwrap();
return Ok(Some(CachedEnvelope {
Ok(Some(CachedEnvelope {
inner,
uid,
mailbox_hash,
modsequence,
}));
}))
}
fn rfc822(
@ -613,7 +613,7 @@ mod sqlite3_m {
let x = stmt
.query_map(
sqlite3::params![mailbox_hash as i64, uid as Sqlite3UID],
|row| Ok(row.get(0)?),
|row| row.get(0),
)?
.collect::<std::result::Result<_, _>>()?;
x
@ -625,7 +625,7 @@ mod sqlite3_m {
let x = stmt
.query_map(
sqlite3::params![mailbox_hash as i64, env_hash as i64],
|row| Ok(row.get(0)?),
|row| row.get(0),
)?
.collect::<std::result::Result<_, _>>()?;
x
@ -655,19 +655,19 @@ pub(super) async fn fetch_cached_envs(state: &mut FetchState) -> Result<Option<V
{
let mut conn = connection.lock().await;
match conn.load_cache(mailbox_hash).await {
None => return Ok(None),
None => Ok(None),
Some(Ok(env_hashes)) => {
let env_lck = uid_store.envelopes.lock().unwrap();
return Ok(Some(
Ok(Some(
env_hashes
.into_iter()
.filter_map(|env_hash| {
env_lck.get(&env_hash).map(|c_env| c_env.inner.clone())
})
.collect::<Vec<Envelope>>(),
));
))
}
Some(Err(err)) => return Err(err),
Some(Err(err)) => Err(err),
}
}
}

View File

@ -398,7 +398,7 @@ impl ImapStream {
r#"LOGIN "{}" {{{}}}"#,
&server_conf
.server_username
.replace(r#"\"#, r#"\\"#)
.replace('\\', r#"\\"#)
.replace('"', r#"\""#)
.replace('{', r#"\{"#)
.replace('}', r#"\}"#),

View File

@ -257,7 +257,7 @@ pub enum ImapResponse {
impl TryFrom<&'_ [u8]> for ImapResponse {
type Error = MeliError;
fn try_from(val: &'_ [u8]) -> Result<ImapResponse> {
let val: &[u8] = val.split_rn().last().unwrap_or_else(|| val.as_ref());
let val: &[u8] = val.split_rn().last().unwrap_or(val);
let mut val = val[val.find(b" ").ok_or_else(|| {
MeliError::new(format!(
"Expected tagged IMAP response (OK,NO,BAD, etc) but found {:?}",
@ -664,7 +664,7 @@ pub fn fetch_response(input: &[u8]) -> ImapParseResult<FetchResponse<'_>> {
i += b"BODY[HEADER.FIELDS (REFERENCES)] ".len();
if let Ok((rest, mut references)) = astring_token(&input[i..]) {
if !references.trim().is_empty() {
if let Ok((_, (_, v))) = crate::email::parser::headers::header(&references) {
if let Ok((_, (_, v))) = crate::email::parser::headers::header(references) {
references = v;
}
ret.references = Some(references);
@ -680,7 +680,7 @@ pub fn fetch_response(input: &[u8]) -> ImapParseResult<FetchResponse<'_>> {
i += b"BODY[HEADER.FIELDS (\"REFERENCES\")] ".len();
if let Ok((rest, mut references)) = astring_token(&input[i..]) {
if !references.trim().is_empty() {
if let Ok((_, (_, v))) = crate::email::parser::headers::header(&references) {
if let Ok((_, (_, v))) = crate::email::parser::headers::header(references) {
references = v;
}
ret.references = Some(references);
@ -737,7 +737,7 @@ pub fn fetch_responses(mut input: &[u8]) -> ImapParseResult<Vec<FetchResponse<'_
Err(err) => {
return Err(MeliError::new(format!(
"Unexpected input while parsing UID FETCH responses: `{:.40}`, {}",
String::from_utf8_lossy(&input),
String::from_utf8_lossy(input),
err
)));
}
@ -749,7 +749,7 @@ pub fn fetch_responses(mut input: &[u8]) -> ImapParseResult<Vec<FetchResponse<'_
} else {
return Err(MeliError::new(format!(
"310Unexpected input while parsing UID FETCH responses: `{:.40}`",
String::from_utf8_lossy(&input)
String::from_utf8_lossy(input)
)));
}
}
@ -923,7 +923,7 @@ pub fn untagged_responses(input: &[u8]) -> ImapParseResult<Option<UntaggedRespon
_ => {
debug!(
"unknown untagged_response: {}",
String::from_utf8_lossy(&_tag)
String::from_utf8_lossy(_tag)
);
None
}
@ -1617,7 +1617,7 @@ pub fn status_response(input: &[u8]) -> IResult<&[u8], StatusResponse> {
// ; is considered to be INBOX and not an astring.
// ; Refer to section 5.1 for further
// ; semantic details of mailbox names.
pub fn mailbox_token<'i>(input: &'i [u8]) -> IResult<&'i [u8], std::borrow::Cow<'i, str>> {
pub fn mailbox_token(input: &'_ [u8]) -> IResult<&'_ [u8], std::borrow::Cow<'_, str>> {
let (input, astring) = astring_token(input)?;
if astring.eq_ignore_ascii_case(b"INBOX") {
return Ok((input, "INBOX".into()));

View File

@ -222,7 +222,7 @@ impl ImapConnection {
}
let uid = uid.unwrap();
let env = envelope.as_mut().unwrap();
env.set_hash(generate_envelope_hash(&mailbox.imap_path(), &uid));
env.set_hash(generate_envelope_hash(mailbox.imap_path(), &uid));
if let Some(value) = references {
env.set_references(value);
}
@ -317,9 +317,10 @@ impl ImapConnection {
let command = {
let mut iter = v.split(u8::is_ascii_whitespace);
let first = iter.next().unwrap_or(v);
let mut accum = format!("{}", to_str!(first).trim());
let mut accum = to_str!(first).trim().to_string();
for ms in iter {
accum = format!("{},{}", accum, to_str!(ms).trim());
accum.push(',');
accum.push_str(to_str!(ms).trim());
}
format!("UID FETCH {} (UID FLAGS ENVELOPE BODY.PEEK[HEADER.FIELDS (REFERENCES)] BODYSTRUCTURE)", accum)
};
@ -352,7 +353,7 @@ impl ImapConnection {
}
let uid = uid.unwrap();
let env = envelope.as_mut().unwrap();
env.set_hash(generate_envelope_hash(&mailbox.imap_path(), &uid));
env.set_hash(generate_envelope_hash(mailbox.imap_path(), &uid));
if let Some(value) = references {
env.set_references(value);
}

View File

@ -82,7 +82,7 @@ impl MaildirOp {
Ok(if let Some(modif) = &map[&self.hash].modified {
match modif {
PathMod::Path(ref path) => path.clone(),
PathMod::Hash(hash) => map[&hash].to_path_buf(),
PathMod::Hash(hash) => map[hash].to_path_buf(),
}
} else {
map.get(&self.hash).unwrap().to_path_buf()
@ -148,7 +148,7 @@ impl MaildirMailbox {
PathBuf::from(&settings.root_mailbox)
.expand()
.parent()
.unwrap_or_else(|| &Path::new("/")),
.unwrap_or_else(|| Path::new("/")),
)
.ok();
@ -217,7 +217,7 @@ impl BackendMailbox for MaildirMailbox {
}
fn path(&self) -> &str {
self.path.to_str().unwrap_or(self.name())
self.path.to_str().unwrap_or_else(|| self.name())
}
fn change_name(&mut self, s: &str) {

View File

@ -84,7 +84,7 @@ impl From<PathBuf> for MaildirPath {
#[derive(Debug, Default)]
pub struct HashIndex {
index: HashMap<EnvelopeHash, MaildirPath>,
hash: MailboxHash,
_hash: MailboxHash,
}
impl Deref for HashIndex {
@ -516,7 +516,7 @@ impl MailBackend for MaildirType {
PathMod::Hash(hash) => debug!(
"envelope {} has modified path set {}",
hash,
&index_lock[&hash].buf.display()
&index_lock[hash].buf.display()
),
}
index_lock.entry(hash).and_modify(|e| {
@ -854,7 +854,7 @@ impl MailBackend for MaildirType {
if let Some(modif) = &hash_index[&env_hash].modified {
match modif {
PathMod::Path(ref path) => path.clone(),
PathMod::Hash(hash) => hash_index[&hash].to_path_buf(),
PathMod::Hash(hash) => hash_index[hash].to_path_buf(),
}
} else {
hash_index[&env_hash].to_path_buf()
@ -919,7 +919,7 @@ impl MailBackend for MaildirType {
if let Some(modif) = &hash_index[&env_hash].modified {
match modif {
PathMod::Path(ref path) => path.clone(),
PathMod::Hash(hash) => hash_index[&hash].to_path_buf(),
PathMod::Hash(hash) => hash_index[hash].to_path_buf(),
}
} else {
hash_index[&env_hash].to_path_buf()
@ -959,15 +959,15 @@ impl MailBackend for MaildirType {
if let Some(modif) = &hash_index[&env_hash].modified {
match modif {
PathMod::Path(ref path) => path.clone(),
PathMod::Hash(hash) => hash_index[&hash].to_path_buf(),
PathMod::Hash(hash) => hash_index[hash].to_path_buf(),
}
} else {
hash_index[&env_hash].to_path_buf()
}
};
let filename = path_src
.file_name()
.expect(&format!("Could not get filename of {}", path_src.display()));
let filename = path_src.file_name().ok_or_else(|| {
format!("Could not get filename of `{}`", path_src.display(),)
})?;
dest_path.push(filename);
hash_index.entry(env_hash).or_default().modified =
Some(PathMod::Path(dest_path.clone()));
@ -1114,7 +1114,7 @@ impl MaildirType {
None,
Vec::new(),
false,
&settings,
settings,
) {
f.children = recurse_mailboxes(mailboxes, settings, &path)?;
for c in &f.children {
@ -1137,7 +1137,7 @@ impl MaildirType {
None,
subdirs,
true,
&settings,
settings,
) {
for c in &f.children {
if let Some(f) = mailboxes.get_mut(c) {
@ -1213,7 +1213,7 @@ impl MaildirType {
fh,
HashIndex {
index: HashMap::with_capacity_and_hasher(0, Default::default()),
hash: fh,
_hash: fh,
},
);
}
@ -1319,25 +1319,17 @@ impl MaildirType {
pub fn list_mail_in_maildir_fs(mut path: PathBuf, read_only: bool) -> Result<Vec<PathBuf>> {
let mut files: Vec<PathBuf> = vec![];
path.push("new");
for d in path.read_dir()? {
if let Ok(p) = d {
if !read_only {
move_to_cur(p.path()).ok().take();
} else {
files.push(p.path());
}
for p in path.read_dir()?.flatten() {
if !read_only {
move_to_cur(p.path()).ok().take();
} else {
files.push(p.path());
}
}
path.pop();
path.push("cur");
let iter = path.read_dir()?;
for e in iter {
let e = e.and_then(|x| {
let path = x.path();
Ok(path)
})?;
files.push(e);
for e in path.read_dir()?.flatten() {
files.push(e.path());
}
Ok(files)
}

View File

@ -52,23 +52,16 @@ impl MaildirStream {
) -> Result<Pin<Box<dyn Stream<Item = Result<Vec<Envelope>>> + Send + 'static>>> {
let chunk_size = 2048;
path.push("new");
for d in path.read_dir()? {
if let Ok(p) = d {
move_to_cur(p.path()).ok().take();
}
for p in path.read_dir()?.flatten() {
move_to_cur(p.path()).ok().take();
}
path.pop();
path.push("cur");
let iter = path.read_dir()?;
let count = path.read_dir()?.count();
let mut files: Vec<PathBuf> = Vec::with_capacity(count);
for e in iter {
let e = e.and_then(|x| {
let path = x.path();
Ok(path)
})?;
files.push(e);
}
let files: Vec<PathBuf> = path
.read_dir()?
.flatten()
.map(|e| e.path())
.collect::<Vec<_>>();
let payloads = Box::pin(if !files.is_empty() {
files
.chunks(chunk_size)

View File

@ -271,7 +271,7 @@ impl BackendMailbox for MboxMailbox {
/// `BackendOp` implementor for Mbox
#[derive(Debug, Default)]
pub struct MboxOp {
hash: EnvelopeHash,
_hash: EnvelopeHash,
path: PathBuf,
offset: Offset,
length: Length,
@ -279,9 +279,9 @@ pub struct MboxOp {
}
impl MboxOp {
pub fn new(hash: EnvelopeHash, path: &Path, offset: Offset, length: Length) -> Self {
pub fn new(_hash: EnvelopeHash, path: &Path, offset: Offset, length: Length) -> Self {
MboxOp {
hash,
_hash,
path: path.to_path_buf(),
slice: std::cell::RefCell::new(None),
offset,
@ -883,7 +883,7 @@ impl MailBackend for MboxType {
drop(mailboxes_lck);
let mut message_iter = MessageIterator {
index,
input: &self.contents.as_slice(),
input: self.contents.as_slice(),
offset: self.offset,
file_offset: self.file_offset,
format: self.prefer_mbox_type,

View File

@ -50,7 +50,7 @@ impl MboxFormat {
writer.write_all(&b" "[..])?;
writer.write_all(
crate::datetime::timestamp_to_string(
delivery_date.unwrap_or_else(|| crate::datetime::now()),
delivery_date.unwrap_or_else(crate::datetime::now),
Some(crate::datetime::ASCTIME_FMT),
true,
)

View File

@ -108,7 +108,6 @@ type Capabilities = HashSet<String>;
pub struct UIDStore {
account_hash: AccountHash,
account_name: Arc<String>,
offline_cache: bool,
capabilities: Arc<Mutex<Capabilities>>,
message_id_index: Arc<Mutex<HashMap<String, EnvelopeHash>>>,
hash_index: Arc<Mutex<HashMap<EnvelopeHash, (UID, MailboxHash)>>>,
@ -130,7 +129,6 @@ impl UIDStore {
account_hash,
account_name,
event_consumer,
offline_cache: false,
capabilities: Default::default(),
message_id_index: Default::default(),
hash_index: Default::default(),
@ -147,11 +145,11 @@ impl UIDStore {
#[derive(Debug)]
pub struct NntpType {
is_subscribed: Arc<IsSubscribedFn>,
_is_subscribed: Arc<IsSubscribedFn>,
connection: Arc<FutureMutex<NntpConnection>>,
server_conf: NntpServerConf,
uid_store: Arc<UIDStore>,
can_create_flags: Arc<Mutex<bool>>,
_can_create_flags: Arc<Mutex<bool>>,
}
impl MailBackend for NntpType {
@ -251,8 +249,7 @@ impl MailBackend for NntpType {
/* To get updates, either issue NEWNEWS if it's supported by the server, and fallback
* to OVER otherwise */
let mbox: NntpMailbox = uid_store.mailboxes.lock().await.get(&mailbox_hash).map(std::clone::Clone::clone).ok_or_else(|| MeliError::new(format!("Mailbox with hash {} not found in NNTP connection, this could possibly be a bug or it was deleted.", mailbox_hash)))?;
let latest_article: Option<crate::UnixTimestamp> =
mbox.latest_article.lock().unwrap().clone();
let latest_article: Option<crate::UnixTimestamp> = *mbox.latest_article.lock().unwrap();
let (over_msgid_support, newnews_support): (bool, bool) = {
let caps = uid_store.capabilities.lock().unwrap();
@ -599,7 +596,6 @@ impl NntpType {
)));
}
let uid_store: Arc<UIDStore> = Arc::new(UIDStore {
offline_cache: false, //get_conf_val!(s["X_header_caching"], false)?,
mailboxes: Arc::new(FutureMutex::new(mailboxes)),
..UIDStore::new(account_hash, account_name, event_consumer)
});
@ -607,8 +603,8 @@ impl NntpType {
Ok(Box::new(NntpType {
server_conf,
is_subscribed: Arc::new(IsSubscribedFn(is_subscribed)),
can_create_flags: Arc::new(Mutex::new(false)),
_is_subscribed: Arc::new(IsSubscribedFn(is_subscribed)),
_can_create_flags: Arc::new(Mutex::new(false)),
connection: Arc::new(FutureMutex::new(connection)),
uid_store,
}))
@ -699,7 +695,7 @@ impl NntpType {
let _ = get_conf_val!(s["server_password_command"]);
let server_port = get_conf_val!(s["server_port"], 119)?;
let use_tls = get_conf_val!(s["use_tls"], server_port == 563)?;
let use_starttls = get_conf_val!(s["use_starttls"], !(server_port == 563))?;
let use_starttls = get_conf_val!(s["use_starttls"], server_port != 563)?;
if !use_tls && use_starttls {
return Err(MeliError::new(format!(
"Configuration error ({}): incompatible use_tls and use_starttls values: use_tls = false, use_starttls = true",

View File

@ -102,7 +102,7 @@ impl DbConnection {
*self.revision_uuid.read().unwrap(),
new_revision_uuid
);
let query: Query = Query::new(&self, &query_str)?;
let query: Query = Query::new(self, &query_str)?;
let iter = query.search()?;
let mailbox_index_lck = mailbox_index.write().unwrap();
let mailboxes_lck = mailboxes.read().unwrap();
@ -156,7 +156,7 @@ impl DbConnection {
}
drop(query);
index.write().unwrap().retain(|&env_hash, msg_id| {
if Message::find_message(&self, &msg_id).is_err() {
if Message::find_message(self, msg_id).is_err() {
if let Some(mailbox_hashes) = mailbox_index_lck.get(&env_hash) {
for &mailbox_hash in mailbox_hashes {
let m = &mailboxes_lck[&mailbox_hash];
@ -224,7 +224,7 @@ pub struct NotmuchDb {
mailbox_index: Arc<RwLock<HashMap<EnvelopeHash, SmallVec<[MailboxHash; 16]>>>>,
collection: Collection,
path: PathBuf,
account_name: Arc<String>,
_account_name: Arc<String>,
account_hash: AccountHash,
event_consumer: BackendEventConsumer,
save_messages_to: Option<PathBuf>,
@ -408,7 +408,7 @@ impl NotmuchDb {
mailboxes: Arc::new(RwLock::new(mailboxes)),
save_messages_to: None,
account_name: Arc::new(s.name().to_string()),
_account_name: Arc::new(s.name().to_string()),
account_hash,
event_consumer,
}))
@ -694,7 +694,7 @@ impl MailBackend for NotmuchDb {
index.clone(),
mailbox_index.clone(),
collection.tag_index.clone(),
account_hash.clone(),
account_hash,
event_consumer.clone(),
new_revision_uuid,
)?;
@ -728,7 +728,6 @@ impl MailBackend for NotmuchDb {
hash,
index: self.index.clone(),
bytes: None,
collection: self.collection.clone(),
}))
}
@ -932,7 +931,6 @@ impl MailBackend for NotmuchDb {
struct NotmuchOp {
hash: EnvelopeHash,
index: Arc<RwLock<HashMap<EnvelopeHash, CString>>>,
collection: Collection,
database: Arc<DbConnection>,
bytes: Option<Vec<u8>>,
#[allow(dead_code)]
@ -1061,7 +1059,7 @@ impl MelibQueryToNotmuchQuery for crate::search::Query {
ret.push(c);
}
}
ret.push_str("\"");
ret.push('"');
}
To(s) | Cc(s) | Bcc(s) => {
ret.push_str("to:\"");
@ -1072,7 +1070,7 @@ impl MelibQueryToNotmuchQuery for crate::search::Query {
ret.push(c);
}
}
ret.push_str("\"");
ret.push('"');
}
InReplyTo(_s) | References(_s) | AllAddresses(_s) => {}
/* * * * */
@ -1085,7 +1083,7 @@ impl MelibQueryToNotmuchQuery for crate::search::Query {
ret.push(c);
}
}
ret.push_str("\"");
ret.push('"');
}
Subject(s) => {
ret.push_str("subject:\"");
@ -1096,10 +1094,10 @@ impl MelibQueryToNotmuchQuery for crate::search::Query {
ret.push(c);
}
}
ret.push_str("\"");
ret.push('"');
}
AllText(s) => {
ret.push_str("\"");
ret.push('"');
for c in s.chars() {
if c == '"' {
ret.push_str("\\\"");
@ -1107,7 +1105,7 @@ impl MelibQueryToNotmuchQuery for crate::search::Query {
ret.push(c);
}
}
ret.push_str("\"");
ret.push('"');
}
/* * * * */
Flags(v) => {

View File

@ -247,7 +247,7 @@ impl<'m> Message<'m> {
pub fn get_filename(&self) -> &OsStr {
let fs_path = unsafe { call!(self.lib, notmuch_message_get_filename)(self.message) };
let c_str = unsafe { CStr::from_ptr(fs_path) };
&OsStr::from_bytes(c_str.to_bytes())
OsStr::from_bytes(c_str.to_bytes())
}
}

View File

@ -202,23 +202,19 @@ impl ToggleFlag {
ToggleFlag::Unset == *self
}
pub fn is_internal(&self) -> bool {
if let ToggleFlag::InternalVal(_) = *self {
true
} else {
false
}
matches!(self, ToggleFlag::InternalVal(_))
}
pub fn is_ask(&self) -> bool {
*self == ToggleFlag::Ask
matches!(self, ToggleFlag::Ask)
}
pub fn is_false(&self) -> bool {
ToggleFlag::False == *self || ToggleFlag::InternalVal(false) == *self
matches!(self, ToggleFlag::False | ToggleFlag::InternalVal(false))
}
pub fn is_true(&self) -> bool {
ToggleFlag::True == *self || ToggleFlag::InternalVal(true) == *self
matches!(self, ToggleFlag::True | ToggleFlag::InternalVal(true))
}
}

View File

@ -233,9 +233,7 @@ fn year_to_secs(year: i64, is_leap: &mut bool) -> std::result::Result<i64, ()> {
let cycles = (year - 100) / 400;
let centuries;
let mut leaps;
let mut rem;
rem = (year - 100) % 400;
let mut rem = (year - 100) % 400;
if rem == 0 {
*is_leap = true;

View File

@ -391,7 +391,7 @@ impl Envelope {
if let Some(x) = self.in_reply_to.clone() {
self.push_references(x);
}
if let Ok(d) = parser::dates::rfc5322_date(&self.date.as_bytes()) {
if let Ok(d) = parser::dates::rfc5322_date(self.date.as_bytes()) {
self.set_datetime(d);
}
if self.message_id.raw().is_empty() {

View File

@ -112,7 +112,7 @@ impl Address {
}
} else {
MailboxAddress {
raw: format!("{}", address).into_bytes(),
raw: address.to_string().into_bytes(),
display_name: StrBuilder {
offset: 0,
length: 0,
@ -262,7 +262,7 @@ impl Address {
let email = self.get_email();
let (local_part, domain) =
match super::parser::address::addr_spec_raw(email.as_bytes())
.map_err(|err| Into::<MeliError>::into(err))
.map_err(Into::<MeliError>::into)
.and_then(|(_, (l, d))| {
Ok((String::from_utf8(l.into())?, String::from_utf8(d.into())?))
}) {
@ -325,7 +325,7 @@ impl core::fmt::Display for Address {
match self {
Address::Mailbox(m) if m.display_name.length > 0 => {
match m.display_name.display(&m.raw) {
d if d.contains(".") || d.contains(",") => {
d if d.contains('.') || d.contains(',') => {
write!(f, "\"{}\" <{}>", d, m.address_spec.display(&m.raw))
}
d => write!(f, "{} <{}>", d, m.address_spec.display(&m.raw)),
@ -392,7 +392,7 @@ pub trait StrBuild {
}
impl StrBuilder {
pub fn display<'a>(&self, s: &'a [u8]) -> String {
pub fn display(&self, s: &[u8]) -> String {
let offset = self.offset;
let length = self.length;
String::from_utf8_lossy(&s[offset..offset + length]).to_string()

View File

@ -348,7 +348,7 @@ impl PartialEq<&str> for ContentType {
(ContentType::CMSSignature, "application/pkcs7-signature") => true,
(ContentType::MessageRfc822, "message/rfc822") => true,
(ContentType::Other { tag, .. }, _) => {
other.eq_ignore_ascii_case(&String::from_utf8_lossy(&tag))
other.eq_ignore_ascii_case(&String::from_utf8_lossy(tag))
}
(ContentType::OctetStream { .. }, "application/octet-stream") => true,
_ => false,
@ -372,22 +372,17 @@ impl Display for ContentType {
impl ContentType {
pub fn is_text(&self) -> bool {
if let ContentType::Text { .. } = self {
true
} else {
false
}
matches!(self, ContentType::Text { .. })
}
pub fn is_text_html(&self) -> bool {
if let ContentType::Text {
kind: Text::Html, ..
} = self
{
true
} else {
false
}
matches!(
self,
ContentType::Text {
kind: Text::Html,
..
}
)
}
pub fn make_boundary(parts: &[AttachmentBuilder]) -> String {
@ -453,11 +448,7 @@ pub enum Text {
impl Text {
pub fn is_html(&self) -> bool {
if let Text::Html = self {
true
} else {
false
}
matches!(self, Text::Html)
}
}
@ -537,11 +528,11 @@ pub enum ContentDispositionKind {
impl ContentDispositionKind {
pub fn is_inline(&self) -> bool {
*self == ContentDispositionKind::Inline
matches!(self, ContentDispositionKind::Inline)
}
pub fn is_attachment(&self) -> bool {
*self == ContentDispositionKind::Attachment
matches!(self, ContentDispositionKind::Attachment)
}
}

View File

@ -149,7 +149,7 @@ impl AttachmentBuilder {
}
}
if let Some(boundary) = boundary {
let parts = Self::parts(self.body(), &boundary);
let parts = Self::parts(self.body(), boundary);
let boundary = boundary.to_vec();
self.content_type = ContentType::Multipart {
@ -259,7 +259,7 @@ impl AttachmentBuilder {
let mut vec = Vec::with_capacity(attachments.len());
for a in attachments {
let mut builder = AttachmentBuilder::default();
let (headers, body) = match parser::attachments::attachment(&a) {
let (headers, body) = match parser::attachments::attachment(a) {
Ok((_, v)) => v,
Err(_) => {
debug!("error in parsing attachment");
@ -516,20 +516,19 @@ impl Attachment {
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(b"content-type"))
.and_then(|(_, v)| {
match parser::attachments::content_type(v) {
Ok((_, (ct, _cst, params))) => {
if ct.eq_ignore_ascii_case(b"multipart") {
let mut boundary = None;
for (n, v) in params {
if n.eq_ignore_ascii_case(b"boundary") {
boundary = Some(v);
break;
}
if let Ok((_, (ct, _cst, params))) =
parser::attachments::content_type(v)
{
if ct.eq_ignore_ascii_case(b"multipart") {
let mut boundary = None;
for (n, v) in params {
if n.eq_ignore_ascii_case(b"boundary") {
boundary = Some(v);
break;
}
return boundary;
}
return boundary;
}
_ => {}
}
None
})
@ -585,6 +584,7 @@ impl Attachment {
_ => {}
}
}
pub fn text(&self) -> String {
let mut text = Vec::with_capacity(self.body.length);
self.get_text_recursive(&mut text);
@ -594,6 +594,7 @@ impl Attachment {
pub fn mime_type(&self) -> String {
self.content_type.to_string()
}
pub fn attachments(&self) -> Vec<Attachment> {
let mut ret = Vec::new();
fn count_recursive(att: &Attachment, ret: &mut Vec<Attachment>) {
@ -612,24 +613,26 @@ impl Attachment {
}
}
count_recursive(&self, &mut ret);
count_recursive(self, &mut ret);
ret
}
pub fn count_attachments(&self) -> usize {
self.attachments().len()
}
pub fn content_type(&self) -> &ContentType {
&self.content_type
}
pub fn content_transfer_encoding(&self) -> &ContentTransferEncoding {
&self.content_transfer_encoding
}
pub fn is_text(&self) -> bool {
match self.content_type {
ContentType::Text { .. } => true,
_ => false,
}
matches!(self.content_type, ContentType::Text { .. })
}
pub fn is_html(&self) -> bool {
match self.content_type {
ContentType::Text {
@ -650,23 +653,23 @@ impl Attachment {
}
pub fn is_encrypted(&self) -> bool {
match self.content_type {
matches!(
self.content_type,
ContentType::Multipart {
kind: MultipartType::Encrypted,
..
} => true,
_ => false,
}
}
)
}
pub fn is_signed(&self) -> bool {
match self.content_type {
matches!(
self.content_type,
ContentType::Multipart {
kind: MultipartType::Signed,
..
} => true,
_ => false,
}
}
)
}
pub fn into_raw(&self) -> String {
@ -689,13 +692,13 @@ impl Attachment {
for (n, v) in parameters {
ret.push_str("; ");
ret.push_str(&String::from_utf8_lossy(n));
ret.push_str("=");
ret.push('=');
if v.contains(&b' ') {
ret.push_str("\"");
ret.push('"');
}
ret.push_str(&String::from_utf8_lossy(v));
if v.contains(&b' ') {
ret.push_str("\"");
ret.push('"');
}
}
@ -738,7 +741,7 @@ impl Attachment {
} else {
ret.push_str(&format!("Content-Type: {}\r\n\r\n", a.content_type));
}
ret.push_str(&BASE64_MIME.encode(a.body()).trim());
ret.push_str(BASE64_MIME.encode(a.body()).trim());
}
_ => {
ret.push_str(&format!("Content-Type: {}\r\n\r\n", a.content_type));
@ -758,11 +761,8 @@ impl Attachment {
};
for (name, value) in headers {
if name.eq_ignore_ascii_case(b"content-type") {
match parser::attachments::content_type(value) {
Ok((_, (_, _, params))) => {
ret = params;
}
_ => {}
if let Ok((_, (_, _, params))) = parser::attachments::content_type(value) {
ret = params;
}
break;
}
@ -794,7 +794,7 @@ impl Attachment {
.map(|(_, v)| v)
.ok()
.and_then(|n| String::from_utf8(n).ok())
.unwrap_or_else(|| s)
.unwrap_or(s)
})
.map(|n| n.replace(|c| std::path::is_separator(c) || c.is_ascii_control(), "_"))
}
@ -810,9 +810,9 @@ impl Attachment {
ContentType::CMSSignature | ContentType::PGPSignature => Vec::new(),
ContentType::MessageRfc822 => {
if self.content_disposition.kind.is_inline() {
let b = AttachmentBuilder::new(self.body()).build();
let ret = b.decode_rec_helper(options);
ret
AttachmentBuilder::new(self.body())
.build()
.decode_rec_helper(options)
} else {
b"message/rfc822 attachment".to_vec()
}

View File

@ -101,7 +101,7 @@ impl FromStr for Draft {
impl Draft {
pub fn edit(envelope: &Envelope, bytes: &[u8]) -> Result<Self> {
let mut ret = Draft::default();
for (k, v) in envelope.headers(&bytes).unwrap_or_else(|_| Vec::new()) {
for (k, v) in envelope.headers(bytes).unwrap_or_else(|_| Vec::new()) {
ret.headers.insert(k.try_into()?, v.into());
}
@ -257,7 +257,7 @@ impl Draft {
if let Some((pre, _)) = self.wrap_header_preamble.as_ref() {
if !pre.is_empty() {
ret.push_str(&pre);
ret.push_str(pre);
if !pre.ends_with('\n') {
ret.push('\n');
}
@ -273,7 +273,7 @@ impl Draft {
if !post.starts_with('\n') && !ret.ends_with('\n') {
ret.push('\n');
}
ret.push_str(&post);
ret.push_str(post);
ret.push('\n');
}
}
@ -324,11 +324,11 @@ impl Draft {
ret.push_str("\r\n");
}
} else if self.body.is_empty() && self.attachments.len() == 1 {
let attachment = std::mem::replace(&mut self.attachments, Vec::new()).remove(0);
let attachment = std::mem::take(&mut self.attachments).remove(0);
print_attachment(&mut ret, attachment);
} else {
let mut parts = Vec::with_capacity(self.attachments.len() + 1);
let attachments = std::mem::replace(&mut self.attachments, Vec::new());
let attachments = std::mem::take(&mut self.attachments);
if !self.body.is_empty() {
let mut body_attachment = AttachmentBuilder::default();
body_attachment.set_raw(self.body.as_bytes().to_vec());

View File

@ -49,7 +49,7 @@ pub struct ParsingError<I> {
impl core::fmt::Debug for ParsingError<&'_ [u8]> {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
fmt.debug_struct("ParsingError")
.field("input", &to_str!(&self.input))
.field("input", &to_str!(self.input))
.field("error", &self.error)
.finish()
}
@ -415,22 +415,22 @@ pub mod dates {
accum.extend_from_slice(&day_of_week);
accum.extend_from_slice(b", ");
}
accum.extend_from_slice(&day);
accum.extend_from_slice(day);
accum.extend_from_slice(b" ");
accum.extend_from_slice(&month);
accum.extend_from_slice(month);
accum.extend_from_slice(b" ");
accum.extend_from_slice(&year);
accum.extend_from_slice(year);
accum.extend_from_slice(b" ");
accum.extend_from_slice(&hour);
accum.extend_from_slice(hour);
accum.extend_from_slice(b":");
accum.extend_from_slice(&minute);
accum.extend_from_slice(minute);
if let Some(second) = second {
accum.extend_from_slice(b":");
accum.extend_from_slice(&second);
accum.extend_from_slice(second);
}
accum.extend_from_slice(b" ");
accum.extend_from_slice(&sign);
accum.extend_from_slice(&zone);
accum.extend_from_slice(sign);
accum.extend_from_slice(zone);
match crate::datetime::rfc822_to_timestamp(accum.to_vec()) {
Ok(t) => Ok((input, t)),
Err(_err) => Err(nom::Err::Error(
@ -472,23 +472,23 @@ pub mod dates {
let (input, year) = year(input)?;
accum.extend_from_slice(&day_of_week);
accum.extend_from_slice(b", ");
accum.extend_from_slice(&day);
accum.extend_from_slice(day);
accum.extend_from_slice(b" ");
accum.extend_from_slice(&month);
accum.extend_from_slice(month);
accum.extend_from_slice(b" ");
accum.extend_from_slice(&year);
accum.extend_from_slice(year);
accum.extend_from_slice(b" ");
accum.extend_from_slice(&hour);
accum.extend_from_slice(hour);
accum.extend_from_slice(b":");
accum.extend_from_slice(&minute);
accum.extend_from_slice(minute);
if let Some(second) = second {
accum.extend_from_slice(b":");
accum.extend_from_slice(&second);
accum.extend_from_slice(second);
}
if let Some((sign, zone)) = zone {
accum.extend_from_slice(b" ");
accum.extend_from_slice(&sign);
accum.extend_from_slice(&zone);
accum.extend_from_slice(sign);
accum.extend_from_slice(zone);
}
match crate::datetime::rfc822_to_timestamp(accum.to_vec()) {
Ok(t) => Ok((input, t)),
@ -571,7 +571,7 @@ pub mod dates {
Ok((rest, ret))
})
.or_else(|_| {
let (rest, ret) = match mbox_date_time(&input) {
let (rest, ret) = match mbox_date_time(input) {
Ok(v) => v,
Err(_) => {
return Err(nom::Err::Error(
@ -861,12 +861,12 @@ pub mod generic {
|input| {
let (input, pr) = many1(terminated(opt(fws), comment))(input)?;
let (input, end) = opt(fws)(input)?;
let mut pr = pr.into_iter().filter_map(|s| s).fold(vec![], |mut acc, x| {
let mut pr = pr.into_iter().flatten().fold(vec![], |mut acc, x| {
acc.extend_from_slice(&x);
acc
});
if pr.is_empty() {
Ok((input, end.unwrap_or((&b""[..]).into())))
Ok((input, end.unwrap_or_else(|| (&b""[..]).into())))
} else {
if let Some(end) = end {
pr.extend_from_slice(&end);
@ -1219,7 +1219,7 @@ pub mod generic {
{
Ok((&input[1..], input[0..1].into()))
} else {
return Err(nom::Err::Error((input, "atext(): invalid byte").into()));
Err(nom::Err::Error((input, "atext(): invalid byte").into()))
}
}
@ -1232,7 +1232,7 @@ pub mod generic {
let (input, _) = opt(cfws)(input)?;
let (input, ret) = dot_atom_text(input)?;
let (input, _) = opt(cfws)(input)?;
Ok((input, ret.into()))
Ok((input, ret))
}
///```text
@ -2064,7 +2064,7 @@ pub mod encodings {
input,
list.iter()
.fold(SmallVec::with_capacity(list_len), |mut acc, x| {
acc.extend(x.into_iter().cloned());
acc.extend(x.iter().cloned());
acc
}),
))
@ -2113,7 +2113,7 @@ pub mod encodings {
}
let end = input[ptr..].find(b"=?");
let end = end.unwrap_or_else(|| input.len() - ptr) + ptr;
let end = end.unwrap_or(input.len() - ptr) + ptr;
let ascii_s = ptr;
let mut ascii_e = 0;
@ -2378,7 +2378,7 @@ pub mod address {
///`name-addr = [display-name] angle-addr`
pub fn name_addr(input: &[u8]) -> IResult<&[u8], Address> {
let (input, (display_name, angle_addr)) = alt((
pair(map(display_name, |s| Some(s)), angle_addr),
pair(map(display_name, Some), angle_addr),
map(angle_addr, |r| (None, r)),
))(input)?;
Ok((
@ -2475,7 +2475,7 @@ pub mod address {
.trim(),
);
if i != list_len - 1 {
acc.push_str(" ");
acc.push(' ');
i += 1;
}
acc

File diff suppressed because it is too large Load Diff

View File

@ -111,7 +111,7 @@ impl Read for Data {
if result >= 0 {
Ok(result as usize)
} else {
Err(io::Error::last_os_error().into())
Err(io::Error::last_os_error())
}
}
}
@ -126,7 +126,7 @@ impl Write for Data {
if result >= 0 {
Ok(result as usize)
} else {
Err(io::Error::last_os_error().into())
Err(io::Error::last_os_error())
}
}
@ -149,7 +149,7 @@ impl Seek for Data {
if result >= 0 {
Ok(result as u64)
} else {
Err(io::Error::last_os_error().into())
Err(io::Error::last_os_error())
}
}
}

View File

@ -131,9 +131,9 @@ impl LocateKey {
s if s.eq_ignore_ascii_case("keyserver") => LocateKey::KEYSERVER,
s if s.eq_ignore_ascii_case("keyserver-url") => LocateKey::KEYSERVER_URL,
s if s.eq_ignore_ascii_case("local") => LocateKey::LOCAL,
combination if combination.contains(",") => {
combination if combination.contains(',') => {
let mut ret = LocateKey::NODEFAULT;
for c in combination.trim().split(",") {
for c in combination.trim().split(',') {
ret |= Self::from_string_de::<'de, D, &str>(c.trim())?;
}
ret
@ -157,7 +157,7 @@ impl std::fmt::Display for LocateKey {
($flag:expr, $string:literal) => {{
if self.intersects($flag) {
accum.push_str($string);
accum.push_str(",");
accum.push(',');
}
}};
}
@ -360,7 +360,7 @@ impl Context {
self.set_flag_inner(
auto_key_locate,
CStr::from_bytes_with_nul(accum.as_bytes())
.expect(accum.as_str())
.map_err(|err| format!("Expected `{}`: {}", accum.as_str(), err))?
.as_ptr() as *const _,
)
}
@ -372,7 +372,7 @@ impl Context {
unsafe { CStr::from_ptr(self.get_flag_inner(auto_key_locate)) }.to_string_lossy();
let mut val = LocateKey::NODEFAULT;
if !raw_value.contains("nodefault") {
for mechanism in raw_value.split(",") {
for mechanism in raw_value.split(',') {
match mechanism {
"cert" => val.set(LocateKey::CERT, true),
"pka" => {
@ -538,7 +538,7 @@ impl Context {
};
let _ = rcv.recv().await;
{
let verify_result =
let verify_result: gpgme_verify_result_t =
unsafe { call!(&ctx.lib, gpgme_op_verify_result)(ctx.inner.as_ptr()) };
if verify_result.is_null() {
return Err(MeliError::new(
@ -546,7 +546,7 @@ impl Context {
)
.set_err_kind(ErrorKind::External));
}
drop(verify_result);
unsafe { call!(&ctx.lib, gpgme_free)(verify_result as *mut ::libc::c_void) };
}
let io_state_lck = io_state.lock().unwrap();
let ret = io_state_lck
@ -792,7 +792,7 @@ impl Context {
.chain_err_summary(|| {
"libgpgme error: could not perform seek on signature data object"
})?;
Ok(sig.into_bytes()?)
sig.into_bytes()
})
}
@ -1118,7 +1118,7 @@ impl Context {
cipher
.seek(std::io::SeekFrom::Start(0))
.chain_err_summary(|| "libgpgme error: could not perform seek on plain text")?;
Ok(cipher.into_bytes()?)
cipher.into_bytes()
})
}
}

View File

@ -41,8 +41,8 @@ pub mod dbg {
() => {
eprint!(
"[{}][{:?}] {}:{}_{}: ",
crate::datetime::timestamp_to_string(
crate::datetime::now(),
$crate::datetime::timestamp_to_string(
$crate::datetime::now(),
Some("%Y-%m-%d %T"),
false
),
@ -340,7 +340,7 @@ pub mod shellexpand {
.components()
.last()
.map(|c| c.as_os_str())
.unwrap_or(OsStr::from_bytes(b""));
.unwrap_or_else(|| OsStr::from_bytes(b""));
let prefix = if let Some(p) = self.parent() {
p
} else {
@ -354,37 +354,33 @@ pub mod shellexpand {
}
if let Ok(iter) = std::fs::read_dir(&prefix) {
for entry in iter {
if let Ok(entry) = entry {
if entry.path().as_os_str().as_bytes() != b"."
&& entry.path().as_os_str().as_bytes() != b".."
&& entry
.path()
.as_os_str()
.as_bytes()
.starts_with(_match.as_bytes())
for entry in iter.flatten() {
if entry.path().as_os_str().as_bytes() != b"."
&& entry.path().as_os_str().as_bytes() != b".."
&& entry
.path()
.as_os_str()
.as_bytes()
.starts_with(_match.as_bytes())
{
if entry.path().is_dir()
&& !entry.path().as_os_str().as_bytes().ends_with(b"/")
{
if entry.path().is_dir()
&& !entry.path().as_os_str().as_bytes().ends_with(b"/")
{
let mut s = unsafe {
String::from_utf8_unchecked(
entry.path().as_os_str().as_bytes()
[_match.as_bytes().len()..]
.to_vec(),
)
};
s.push('/');
entries.push(s);
} else {
entries.push(unsafe {
String::from_utf8_unchecked(
entry.path().as_os_str().as_bytes()
[_match.as_bytes().len()..]
.to_vec(),
)
});
}
let mut s = unsafe {
String::from_utf8_unchecked(
entry.path().as_os_str().as_bytes()[_match.as_bytes().len()..]
.to_vec(),
)
};
s.push('/');
entries.push(s);
} else {
entries.push(unsafe {
String::from_utf8_unchecked(
entry.path().as_os_str().as_bytes()[_match.as_bytes().len()..]
.to_vec(),
)
});
}
}
}

View File

@ -423,10 +423,10 @@ impl SmtpConnection {
ref mut auth_type, ..
} = ret.server_conf.auth
{
for l in pre_auth_extensions_reply
if let Some(l) = pre_auth_extensions_reply
.lines
.iter()
.filter(|l| l.starts_with("AUTH"))
.find(|l| l.starts_with("AUTH"))
{
let l = l["AUTH ".len()..].trim();
for _type in l.split_whitespace() {
@ -436,7 +436,6 @@ impl SmtpConnection {
auth_type.login = true;
}
}
break;
}
}
}
@ -661,9 +660,9 @@ impl SmtpConnection {
//the client tries to send the same address again) or temporary (i.e., the address might
//be accepted if the client tries again later).
for addr in tos
.into_iter()
.chain(envelope.cc().into_iter())
.chain(envelope.bcc().into_iter())
.iter()
.chain(envelope.cc().iter())
.chain(envelope.bcc().iter())
{
current_command.clear();
current_command.push(b"RCPT TO:<");
@ -900,11 +899,26 @@ impl ReplyCode {
fn is_err(&self) -> bool {
use ReplyCode::*;
match self {
_421 | _450 | _451 | _452 | _455 | _500 | _501 | _502 | _503 | _504 | _535 | _550
| _551 | _552 | _553 | _554 | _555 | _530 => true,
_ => false,
}
matches!(
self,
_421 | _450
| _451
| _452
| _455
| _500
| _501
| _502
| _503
| _504
| _535
| _550
| _551
| _552
| _553
| _554
| _555
| _530
)
}
}

View File

@ -34,9 +34,9 @@ pub struct DatabaseDescription {
pub fn db_path(name: &str) -> Result<PathBuf> {
let data_dir =
xdg::BaseDirectories::with_prefix("meli").map_err(|e| MeliError::new(e.to_string()))?;
Ok(data_dir
data_dir
.place_data_file(name)
.map_err(|e| MeliError::new(e.to_string()))?)
.map_err(|err| MeliError::new(err.to_string()))
}
pub fn open_db(db_path: PathBuf) -> Result<Connection> {
@ -149,13 +149,13 @@ impl FromSql for Envelope {
let b: Vec<u8> = FromSql::column_result(value)?;
Ok(bincode::Options::deserialize(
bincode::Options::deserialize(
bincode::Options::with_limit(
bincode::config::DefaultOptions::new(),
2 * u64::try_from(b.len()).map_err(|e| FromSqlError::Other(Box::new(e)))?,
),
&b,
)
.map_err(|e| FromSqlError::Other(Box::new(e)))?)
.map_err(|e| FromSqlError::Other(Box::new(e)))
}
}

View File

@ -972,7 +972,8 @@ mod alg {
);
let x = minima[r - 1 + offset];
let mut for_was_broken = false;
for j in i..(r - 1) {
let i_copy = i;
for j in i_copy..(r - 1) {
let y = cost(j + offset, r - 1 + offset, width, &minima, &offsets);
if y <= x {
n -= j;
@ -1179,8 +1180,8 @@ fn reflow_helper(
let paragraph = paragraph
.trim_start_matches(&quotes)
.replace(&format!("\n{}", &quotes), "")
.replace("\n", "")
.replace("\r", "");
.replace('\n', "")
.replace('\r', "");
if in_paragraph {
if let Some(width) = width {
ret.extend(
@ -1195,7 +1196,7 @@ fn reflow_helper(
ret.push(format!("{}{}", &quotes, &paragraph));
}
} else {
let paragraph = paragraph.replace("\n", "").replace("\r", "");
let paragraph = paragraph.replace('\n', "").replace('\r', "");
if in_paragraph {
if let Some(width) = width {
@ -1573,7 +1574,7 @@ impl Iterator for LineBreakText {
);
self.paragraph = paragraph;
}
return self.paragraph.pop_front();
self.paragraph.pop_front()
}
ReflowState::AllWidth {
width,
@ -1746,7 +1747,7 @@ impl Iterator for LineBreakText {
*cur_index += line.len() + 2;
return Some(ret);
}
return None;
None
}
}
}
@ -1764,8 +1765,8 @@ fn reflow_helper2(
let paragraph = paragraph
.trim_start_matches(&quotes)
.replace(&format!("\n{}", &quotes), "")
.replace("\n", "")
.replace("\r", "");
.replace('\n', "")
.replace('\r', "");
if in_paragraph {
if let Some(width) = width {
ret.extend(
@ -1780,7 +1781,7 @@ fn reflow_helper2(
ret.push_back(format!("{}{}", &quotes, &paragraph));
}
} else {
let paragraph = paragraph.replace("\n", "").replace("\r", "");
let paragraph = paragraph.replace('\n', "").replace('\r', "");
if in_paragraph {
if let Some(width) = width {

View File

@ -77,10 +77,7 @@ impl Truncate for &str {
extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;
if let Some((first, _)) = UnicodeSegmentation::grapheme_indices(*self, true)
.skip(skip_len)
.next()
{
if let Some((first, _)) = UnicodeSegmentation::grapheme_indices(*self, true).nth(skip_len) {
&self[first..]
} else {
self
@ -95,10 +92,7 @@ impl Truncate for &str {
extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;
if let Some((first, _)) = UnicodeSegmentation::grapheme_indices(*self, true)
.skip(skip_len)
.next()
{
if let Some((first, _)) = UnicodeSegmentation::grapheme_indices(*self, true).nth(skip_len) {
*self = &self[first..];
}
}
@ -144,9 +138,8 @@ impl Truncate for String {
extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;
if let Some((first, _)) = UnicodeSegmentation::grapheme_indices(self.as_str(), true)
.skip(skip_len)
.next()
if let Some((first, _)) =
UnicodeSegmentation::grapheme_indices(self.as_str(), true).nth(skip_len)
{
&self[first..]
} else {
@ -162,9 +155,8 @@ impl Truncate for String {
extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;
if let Some((first, _)) = UnicodeSegmentation::grapheme_indices(self.as_str(), true)
.skip(skip_len)
.next()
if let Some((first, _)) =
UnicodeSegmentation::grapheme_indices(self.as_str(), true).nth(skip_len)
{
*self = self[first..].to_string();
}

View File

@ -19,6 +19,7 @@
* along with meli. If not, see <http://www.gnu.org/licenses/>.
*/
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum LineBreakClass {
BK,

View File

@ -385,15 +385,15 @@ impl SubjectPrefix for &str {
slice = &slice[4..];
continue;
}
if slice.starts_with(" ") || slice.starts_with("\t") || slice.starts_with("\r") {
if slice.starts_with(' ') || slice.starts_with('\t') || slice.starts_with('\r') {
//FIXME just trim whitespace
slice = &slice[1..];
continue;
}
if slice.starts_with("[")
if slice.starts_with('[')
&& !(slice.starts_with("[PATCH") || slice.starts_with("[RFC"))
{
if let Some(pos) = slice.find("]") {
if let Some(pos) = slice.find(']') {
slice = &slice[pos..];
continue;
}
@ -868,7 +868,6 @@ impl Threads {
{
let thread_hash = self.message_ids[message_id];
let node = self.thread_nodes.entry(thread_hash).or_default();
drop(message_id);
drop(envelopes_lck);
envelopes
.write()
@ -879,7 +878,7 @@ impl Threads {
/* If thread node currently has a message from a foreign mailbox and env_hash is
* from current mailbox we want to update it, otherwise return */
if !(node.other_mailbox && !other_mailbox) {
if !node.other_mailbox || other_mailbox {
return false;
}
}
@ -1223,18 +1222,18 @@ impl Threads {
let envelopes = envelopes.read().unwrap();
vec.sort_by(|a, b| match sort {
(SortField::Date, SortOrder::Desc) => {
let a = self.thread_ref(self.thread_nodes[&a].group).date();
let b = self.thread_ref(self.thread_nodes[&b].group).date();
let a = self.thread_ref(self.thread_nodes[a].group).date();
let b = self.thread_ref(self.thread_nodes[b].group).date();
b.cmp(&a)
}
(SortField::Date, SortOrder::Asc) => {
let a = self.thread_ref(self.thread_nodes[&a].group).date();
let b = self.thread_ref(self.thread_nodes[&b].group).date();
let a = self.thread_ref(self.thread_nodes[a].group).date();
let b = self.thread_ref(self.thread_nodes[b].group).date();
a.cmp(&b)
}
(SortField::Subject, SortOrder::Desc) => {
let a = &self.thread_nodes[&a].message();
let b = &self.thread_nodes[&b].message();
let a = &self.thread_nodes[a].message();
let b = &self.thread_nodes[b].message();
match (a, b) {
(Some(_), Some(_)) => {}
@ -1262,8 +1261,8 @@ impl Threads {
}
}
(SortField::Subject, SortOrder::Asc) => {
let a = &self.thread_nodes[&a].message();
let b = &self.thread_nodes[&b].message();
let a = &self.thread_nodes[a].message();
let b = &self.thread_nodes[b].message();
match (a, b) {
(Some(_), Some(_)) => {}
@ -1299,18 +1298,18 @@ impl Threads {
let envelopes = envelopes.read().unwrap();
tree.sort_by(|a, b| match sort {
(SortField::Date, SortOrder::Desc) => {
let a = self.thread_ref(self.thread_nodes[&a].group).date();
let b = self.thread_ref(self.thread_nodes[&b].group).date();
let a = self.thread_ref(self.thread_nodes[a].group).date();
let b = self.thread_ref(self.thread_nodes[b].group).date();
b.cmp(&a)
}
(SortField::Date, SortOrder::Asc) => {
let a = self.thread_ref(self.thread_nodes[&a].group).date();
let b = self.thread_ref(self.thread_nodes[&b].group).date();
let a = self.thread_ref(self.thread_nodes[a].group).date();
let b = self.thread_ref(self.thread_nodes[b].group).date();
a.cmp(&b)
}
(SortField::Subject, SortOrder::Desc) => {
let a = &self.thread_nodes[&a].message();
let b = &self.thread_nodes[&b].message();
let a = &self.thread_nodes[a].message();
let b = &self.thread_nodes[b].message();
match (a, b) {
(Some(_), Some(_)) => {}
@ -1338,8 +1337,8 @@ impl Threads {
}
}
(SortField::Subject, SortOrder::Asc) => {
let a = &self.thread_nodes[&a].message();
let b = &self.thread_nodes[&b].message();
let a = &self.thread_nodes[a].message();
let b = &self.thread_nodes[b].message();
match (a, b) {
(Some(_), Some(_)) => {}