Fix some clippy warnings

This commit is contained in:
Alexander Krotov
2019-10-03 13:22:59 +03:00
committed by holger krekel
parent a5c4e16405
commit 130d485cac
27 changed files with 193 additions and 251 deletions

View File

@@ -88,8 +88,7 @@ impl Aheader {
.unwrap() .unwrap()
}; };
match Self::from_str(value) { if let Ok(test) = Self::from_str(value) {
Ok(test) => {
if addr_cmp(&test.addr, wanted_from) { if addr_cmp(&test.addr, wanted_from) {
if fine_header.is_none() { if fine_header.is_none() {
fine_header = Some(test); fine_header = Some(test);
@@ -99,8 +98,6 @@ impl Aheader {
} }
} }
} }
_ => {}
}
} }
} }
@@ -131,9 +128,9 @@ impl str::FromStr for Aheader {
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut attributes: BTreeMap<String, String> = s let mut attributes: BTreeMap<String, String> = s
.split(";") .split(';')
.filter_map(|a| { .filter_map(|a| {
let attribute: Vec<&str> = a.trim().splitn(2, "=").collect(); let attribute: Vec<&str> = a.trim().splitn(2, '=').collect();
if attribute.len() < 2 { if attribute.len() < 2 {
return None; return None;
} }
@@ -178,7 +175,7 @@ impl str::FromStr for Aheader {
// Autocrypt-Level0: unknown attributes starting with an underscore can be safely ignored // Autocrypt-Level0: unknown attributes starting with an underscore can be safely ignored
// Autocrypt-Level0: unknown attribute, treat the header as invalid // Autocrypt-Level0: unknown attribute, treat the header as invalid
if attributes.keys().find(|k| !k.starts_with("_")).is_some() { if attributes.keys().any(|k| !k.starts_with('_')) {
return Err(()); return Err(());
} }

View File

@@ -152,12 +152,10 @@ impl Chat {
return context.stock_str(StockMessage::DeadDrop).into(); return context.stock_str(StockMessage::DeadDrop).into();
} }
let cnt = get_chat_contact_cnt(context, self.id); let cnt = get_chat_contact_cnt(context, self.id);
return context return context.stock_string_repl_int(StockMessage::Member, cnt as i32);
.stock_string_repl_int(StockMessage::Member, cnt as i32)
.into();
} }
return "Err".into(); "Err".to_string()
} }
pub fn get_parent_mime_headers(&self, context: &Context) -> Option<(String, String, String)> { pub fn get_parent_mime_headers(&self, context: &Context) -> Option<(String, String, String)> {
@@ -799,12 +797,10 @@ pub fn send_msg(context: &Context, chat_id: u32, msg: &mut Message) -> Result<u3
if 0 == id { if 0 == id {
// avoid hanging if user tampers with db // avoid hanging if user tampers with db
break; break;
} else { } else if let Ok(mut copy) = Message::load_from_db(context, id as u32) {
if let Ok(mut copy) = Message::load_from_db(context, id as u32) {
send_msg(context, 0, &mut copy)?; send_msg(context, 0, &mut copy)?;
} }
} }
}
msg.param.remove(Param::PrepForwards); msg.param.remove(Param::PrepForwards);
msg.save_param_to_disk(context); msg.save_param_to_disk(context);
} }
@@ -1392,15 +1388,15 @@ pub(crate) fn add_contact_to_chat_ex(
} }
} else { } else {
// else continue and send status mail // else continue and send status mail
if chat.typ == Chattype::VerifiedGroup { if chat.typ == Chattype::VerifiedGroup
if contact.is_verified(context) != VerifiedStatus::BidirectVerified { && contact.is_verified(context) != VerifiedStatus::BidirectVerified
{
error!( error!(
context, context,
"Only bidirectional verified contacts can be added to verified groups." "Only bidirectional verified contacts can be added to verified groups."
); );
return Ok(false); return Ok(false);
} }
}
if !add_to_chat_contacts_table(context, chat_id, contact_id) { if !add_to_chat_contacts_table(context, chat_id, contact_id) {
return Ok(false); return Ok(false);
} }
@@ -1423,7 +1419,7 @@ pub(crate) fn add_contact_to_chat_ex(
}); });
} }
context.call_cb(Event::MsgsChanged { chat_id, msg_id: 0 }); context.call_cb(Event::MsgsChanged { chat_id, msg_id: 0 });
return Ok(true); Ok(true)
} }
fn real_group_exists(context: &Context, chat_id: u32) -> bool { fn real_group_exists(context: &Context, chat_id: u32) -> bool {
@@ -1591,7 +1587,7 @@ pub fn set_chat_name(
let mut msg = Message::default(); let mut msg = Message::default();
if real_group_exists(context, chat_id) { if real_group_exists(context, chat_id) {
if &chat.name == new_name.as_ref() { if chat.name == new_name.as_ref() {
success = true; success = true;
} else if !is_contact_in_chat(context, chat_id, 1) { } else if !is_contact_in_chat(context, chat_id, 1) {
emit_event!( emit_event!(
@@ -1723,7 +1719,7 @@ pub fn forward_msgs(context: &Context, msg_ids: &[u32], chat_id: u32) -> Result<
if let Ok(mut chat) = Chat::load_from_db(context, chat_id) { if let Ok(mut chat) = Chat::load_from_db(context, chat_id) {
curr_timestamp = dc_create_smeared_timestamps(context, msg_ids.len()); curr_timestamp = dc_create_smeared_timestamps(context, msg_ids.len());
let idsstr = msg_ids let idsstr = msg_ids
.into_iter() .iter()
.enumerate() .enumerate()
.fold(String::with_capacity(2 * msg_ids.len()), |acc, (i, n)| { .fold(String::with_capacity(2 * msg_ids.len()), |acc, (i, n)| {
(if i == 0 { acc } else { acc + "," }) + &n.to_string() (if i == 0 { acc } else { acc + "," }) + &n.to_string()
@@ -1760,7 +1756,7 @@ pub fn forward_msgs(context: &Context, msg_ids: &[u32], chat_id: u32) -> Result<
let new_msg_id: u32; let new_msg_id: u32;
if msg.state == MessageState::OutPreparing { if msg.state == MessageState::OutPreparing {
let fresh9 = curr_timestamp; let fresh9 = curr_timestamp;
curr_timestamp = curr_timestamp + 1; curr_timestamp += 1;
new_msg_id = chat new_msg_id = chat
.prepare_msg_raw(context, &mut msg, fresh9) .prepare_msg_raw(context, &mut msg, fresh9)
.unwrap_or_default(); .unwrap_or_default();
@@ -1780,7 +1776,7 @@ pub fn forward_msgs(context: &Context, msg_ids: &[u32], chat_id: u32) -> Result<
} else { } else {
msg.state = MessageState::OutPending; msg.state = MessageState::OutPending;
let fresh10 = curr_timestamp; let fresh10 = curr_timestamp;
curr_timestamp = curr_timestamp + 1; curr_timestamp += 1;
new_msg_id = chat new_msg_id = chat
.prepare_msg_raw(context, &mut msg, fresh10) .prepare_msg_raw(context, &mut msg, fresh10)
.unwrap_or_default(); .unwrap_or_default();

View File

@@ -258,13 +258,11 @@ impl Chatlist {
let chat_loaded: Chat; let chat_loaded: Chat;
let chat = if let Some(chat) = chat { let chat = if let Some(chat) = chat {
chat chat
} else { } else if let Ok(chat) = Chat::load_from_db(context, self.ids[index].0) {
if let Ok(chat) = Chat::load_from_db(context, self.ids[index].0) {
chat_loaded = chat; chat_loaded = chat;
&chat_loaded &chat_loaded
} else { } else {
return ret; return ret;
}
}; };
let lastmsg_id = self.ids[index].1; let lastmsg_id = self.ids[index].1;

View File

@@ -41,7 +41,7 @@ pub unsafe fn outlk_autodiscover(
let ok_to_continue; let ok_to_continue;
let mut i = 0; let mut i = 0;
loop { loop {
if !(i < 10) { if i >= 10 {
ok_to_continue = true; ok_to_continue = true;
break; break;
} }

View File

@@ -352,7 +352,7 @@ pub unsafe fn dc_job_do_DC_JOB_CONFIGURE_IMAP(context: &Context) {
ok_to_continue8 = true; ok_to_continue8 = true;
break; break;
} }
if !param_autoconfig.is_none() { if param_autoconfig.is_some() {
ok_to_continue8 = false; ok_to_continue8 = false;
break; break;
} }
@@ -423,7 +423,7 @@ pub unsafe fn dc_job_do_DC_JOB_CONFIGURE_IMAP(context: &Context) {
.unwrap() .unwrap()
.connect(context, &param) .connect(context, &param)
{ {
if !param_autoconfig.is_none() { if param_autoconfig.is_some() {
success = false; success = false;
} else if s.shall_stop_ongoing { } else if s.shall_stop_ongoing {
success = false; success = false;

View File

@@ -390,8 +390,7 @@ impl Contact {
} }
sth_modified = Modifier::Modified; sth_modified = Modifier::Modified;
} }
} else { } else if sql::execute(
if sql::execute(
context, context,
&context.sql, &context.sql,
"INSERT INTO contacts (name, addr, origin) VALUES(?, ?, ?);", "INSERT INTO contacts (name, addr, origin) VALUES(?, ?, ?);",
@@ -404,7 +403,6 @@ impl Contact {
} else { } else {
error!(context, "Cannot add contact."); error!(context, "Cannot add contact.");
} }
}
Ok((row_id, sth_modified)) Ok((row_id, sth_modified))
} }
@@ -827,7 +825,7 @@ impl Contact {
if let Ok(contact) = Contact::load_from_db(context, contact_id) { if let Ok(contact) = Contact::load_from_db(context, contact_id) {
if !contact.addr.is_empty() { if !contact.addr.is_empty() {
let normalized_addr = addr_normalize(addr.as_ref()); let normalized_addr = addr_normalize(addr.as_ref());
if &contact.addr == &normalized_addr { if contact.addr == normalized_addr {
return true; return true;
} }
} }
@@ -963,9 +961,9 @@ pub fn normalize_name(full_name: impl AsRef<str>) -> String {
if len > 0 { if len > 0 {
let firstchar = full_name.as_bytes()[0]; let firstchar = full_name.as_bytes()[0];
let lastchar = full_name.as_bytes()[len - 1]; let lastchar = full_name.as_bytes()[len - 1];
if firstchar == '\'' as u8 && lastchar == '\'' as u8 if firstchar == b'\'' && lastchar == b'\''
|| firstchar == '\"' as u8 && lastchar == '\"' as u8 || firstchar == b'\"' && lastchar == b'\"'
|| firstchar == '<' as u8 && lastchar == '>' as u8 || firstchar == b'<' && lastchar == b'>'
{ {
full_name = &full_name[1..len - 1]; full_name = &full_name[1..len - 1];
} }

View File

@@ -164,24 +164,20 @@ impl<'a> MimeParser<'a> {
} }
} }
} }
} else { } else if let Some(optional_field) = self.lookup_optional_field("Chat-Content") {
if let Some(optional_field) = self.lookup_optional_field("Chat-Content") {
if optional_field == "location-streaming-enabled" { if optional_field == "location-streaming-enabled" {
self.is_system_message = SystemMessage::LocationStreamingEnabled; self.is_system_message = SystemMessage::LocationStreamingEnabled;
} }
} }
}
if self.lookup_field("Chat-Group-Image").is_some() && !self.parts.is_empty() { if self.lookup_field("Chat-Group-Image").is_some() && !self.parts.is_empty() {
let textpart = &self.parts[0]; let textpart = &self.parts[0];
if textpart.typ == Viewtype::Text { if textpart.typ == Viewtype::Text && self.parts.len() >= 2 {
if self.parts.len() >= 2 {
let imgpart = &mut self.parts[1]; let imgpart = &mut self.parts[1];
if imgpart.typ == Viewtype::Image { if imgpart.typ == Viewtype::Image {
imgpart.is_meta = true; imgpart.is_meta = true;
} }
} }
} }
}
if self.is_send_by_messenger && self.parts.len() == 2 { if self.is_send_by_messenger && self.parts.len() == 2 {
let need_drop = { let need_drop = {
let textpart = &self.parts[0]; let textpart = &self.parts[0];
@@ -259,7 +255,7 @@ impl<'a> MimeParser<'a> {
} }
if self.parts[0].typ == Viewtype::Image { if self.parts[0].typ == Viewtype::Image {
if let Some(content_type) = self.lookup_optional_field("Chat-Content") { if let Some(content_type) = self.lookup_optional_field("Chat-Content") {
if content_type == "sticker".to_string() { if content_type == "sticker" {
let part_mut = &mut self.parts[0]; let part_mut = &mut self.parts[0];
part_mut.typ = Viewtype::Sticker; part_mut.typ = Viewtype::Sticker;
} }
@@ -866,13 +862,11 @@ impl<'a> MimeParser<'a> {
if !mb.is_null() { if !mb.is_null() {
let from_addr_norm = addr_normalize(as_str((*mb).mb_addr_spec)); let from_addr_norm = addr_normalize(as_str((*mb).mb_addr_spec));
let recipients = wrapmime::mailimf_get_recipients(self.header_root); let recipients = wrapmime::mailimf_get_recipients(self.header_root);
if recipients.len() == 1 { if recipients.len() == 1 && recipients.contains(from_addr_norm) {
if recipients.contains(from_addr_norm) {
sender_equals_recipient = true; sender_equals_recipient = true;
} }
} }
} }
}
sender_equals_recipient sender_equals_recipient
} }
@@ -996,8 +990,7 @@ unsafe fn mailmime_get_mime_type(mime: *mut Mailmime) -> (libc::c_int, Viewtype,
) == 0i32 ) == 0i32
{ {
return (DC_MIMETYPE_TEXT_PLAIN, Viewtype::Text, None); return (DC_MIMETYPE_TEXT_PLAIN, Viewtype::Text, None);
} else { } else if strcmp(
if strcmp(
(*c).ct_subtype, (*c).ct_subtype,
b"html\x00" as *const u8 as *const libc::c_char, b"html\x00" as *const u8 as *const libc::c_char,
) == 0i32 ) == 0i32
@@ -1005,7 +998,6 @@ unsafe fn mailmime_get_mime_type(mime: *mut Mailmime) -> (libc::c_int, Viewtype,
return (DC_MIMETYPE_TEXT_HTML, Viewtype::Text, None); return (DC_MIMETYPE_TEXT_HTML, Viewtype::Text, None);
} }
} }
}
let raw_mime = reconcat_mime(Some("text"), as_opt_str((*c).ct_subtype)); let raw_mime = reconcat_mime(Some("text"), as_opt_str((*c).ct_subtype));
(DC_MIMETYPE_FILE, Viewtype::File, Some(raw_mime)) (DC_MIMETYPE_FILE, Viewtype::File, Some(raw_mime))

View File

@@ -148,7 +148,7 @@ pub unsafe fn dc_receive_imf(
if mime_parser.sender_equals_recipient() { if mime_parser.sender_equals_recipient() {
from_id = DC_CONTACT_ID_SELF; from_id = DC_CONTACT_ID_SELF;
} }
} else if from_list.len() >= 1 { } else if !from_list.is_empty() {
// if there is no from given, from_id stays 0 which is just fine. These messages // if there is no from given, from_id stays 0 which is just fine. These messages
// are very rare, however, we have to add them to the database (they go to the // are very rare, however, we have to add them to the database (they go to the
// "deaddrop" chat) to avoid a re-download from the server. See also [**] // "deaddrop" chat) to avoid a re-download from the server. See also [**]
@@ -495,11 +495,13 @@ unsafe fn add_parts(
// if the chat_id is blocked, // if the chat_id is blocked,
// for unknown senders and non-delta messages set the state to NOTICED // for unknown senders and non-delta messages set the state to NOTICED
// to not result in a contact request (this would require the state FRESH) // to not result in a contact request (this would require the state FRESH)
if Blocked::Not != chat_id_blocked && state == MessageState::InFresh { if Blocked::Not != chat_id_blocked
if !incoming_origin.is_verified() && msgrmsg == 0 { && state == MessageState::InFresh
&& !incoming_origin.is_verified()
&& msgrmsg == 0
{
state = MessageState::InNoticed; state = MessageState::InNoticed;
} }
}
} else { } else {
// Outgoing // Outgoing
@@ -627,7 +629,7 @@ unsafe fn add_parts(
} }
if let Some(ref msg) = part.msg { if let Some(ref msg) = part.msg {
if !mime_parser.location_kml.is_none() if mime_parser.location_kml.is_some()
&& icnt == 1 && icnt == 1
&& (msg == "-location-" || msg.is_empty()) && (msg == "-location-" || msg.is_empty())
{ {
@@ -1479,7 +1481,7 @@ fn create_group_record(
sql::get_rowid(context, &context.sql, "chats", "grpid", grpid.as_ref()) sql::get_rowid(context, &context.sql, "chats", "grpid", grpid.as_ref())
} }
fn create_adhoc_grp_id(context: &Context, member_ids: &Vec<u32>) -> String { fn create_adhoc_grp_id(context: &Context, member_ids: &[u32]) -> String {
/* algorithm: /* algorithm:
- sort normalized, lowercased, e-mail addresses alphabetically - sort normalized, lowercased, e-mail addresses alphabetically
- put all e-mail addresses into a single string, separate the address by a single comma - put all e-mail addresses into a single string, separate the address by a single comma
@@ -1591,7 +1593,7 @@ fn check_verified_properties(
context: &Context, context: &Context,
mimeparser: &MimeParser, mimeparser: &MimeParser,
from_id: u32, from_id: u32,
to_ids: &Vec<u32>, to_ids: &[u32],
) -> Result<()> { ) -> Result<()> {
let contact = Contact::load_from_db(context, from_id)?; let contact = Contact::load_from_db(context, from_id)?;
@@ -1711,16 +1713,16 @@ unsafe fn dc_is_reply_to_known_message(context: &Context, mime_parser: &MimePars
if let Some(field) = mime_parser.lookup_field("References") { if let Some(field) = mime_parser.lookup_field("References") {
if (*field).fld_type == MAILIMF_FIELD_REFERENCES as libc::c_int { if (*field).fld_type == MAILIMF_FIELD_REFERENCES as libc::c_int {
let fld_references = (*field).fld_data.fld_references; let fld_references = (*field).fld_data.fld_references;
if !fld_references.is_null() { if !fld_references.is_null()
if is_known_rfc724_mid_in_list( && is_known_rfc724_mid_in_list(
context, context,
(*(*field).fld_data.fld_references).mid_list, (*(*field).fld_data.fld_references).mid_list,
) { )
{
return 1; return 1;
} }
} }
} }
}
0 0
} }
@@ -1731,12 +1733,12 @@ unsafe fn is_known_rfc724_mid_in_list(context: &Context, mid_list: *const clist)
} }
for data in &*mid_list { for data in &*mid_list {
if 0 != is_known_rfc724_mid(context, data.cast()) { if is_known_rfc724_mid(context, data.cast()) != 0 {
return true; return true;
} }
} }
return false; false
} }
/// Check if a message is a reply to a known message (messenger or non-messenger). /// Check if a message is a reply to a known message (messenger or non-messenger).
@@ -1961,10 +1963,8 @@ unsafe fn add_or_lookup_contact_by_addr(
let row_id = Contact::add_or_lookup(context, display_name_dec, as_str(addr_spec), origin) let row_id = Contact::add_or_lookup(context, display_name_dec, as_str(addr_spec), origin)
.map(|(id, _)| id) .map(|(id, _)| id)
.unwrap_or_default(); .unwrap_or_default();
if 0 != row_id { if 0 != row_id && !ids.contains(&row_id) {
if !ids.contains(&row_id) {
ids.push(row_id); ids.push(row_id);
}
}; };
} }

View File

@@ -10,18 +10,16 @@ pub struct Simplify {
/// ///
/// Also return whether not-standard (rfc3676, §4.3) footer is found. /// Also return whether not-standard (rfc3676, §4.3) footer is found.
fn find_message_footer(lines: &[&str]) -> (usize, bool) { fn find_message_footer(lines: &[&str]) -> (usize, bool) {
for ix in 0..lines.len() { for (ix, &line) in lines.iter().enumerate() {
let line = lines[ix];
// quoted-printable may encode `-- ` to `-- =20` which is converted // quoted-printable may encode `-- ` to `-- =20` which is converted
// back to `-- ` // back to `-- `
match line.as_ref() { match line {
"-- " | "-- " => return (ix, false), "-- " | "-- " => return (ix, false),
"--" | "---" | "----" => return (ix, true), "--" | "---" | "----" => return (ix, true),
_ => (), _ => (),
} }
} }
return (lines.len(), false); (lines.len(), false)
} }
impl Simplify { impl Simplify {
@@ -103,11 +101,9 @@ impl Simplify {
if let Some(last_quoted_line) = l_lastQuotedLine { if let Some(last_quoted_line) = l_lastQuotedLine {
l_last = last_quoted_line; l_last = last_quoted_line;
is_cut_at_end = true; is_cut_at_end = true;
if l_last > 1 { if l_last > 1 && is_empty_line(lines[l_last - 1]) {
if is_empty_line(lines[l_last - 1]) {
l_last -= 1 l_last -= 1
} }
}
if l_last > 1 { if l_last > 1 {
let line = lines[l_last - 1]; let line = lines[l_last - 1];
if is_quoted_headline(line) { if is_quoted_headline(line) {
@@ -205,7 +201,7 @@ fn is_quoted_headline(buf: &str) -> bool {
} }
fn is_plain_quote(buf: &str) -> bool { fn is_plain_quote(buf: &str) -> bool {
buf.starts_with(">") buf.starts_with('>')
} }
#[cfg(test)] #[cfg(test)]

View File

@@ -141,7 +141,7 @@ pub(crate) fn dc_truncate(buf: &str, approx_chars: usize, do_unwrap: bool) -> Co
.unwrap_or_default(); .unwrap_or_default();
if let Some(index) = buf[..end_pos].rfind(|c| c == ' ' || c == '\n') { if let Some(index) = buf[..end_pos].rfind(|c| c == ' ' || c == '\n') {
Cow::Owned(format!("{}{}", &buf[..index + 1], ellipse)) Cow::Owned(format!("{}{}", &buf[..=index], ellipse))
} else { } else {
Cow::Owned(format!("{}{}", &buf[..end_pos], ellipse)) Cow::Owned(format!("{}{}", &buf[..end_pos], ellipse))
} }
@@ -334,14 +334,14 @@ fn encode_66bits_as_base64(v1: u32, v2: u32, fill: u32) -> String {
enc.write_u8(((fill & 0x3) as u8) << 6).unwrap(); enc.write_u8(((fill & 0x3) as u8) << 6).unwrap();
enc.finish().unwrap(); enc.finish().unwrap();
} }
assert_eq!(wrapped_writer.pop(), Some('A' as u8)); // Remove last "A" assert_eq!(wrapped_writer.pop(), Some(b'A')); // Remove last "A"
String::from_utf8(wrapped_writer).unwrap() String::from_utf8(wrapped_writer).unwrap()
} }
pub(crate) fn dc_create_incoming_rfc724_mid( pub(crate) fn dc_create_incoming_rfc724_mid(
message_timestamp: i64, message_timestamp: i64,
contact_id_from: u32, contact_id_from: u32,
contact_ids_to: &Vec<u32>, contact_ids_to: &[u32],
) -> Option<String> { ) -> Option<String> {
if contact_ids_to.is_empty() { if contact_ids_to.is_empty() {
return None; return None;
@@ -423,10 +423,10 @@ fn get_safe_basename(filename: &str) -> String {
// this might be a path that comes in from another operating system // this might be a path that comes in from another operating system
let mut index: usize = 0; let mut index: usize = 0;
if let Some(unix_index) = filename.rfind("/") { if let Some(unix_index) = filename.rfind('/') {
index = unix_index + 1; index = unix_index + 1;
} }
if let Some(win_index) = filename.rfind("\\") { if let Some(win_index) = filename.rfind('\\') {
index = max(index, win_index + 1); index = max(index, win_index + 1);
} }
if index >= filename.len() { if index >= filename.len() {
@@ -439,7 +439,7 @@ fn get_safe_basename(filename: &str) -> String {
pub fn dc_derive_safe_stem_ext(filename: &str) -> (String, String) { pub fn dc_derive_safe_stem_ext(filename: &str) -> (String, String) {
let basename = get_safe_basename(&filename); let basename = get_safe_basename(&filename);
let (mut stem, mut ext) = if let Some(index) = basename.rfind(".") { let (mut stem, mut ext) = if let Some(index) = basename.rfind('.') {
( (
basename[0..index].to_string(), basename[0..index].to_string(),
basename[index..].to_string(), basename[index..].to_string(),

View File

@@ -532,7 +532,7 @@ fn decrypt_if_autocrypt_message(
// XXX better return parsed headers so that upstream // XXX better return parsed headers so that upstream
// does not need to dive into mmime-stuff again. // does not need to dive into mmime-stuff again.
unsafe { unsafe {
if (*ret_gossip_headers).is_null() && ret_valid_signatures.len() > 0 { if (*ret_gossip_headers).is_null() && !ret_valid_signatures.is_empty() {
let mut dummy: libc::size_t = 0; let mut dummy: libc::size_t = 0;
let mut test: *mut mailimf_fields = ptr::null_mut(); let mut test: *mut mailimf_fields = ptr::null_mut();
if mailimf_envelope_and_optional_fields_parse( if mailimf_envelope_and_optional_fields_parse(
@@ -685,12 +685,12 @@ fn contains_report(mime: *mut Mailmime) -> bool {
/// If this succeeds you are also guaranteed that the /// If this succeeds you are also guaranteed that the
/// [Config::ConfiguredAddr] is configured, this address is returned. /// [Config::ConfiguredAddr] is configured, this address is returned.
pub fn ensure_secret_key_exists(context: &Context) -> Result<String> { pub fn ensure_secret_key_exists(context: &Context) -> Result<String> {
let self_addr = context let self_addr = context.get_config(Config::ConfiguredAddr).ok_or_else(|| {
.get_config(Config::ConfiguredAddr) format_err!(concat!(
.ok_or(format_err!(concat!(
"Failed to get self address, ", "Failed to get self address, ",
"cannot ensure secret key if not configured." "cannot ensure secret key if not configured."
)))?; ))
})?;
load_or_generate_self_public_key(context, &self_addr)?; load_or_generate_self_public_key(context, &self_addr)?;
Ok(self_addr) Ok(self_addr)
} }

View File

@@ -331,7 +331,7 @@ struct ImapConfig {
impl Default for ImapConfig { impl Default for ImapConfig {
fn default() -> Self { fn default() -> Self {
let cfg = ImapConfig { ImapConfig {
addr: "".into(), addr: "".into(),
imap_server: "".into(), imap_server: "".into(),
imap_port: 0, imap_port: 0,
@@ -346,9 +346,7 @@ impl Default for ImapConfig {
has_xlist: false, has_xlist: false,
imap_delimiter: '.', imap_delimiter: '.',
watch_folder: None, watch_folder: None,
}; }
cfg
} }
} }
@@ -935,22 +933,14 @@ impl Imap {
let msg = &msgs[0]; let msg = &msgs[0];
// XXX put flags into a set and pass them to dc_receive_imf // XXX put flags into a set and pass them to dc_receive_imf
let is_deleted = msg let is_deleted = msg.flags().iter().any(|flag| match flag {
.flags()
.iter()
.find(|flag| match flag {
imap::types::Flag::Deleted => true, imap::types::Flag::Deleted => true,
_ => false, _ => false,
}) });
.is_some(); let is_seen = msg.flags().iter().any(|flag| match flag {
let is_seen = msg
.flags()
.iter()
.find(|flag| match flag {
imap::types::Flag::Seen => true, imap::types::Flag::Seen => true,
_ => false, _ => false,
}) });
.is_some();
let flags = if is_seen { DC_IMAP_SEEN } else { 0 }; let flags = if is_seen { DC_IMAP_SEEN } else { 0 };
@@ -1218,7 +1208,7 @@ impl Imap {
); );
} }
} }
return true; // we tried once, that's probably enough for setting flag true // we tried once, that's probably enough for setting flag
} else { } else {
unreachable!(); unreachable!();
} }
@@ -1300,7 +1290,7 @@ impl Imap {
let remote_message_id = let remote_message_id =
prefetch_get_message_id(msgs.first().unwrap()).unwrap_or_default(); prefetch_get_message_id(msgs.first().unwrap()).unwrap_or_default();
if remote_message_id != message_id.as_ref() { if remote_message_id != message_id {
warn!( warn!(
context, context,
"Cannot delete on IMAP, {}: remote message-id '{}' != '{}'", "Cannot delete on IMAP, {}: remote message-id '{}' != '{}'",

View File

@@ -474,7 +474,7 @@ fn import_backup(context: &Context, backup_to_import: impl AsRef<Path>) -> Resul
!dc_is_configured(context), !dc_is_configured(context),
"Cannot import backups to accounts in use." "Cannot import backups to accounts in use."
); );
&context.sql.close(&context); context.sql.close(&context);
dc_delete_file(context, context.get_dbfile()); dc_delete_file(context, context.get_dbfile());
ensure!( ensure!(
!dc_file_exist(context, context.get_dbfile()), !dc_file_exist(context, context.get_dbfile()),
@@ -511,9 +511,7 @@ fn import_backup(context: &Context, backup_to_import: impl AsRef<Path>) -> Resul
Ok((name, blob)) Ok((name, blob))
}, },
|files| { |files| {
let mut processed_files_cnt = 0; for (processed_files_cnt, file) in files.enumerate() {
for file in files {
let (file_name, file_blob) = file?; let (file_name, file_blob) = file?;
if context if context
.running_state .running_state
@@ -524,7 +522,6 @@ fn import_backup(context: &Context, backup_to_import: impl AsRef<Path>) -> Resul
{ {
bail!("received stop signal"); bail!("received stop signal");
} }
processed_files_cnt += 1;
let mut permille = processed_files_cnt * 1000 / total_files_cnt; let mut permille = processed_files_cnt * 1000 / total_files_cnt;
if permille < 10 { if permille < 10 {
permille = 10 permille = 10
@@ -804,7 +801,7 @@ fn import_self_keys(context: &Context, dir: impl AsRef<Path>) -> Result<()> {
"No private keys found in \"{}\".", "No private keys found in \"{}\".",
dir_name dir_name
); );
return Ok(()); Ok(())
} else { } else {
bail!("Import: Cannot open directory \"{}\".", dir_name); bail!("Import: Cannot open directory \"{}\".", dir_name);
} }

View File

@@ -142,7 +142,7 @@ impl Job {
if let Ok(body) = dc_read_file(context, filename) { if let Ok(body) = dc_read_file(context, filename) {
if let Some(recipients) = self.param.get(Param::Recipients) { if let Some(recipients) = self.param.get(Param::Recipients) {
let recipients_list = recipients let recipients_list = recipients
.split("\x1e") .split('\x1e')
.filter_map(|addr| match lettre::EmailAddress::new(addr.to_string()) { .filter_map(|addr| match lettre::EmailAddress::new(addr.to_string()) {
Ok(addr) => Some(addr), Ok(addr) => Some(addr),
Err(err) => { Err(err) => {
@@ -626,14 +626,14 @@ pub fn job_send_msg(context: &Context, msg_id: u32) -> Result<(), Error> {
mimefactory.msg.param.get_int(Param::GuranteeE2ee), mimefactory.msg.param.get_int(Param::GuranteeE2ee),
); );
} }
if context.get_config_bool(Config::BccSelf) { if context.get_config_bool(Config::BccSelf)
if !vec_contains_lowercase(&mimefactory.recipients_addr, &mimefactory.from_addr) { && !vec_contains_lowercase(&mimefactory.recipients_addr, &mimefactory.from_addr)
{
mimefactory.recipients_names.push("".to_string()); mimefactory.recipients_names.push("".to_string());
mimefactory mimefactory
.recipients_addr .recipients_addr
.push(mimefactory.from_addr.to_string()); .push(mimefactory.from_addr.to_string());
} }
}
if mimefactory.recipients_addr.is_empty() { if mimefactory.recipients_addr.is_empty() {
warn!( warn!(
@@ -764,13 +764,13 @@ fn job_perform(context: &Context, thread: Thread, probe_network: bool) {
// - they can be re-executed one time AT_ONCE, but they are not save in the database for later execution // - they can be re-executed one time AT_ONCE, but they are not save in the database for later execution
if Action::ConfigureImap == job.action || Action::ImexImap == job.action { if Action::ConfigureImap == job.action || Action::ImexImap == job.action {
job_kill_action(context, job.action); job_kill_action(context, job.action);
&context context
.sentbox_thread .sentbox_thread
.clone() .clone()
.read() .read()
.unwrap() .unwrap()
.suspend(context); .suspend(context);
&context context
.mvbox_thread .mvbox_thread
.clone() .clone()
.read() .read()
@@ -895,8 +895,7 @@ fn job_perform(context: &Context, thread: Thread, probe_network: bool) {
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn get_backoff_time_offset(c_tries: libc::c_int) -> i64 { fn get_backoff_time_offset(c_tries: libc::c_int) -> i64 {
// results in ~3 weeks for the last backoff timespan // results in ~3 weeks for the last backoff timespan
let mut N = 2_i32.pow((c_tries - 1) as u32); let N = 2_i32.pow((c_tries - 1) as u32) * 60;
N = N * 60;
let mut rng = thread_rng(); let mut rng = thread_rng();
let n: i32 = rng.gen(); let n: i32 = rng.gen();
let mut seconds = n % (N + 1); let mut seconds = n % (N + 1);

View File

@@ -218,10 +218,10 @@ impl Key {
let file_content = self.to_asc(None).into_bytes(); let file_content = self.to_asc(None).into_bytes();
if dc_write_file(context, &file, &file_content) { if dc_write_file(context, &file, &file_content) {
return true; true
} else { } else {
error!(context, "Cannot write key to {}", file.as_ref().display()); error!(context, "Cannot write key to {}", file.as_ref().display());
return false; false
} }
} }

View File

@@ -62,7 +62,7 @@ impl Kml {
pub fn parse(context: &Context, content: impl AsRef<str>) -> Result<Self, Error> { pub fn parse(context: &Context, content: impl AsRef<str>) -> Result<Self, Error> {
ensure!( ensure!(
content.as_ref().len() <= (1 * 1024 * 1024), content.as_ref().len() <= (1024 * 1024),
"A kml-files with {} bytes is larger than reasonably expected.", "A kml-files with {} bytes is larger than reasonably expected.",
content.as_ref().len() content.as_ref().len()
); );
@@ -359,7 +359,7 @@ pub fn get_range(
} }
fn is_marker(txt: &str) -> bool { fn is_marker(txt: &str) -> bool {
txt.len() == 1 && txt.chars().next().unwrap() != ' ' txt.len() == 1 && !txt.starts_with(' ')
} }
pub fn delete_all(context: &Context) -> Result<(), Error> { pub fn delete_all(context: &Context) -> Result<(), Error> {

View File

@@ -494,13 +494,11 @@ impl Lot {
} else { } else {
self.text1 = None; self.text1 = None;
} }
} else { } else if let Some(contact) = contact {
if let Some(contact) = contact {
self.text1 = Some(contact.get_first_name().into()); self.text1 = Some(contact.get_first_name().into());
} else { } else {
self.text1 = None; self.text1 = None;
} }
}
self.text1_meaning = Meaning::Text1Username; self.text1_meaning = Meaning::Text1Username;
} }
} }
@@ -618,9 +616,8 @@ pub fn get_msg_info(context: &Context, msg_id: u32) -> String {
} }
ret += "\n"; ret += "\n";
match msg.param.get(Param::Error) { if let Some(err) = msg.param.get(Param::Error) {
Some(err) => ret += &format!("Error: {}", err), ret += &format!("Error: {}", err)
_ => {}
} }
if let Some(path) = msg.get_file(context) { if let Some(path) = msg.get_file(context) {
@@ -688,7 +685,7 @@ pub fn get_mime_headers(context: &Context, msg_id: u32) -> Option<String> {
} }
pub fn delete_msgs(context: &Context, msg_ids: &[u32]) { pub fn delete_msgs(context: &Context, msg_ids: &[u32]) {
for msg_id in msg_ids.into_iter() { for msg_id in msg_ids.iter() {
update_msg_chat_id(context, *msg_id, DC_CHAT_ID_TRASH); update_msg_chat_id(context, *msg_id, DC_CHAT_ID_TRASH);
job_add( job_add(
context, context,
@@ -728,7 +725,7 @@ pub fn markseen_msgs(context: &Context, msg_ids: &[u32]) -> bool {
"SELECT m.state, c.blocked FROM msgs m LEFT JOIN chats c ON c.id=m.chat_id WHERE m.id=? AND m.chat_id>9", "SELECT m.state, c.blocked FROM msgs m LEFT JOIN chats c ON c.id=m.chat_id WHERE m.id=? AND m.chat_id>9",
|mut stmt, _| { |mut stmt, _| {
let mut res = Vec::with_capacity(msg_ids.len()); let mut res = Vec::with_capacity(msg_ids.len());
for id in msg_ids.into_iter() { for id in msg_ids.iter() {
let query_res = stmt.query_row(params![*id as i32], |row| { let query_res = stmt.query_row(params![*id as i32], |row| {
Ok((row.get::<_, MessageState>(0)?, row.get::<_, Option<Blocked>>(1)?.unwrap_or_default())) Ok((row.get::<_, MessageState>(0)?, row.get::<_, Option<Blocked>>(1)?.unwrap_or_default()))
}); });
@@ -798,7 +795,7 @@ pub fn star_msgs(context: &Context, msg_ids: &[u32], star: bool) -> bool {
context context
.sql .sql
.prepare("UPDATE msgs SET starred=? WHERE id=?;", |mut stmt, _| { .prepare("UPDATE msgs SET starred=? WHERE id=?;", |mut stmt, _| {
for msg_id in msg_ids.into_iter() { for msg_id in msg_ids.iter() {
stmt.execute(params![star as i32, *msg_id as i32])?; stmt.execute(params![star as i32, *msg_id as i32])?;
} }
Ok(()) Ok(())
@@ -837,7 +834,7 @@ pub fn get_summarytext_by_raw(
} else { } else {
None None
} }
.unwrap_or("ErrFileName".to_string()); .unwrap_or_else(|| "ErrFileName".to_string());
let label = context.stock_str(if viewtype == Viewtype::Audio { let label = context.stock_str(if viewtype == Viewtype::Audio {
StockMessage::Audio StockMessage::Audio

View File

@@ -382,15 +382,8 @@ impl<'a> MimeFactory<'a> {
&fingerprint, &fingerprint,
); );
} }
match msg.param.get(Param::Arg4) { if let Some(id) = msg.param.get(Param::Arg4) {
Some(id) => { wrapmime::new_custom_field(imf_fields, "Secure-Join-Group", &id);
wrapmime::new_custom_field(
imf_fields,
"Secure-Join-Group",
&id,
);
}
None => {}
}; };
} }
} }
@@ -640,17 +633,18 @@ impl<'a> MimeFactory<'a> {
let aheader = encrypt_helper.get_aheader().to_string(); let aheader = encrypt_helper.get_aheader().to_string();
wrapmime::new_custom_field(imffields_unprotected, "Autocrypt", &aheader); wrapmime::new_custom_field(imffields_unprotected, "Autocrypt", &aheader);
} }
let mut finalized = false; let finalized = if force_plaintext == 0 {
if force_plaintext == 0 { encrypt_helper.try_encrypt(
finalized = encrypt_helper.try_encrypt(
self, self,
e2ee_guaranteed, e2ee_guaranteed,
min_verified, min_verified,
do_gossip, do_gossip,
message, message,
imffields_unprotected, imffields_unprotected,
)?; )?
} } else {
false
};
if !finalized { if !finalized {
self.finalize_mime_message(message, false, false)?; self.finalize_mime_message(message, false, false)?;
} }
@@ -911,7 +905,7 @@ fn build_body_file(
} }
} }
pub(crate) fn vec_contains_lowercase(vec: &Vec<String>, part: &str) -> bool { pub(crate) fn vec_contains_lowercase(vec: &[String], part: &str) -> bool {
let partlc = part.to_lowercase(); let partlc = part.to_lowercase();
for cur in vec.iter() { for cur in vec.iter() {
if cur.to_lowercase() == partlc { if cur.to_lowercase() == partlc {

View File

@@ -207,14 +207,8 @@ pub fn dc_get_oauth2_addr(
addr: impl AsRef<str>, addr: impl AsRef<str>,
code: impl AsRef<str>, code: impl AsRef<str>,
) -> Option<String> { ) -> Option<String> {
let oauth2 = Oauth2::from_address(addr.as_ref()); let oauth2 = Oauth2::from_address(addr.as_ref())?;
if oauth2.is_none() { oauth2.get_userinfo?;
return None;
}
let oauth2 = oauth2.unwrap();
if oauth2.get_userinfo.is_none() {
return None;
}
if let Some(access_token) = if let Some(access_token) =
dc_get_oauth2_access_token(context, addr.as_ref(), code.as_ref(), false) dc_get_oauth2_access_token(context, addr.as_ref(), code.as_ref(), false)

View File

@@ -12,65 +12,65 @@ use crate::error;
#[repr(u8)] #[repr(u8)]
pub enum Param { pub enum Param {
/// For messages and jobs /// For messages and jobs
File = 'f' as u8, File = b'f',
/// For Messages /// For Messages
Width = 'w' as u8, Width = b'w',
/// For Messages /// For Messages
Height = 'h' as u8, Height = b'h',
/// For Messages /// For Messages
Duration = 'd' as u8, Duration = b'd',
/// For Messages /// For Messages
MimeType = 'm' as u8, MimeType = b'm',
/// For Messages: message is encryoted, outgoing: guarantee E2EE or the message is not send /// For Messages: message is encryoted, outgoing: guarantee E2EE or the message is not send
GuranteeE2ee = 'c' as u8, GuranteeE2ee = b'c',
/// For Messages: decrypted with validation errors or without mutual set, if neither /// For Messages: decrypted with validation errors or without mutual set, if neither
/// 'c' nor 'e' are preset, the messages is only transport encrypted. /// 'c' nor 'e' are preset, the messages is only transport encrypted.
ErroneousE2ee = 'e' as u8, ErroneousE2ee = b'e',
/// For Messages: force unencrypted message, either `ForcePlaintext::AddAutocryptHeader` (1), /// For Messages: force unencrypted message, either `ForcePlaintext::AddAutocryptHeader` (1),
/// `ForcePlaintext::NoAutocryptHeader` (2) or 0. /// `ForcePlaintext::NoAutocryptHeader` (2) or 0.
ForcePlaintext = 'u' as u8, ForcePlaintext = b'u',
/// For Messages /// For Messages
WantsMdn = 'r' as u8, WantsMdn = b'r',
/// For Messages /// For Messages
Forwarded = 'a' as u8, Forwarded = b'a',
/// For Messages /// For Messages
Cmd = 'S' as u8, Cmd = b'S',
/// For Messages /// For Messages
Arg = 'E' as u8, Arg = b'E',
/// For Messages /// For Messages
Arg2 = 'F' as u8, Arg2 = b'F',
/// For Messages /// For Messages
Arg3 = 'G' as u8, Arg3 = b'G',
/// For Messages /// For Messages
Arg4 = 'H' as u8, Arg4 = b'H',
/// For Messages /// For Messages
Error = 'L' as u8, Error = b'L',
/// For Messages: space-separated list of messaged IDs of forwarded copies. /// For Messages: space-separated list of messaged IDs of forwarded copies.
PrepForwards = 'P' as u8, PrepForwards = b'P',
/// For Jobs /// For Jobs
SetLatitude = 'l' as u8, SetLatitude = b'l',
/// For Jobs /// For Jobs
SetLongitude = 'n' as u8, SetLongitude = b'n',
/// For Jobs /// For Jobs
ServerFolder = 'Z' as u8, ServerFolder = b'Z',
/// For Jobs /// For Jobs
ServerUid = 'z' as u8, ServerUid = b'z',
/// For Jobs /// For Jobs
AlsoMove = 'M' as u8, AlsoMove = b'M',
/// For Jobs: space-separated list of message recipients /// For Jobs: space-separated list of message recipients
Recipients = 'R' as u8, Recipients = b'R',
// For Groups // For Groups
Unpromoted = 'U' as u8, Unpromoted = b'U',
// For Groups and Contacts // For Groups and Contacts
ProfileImage = 'i' as u8, ProfileImage = b'i',
// For Chats // For Chats
Selftalk = 'K' as u8, Selftalk = b'K',
// For QR // For QR
Auth = 's' as u8, Auth = b's',
// For QR // For QR
GroupId = 'x' as u8, GroupId = b'x',
// For QR // For QR
GroupName = 'g' as u8, GroupName = b'g',
} }
/// Possible values for `Param::ForcePlaintext`. /// Possible values for `Param::ForcePlaintext`.

View File

@@ -472,7 +472,7 @@ mod tests {
"failed to save to db" "failed to save to db"
); );
let peerstate_new = Peerstate::from_addr(&ctx.ctx, &ctx.ctx.sql, addr.into()) let peerstate_new = Peerstate::from_addr(&ctx.ctx, &ctx.ctx.sql, addr)
.expect("failed to load peerstate from db"); .expect("failed to load peerstate from db");
// clear to_save, as that is not persissted // clear to_save, as that is not persissted
@@ -555,7 +555,7 @@ mod tests {
"failed to save" "failed to save"
); );
let peerstate_new = Peerstate::from_addr(&ctx.ctx, &ctx.ctx.sql, addr.into()) let peerstate_new = Peerstate::from_addr(&ctx.ctx, &ctx.ctx.sql, addr)
.expect("failed to load peerstate from db"); .expect("failed to load peerstate from db");
// clear to_save, as that is not persissted // clear to_save, as that is not persissted

View File

@@ -43,7 +43,7 @@ pub unsafe fn dc_split_armored_data(
if !buf.is_null() { if !buf.is_null() {
dc_remove_cr_chars(buf); dc_remove_cr_chars(buf);
while 0 != *p1 { while 0 != *p1 {
if *p1 as libc::c_int == '\n' as i32 { if i32::from(*p1) == '\n' as i32 {
*line.offset(line_chars as isize) = 0i32 as libc::c_char; *line.offset(line_chars as isize) = 0i32 as libc::c_char;
if headerline.is_null() { if headerline.is_null() {
dc_trim(line); dc_trim(line);
@@ -69,7 +69,7 @@ pub unsafe fn dc_split_armored_data(
} else { } else {
p2 = strchr(line, ':' as i32); p2 = strchr(line, ':' as i32);
if p2.is_null() { if p2.is_null() {
*line.offset(line_chars as isize) = '\n' as i32 as libc::c_char; *line.add(line_chars) = '\n' as i32 as libc::c_char;
base64 = line; base64 = line;
break; break;
} else { } else {
@@ -189,7 +189,7 @@ pub fn dc_pgp_pk_encrypt(
let lit_msg = Message::new_literal_bytes("", plain); let lit_msg = Message::new_literal_bytes("", plain);
let pkeys: Vec<&SignedPublicKey> = public_keys_for_encryption let pkeys: Vec<&SignedPublicKey> = public_keys_for_encryption
.keys() .keys()
.into_iter() .iter()
.filter_map(|key| { .filter_map(|key| {
let k: &Key = &key; let k: &Key = &key;
k.try_into().ok() k.try_into().ok()

View File

@@ -696,7 +696,7 @@ fn encrypted_and_signed(mimeparser: &MimeParser, expected_fingerprint: impl AsRe
if !mimeparser.encrypted { if !mimeparser.encrypted {
warn!(mimeparser.context, "Message not encrypted.",); warn!(mimeparser.context, "Message not encrypted.",);
false false
} else if mimeparser.signatures.len() <= 0 { } else if mimeparser.signatures.is_empty() {
warn!(mimeparser.context, "Message not signed.",); warn!(mimeparser.context, "Message not signed.",);
false false
} else if expected_fingerprint.as_ref().is_empty() { } else if expected_fingerprint.as_ref().is_empty() {

View File

@@ -150,7 +150,7 @@ impl Smtp {
message_len, recipients_display message_len, recipients_display
))); )));
self.transport_connected = true; self.transport_connected = true;
return Ok(()); Ok(())
} }
Err(err) => { Err(err) => {
bail!("SMTP failed len={}: error: {}", message_len, err); bail!("SMTP failed len={}: error: {}", message_len, err);

View File

@@ -224,7 +224,7 @@ impl Sql {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(err) => { Err(err) => {
error!(context, "set_config(): Cannot change value. {:?}", &err); error!(context, "set_config(): Cannot change value. {:?}", &err);
Err(err.into()) Err(err)
} }
} }
} }
@@ -1148,12 +1148,8 @@ mod test {
maybe_add_file(&mut files, "$BLOBDIR/world.txt"); maybe_add_file(&mut files, "$BLOBDIR/world.txt");
maybe_add_file(&mut files, "world2.txt"); maybe_add_file(&mut files, "world2.txt");
assert!(is_file_in_use(&mut files, None, "hello")); assert!(is_file_in_use(&files, None, "hello"));
assert!(!is_file_in_use(&mut files, Some(".txt"), "hello")); assert!(!is_file_in_use(&files, Some(".txt"), "hello"));
assert!(is_file_in_use( assert!(is_file_in_use(&files, Some("-suffix"), "world.txt-suffix"));
&mut files,
Some("-suffix"),
"world.txt-suffix"
));
} }
} }

View File

@@ -351,9 +351,7 @@ mod tests {
let contact_id = { let contact_id = {
Contact::create(&t.ctx, "Alice", "alice@example.com") Contact::create(&t.ctx, "Alice", "alice@example.com")
.expect("Failed to create contact Alice"); .expect("Failed to create contact Alice");
let id = Contact::create(&t.ctx, "Bob", "bob@example.com").expect("failed to create bob")
Contact::create(&t.ctx, "Bob", "bob@example.com").expect("failed to create bob");
id
}; };
assert_eq!( assert_eq!(
t.ctx.stock_system_msg( t.ctx.stock_system_msg(

View File

@@ -329,7 +329,7 @@ pub fn decode_dt_data(
let decoded_data = unsafe { (*mime_data).dt_data.dt_text.dt_data }; let decoded_data = unsafe { (*mime_data).dt_data.dt_text.dt_data };
let decoded_data_bytes = unsafe { (*mime_data).dt_data.dt_text.dt_length }; let decoded_data_bytes = unsafe { (*mime_data).dt_data.dt_text.dt_length };
if decoded_data.is_null() || decoded_data_bytes <= 0 { if decoded_data.is_null() || decoded_data_bytes == 0 {
bail!("No data to decode found"); bail!("No data to decode found");
} else { } else {
let result = unsafe { let result = unsafe {