Reduce number of AsRef generics

They result in compilation of duplicate code.
This commit is contained in:
link2xt
2021-12-31 13:57:45 +00:00
parent 4136217249
commit 30cb0cbcfd
14 changed files with 53 additions and 61 deletions

View File

@@ -1727,7 +1727,7 @@ pub unsafe extern "C" fn dc_lookup_contact_id_by_addr(
let ctx = &*context;
block_on(async move {
Contact::lookup_id_by_addr(ctx, to_string_lossy(addr), Origin::IncomingReplyTo)
Contact::lookup_id_by_addr(ctx, &to_string_lossy(addr), Origin::IncomingReplyTo)
.await
.unwrap_or_log_default(ctx, "failed to lookup id")
.unwrap_or(0)

View File

@@ -221,8 +221,8 @@ impl ChatId {
pub(crate) async fn create_multiuser_record(
context: &Context,
chattype: Chattype,
grpid: impl AsRef<str>,
grpname: impl AsRef<str>,
grpid: &str,
grpname: &str,
create_blocked: Blocked,
create_protected: ProtectionStatus,
param: Option<String>,
@@ -232,8 +232,8 @@ impl ChatId {
"INSERT INTO chats (type, name, grpid, blocked, created_timestamp, protected, param) VALUES(?, ?, ?, ?, ?, ?, ?);",
paramsv![
chattype,
grpname.as_ref(),
grpid.as_ref(),
grpname,
grpid,
create_blocked,
dc_create_smeared_timestamp(context).await,
create_protected,
@@ -244,10 +244,7 @@ impl ChatId {
let chat_id = ChatId::new(u32::try_from(row_id)?);
info!(
context,
"Created group/mailinglist '{}' grpid={} as {}",
grpname.as_ref(),
grpid.as_ref(),
chat_id
"Created group/mailinglist '{}' grpid={} as {}", grpname, grpid, chat_id
);
Ok(chat_id)
@@ -438,7 +435,7 @@ impl ChatId {
add_info_msg_with_cmd(
context,
self,
msg_text,
&msg_text,
cmd,
dc_create_smeared_timestamp(context).await,
)
@@ -2818,15 +2815,12 @@ async fn set_group_explicitly_left(context: &Context, grpid: &str) -> Result<()>
Ok(())
}
pub(crate) async fn is_group_explicitly_left(
context: &Context,
grpid: impl AsRef<str>,
) -> Result<bool> {
pub(crate) async fn is_group_explicitly_left(context: &Context, grpid: &str) -> Result<bool> {
let exists = context
.sql
.exists(
"SELECT COUNT(*) FROM leftgrps WHERE grpid=?;",
paramsv![grpid.as_ref()],
paramsv![grpid],
)
.await?;
Ok(exists)
@@ -3066,13 +3060,13 @@ pub(crate) async fn get_chat_cnt(context: &Context) -> Result<usize> {
/// Returns a tuple of `(chatid, is_protected, blocked)`.
pub(crate) async fn get_chat_id_by_grpid(
context: &Context,
grpid: impl AsRef<str>,
grpid: &str,
) -> Result<Option<(ChatId, bool, Blocked)>> {
context
.sql
.query_row_optional(
"SELECT id, blocked, protected FROM chats WHERE grpid=?;",
paramsv![grpid.as_ref()],
paramsv![grpid],
|row| {
let chat_id = row.get::<_, ChatId>(0)?;
@@ -3242,7 +3236,7 @@ pub(crate) async fn delete_and_reset_all_device_msgs(context: &Context) -> Resul
pub(crate) async fn add_info_msg_with_cmd(
context: &Context,
chat_id: ChatId,
text: impl AsRef<str>,
text: &str,
cmd: SystemMessage,
timestamp: i64,
) -> Result<MsgId> {
@@ -3264,7 +3258,7 @@ pub(crate) async fn add_info_msg_with_cmd(
timestamp,
Viewtype::Text,
MessageState::InNoticed,
text.as_ref().to_string(),
text,
rfc724_mid,
ephemeral_timer,
param.to_string(),
@@ -3280,7 +3274,7 @@ pub(crate) async fn add_info_msg_with_cmd(
pub(crate) async fn add_info_msg(
context: &Context,
chat_id: ChatId,
text: impl AsRef<str>,
text: &str,
timestamp: i64,
) -> Result<MsgId> {
add_info_msg_with_cmd(context, chat_id, text, SystemMessage::Unknown, timestamp).await

View File

@@ -311,17 +311,17 @@ impl Contact {
/// use `dc_may_be_valid_addr()`.
pub async fn lookup_id_by_addr(
context: &Context,
addr: impl AsRef<str>,
addr: &str,
min_origin: Origin,
) -> Result<Option<u32>> {
if addr.as_ref().is_empty() {
if addr.is_empty() {
bail!("lookup_id_by_addr: empty address");
}
let addr_normalized = addr_normalize(addr.as_ref());
let addr_normalized = addr_normalize(addr);
if let Some(addr_self) = context.get_config(Config::ConfiguredAddr).await? {
if addr_cmp(addr_normalized, addr_self) {
if addr_cmp(addr_normalized, &addr_self) {
return Ok(Some(DC_CONTACT_ID_SELF));
}
}
@@ -383,7 +383,7 @@ impl Contact {
.await?
.unwrap_or_default();
if addr_cmp(&addr, addr_self) {
if addr_cmp(&addr, &addr_self) {
return Ok((DC_CONTACT_ID_SELF, sth_modified));
}
@@ -582,7 +582,7 @@ impl Contact {
for (name, addr) in split_address_book(addr_book).into_iter() {
let (name, addr) = sanitize_name_and_addr(name, addr);
let name = normalize_name(name);
let name = normalize_name(&name);
match Contact::add_or_lookup(context, &name, &addr, Origin::AddressBook).await {
Err(err) => {
warn!(
@@ -1210,7 +1210,8 @@ WHERE type=? AND id IN (
// also unblock mailinglist
// if the contact is a mailinglist address explicitly created to allow unblocking
if !new_blocking && contact.origin == Origin::MailinglistAddress {
if let Some((chat_id, _, _)) = chat::get_chat_id_by_grpid(context, contact.addr).await?
if let Some((chat_id, _, _)) =
chat::get_chat_id_by_grpid(context, &contact.addr).await?
{
chat_id.unblock(context).await?;
}
@@ -1326,8 +1327,8 @@ pub(crate) async fn update_last_seen(
/// - Trims the resulting string
///
/// Typically, this function is not needed as it is called implicitly by `Contact::add_address_book`.
pub fn normalize_name(full_name: impl AsRef<str>) -> String {
let full_name = full_name.as_ref().trim();
pub fn normalize_name(full_name: &str) -> String {
let full_name = full_name.trim();
if full_name.is_empty() {
return full_name.into();
}
@@ -1371,16 +1372,16 @@ impl Context {
/// determine whether the specified addr maps to the/a self addr
pub async fn is_self_addr(&self, addr: &str) -> Result<bool> {
if let Some(self_addr) = self.get_config(Config::ConfiguredAddr).await? {
Ok(addr_cmp(self_addr, addr))
Ok(addr_cmp(&self_addr, addr))
} else {
Ok(false)
}
}
}
pub fn addr_cmp(addr1: impl AsRef<str>, addr2: impl AsRef<str>) -> bool {
let norm1 = addr_normalize(addr1.as_ref()).to_lowercase();
let norm2 = addr_normalize(addr2.as_ref()).to_lowercase();
pub fn addr_cmp(addr1: &str, addr2: &str) -> bool {
let norm1 = addr_normalize(addr1).to_lowercase();
let norm2 = addr_normalize(addr2).to_lowercase();
norm1 == norm2
}

View File

@@ -563,7 +563,7 @@ async fn add_parts(
let chat = Chat::load_from_db(context, chat_id).await?;
if chat.is_protected() {
let s = stock_str::unknown_sender_for_chat(context).await;
mime_parser.repl_msg_by_error(s);
mime_parser.repl_msg_by_error(&s);
} else if let Some(from) = mime_parser.from.first() {
// In non-protected chats, just mark the sender as overridden. Therefore, the UI will prepend `~`
// to the sender's name, indicating to the user that he/she is not part of the group.
@@ -943,7 +943,7 @@ async fn add_parts(
chat::add_info_msg(
context,
chat_id,
stock_ephemeral_timer_changed(context, ephemeral_timer, from_id).await,
&stock_ephemeral_timer_changed(context, ephemeral_timer, from_id).await,
sort_timestamp,
)
.await?;
@@ -986,7 +986,7 @@ async fn add_parts(
{
warn!(context, "verification problem: {}", err);
let s = format!("{}. See 'Info' for more details", err);
mime_parser.repl_msg_by_error(s);
mime_parser.repl_msg_by_error(&s);
} else {
// change chat protection only when verification check passes
if let Some(new_status) = new_status {
@@ -1002,7 +1002,7 @@ async fn add_parts(
chat::add_info_msg(
context,
chat_id,
format!("Cannot set protection: {}", e),
&format!("Cannot set protection: {}", e),
sort_timestamp,
)
.await?;
@@ -2300,7 +2300,7 @@ async fn dc_add_or_lookup_contacts_by_address_list(
/// Add contacts to database on receiving messages.
async fn add_or_lookup_contact_by_addr(
context: &Context,
display_name: Option<impl AsRef<str>>,
display_name: Option<&str>,
addr: &str,
origin: Origin,
) -> Result<u32> {

View File

@@ -36,9 +36,9 @@ impl Dehtml {
""
}
}
fn append_prefix(&self, line_end: impl AsRef<str>) -> String {
fn append_prefix(&self, line_end: &str) -> String {
// line_end is e.g. "\n\n". We add "> " if necessary.
line_end.as_ref().to_owned() + self.line_prefix()
line_end.to_string() + self.line_prefix()
}
fn get_add_text(&self) -> AddText {
if self.divs_since_quote_div > 0 && self.divs_since_quoted_content_div == 0 {

View File

@@ -1969,11 +1969,8 @@ async fn get_uidvalidity(context: &Context, folder: &str) -> Result<u32> {
}
/// Deprecated, use get_uid_next() and get_uidvalidity()
pub async fn get_config_last_seen_uid<S: AsRef<str>>(
context: &Context,
folder: S,
) -> Result<(u32, u32)> {
let key = format!("imap.mailbox.{}", folder.as_ref());
pub async fn get_config_last_seen_uid(context: &Context, folder: &str) -> Result<(u32, u32)> {
let key = format!("imap.mailbox.{}", folder);
if let Some(entry) = context.sql.get_raw_config(&key).await? {
// the entry has the format `imap.mailbox.<folder>=<uidvalidity>:<lastseenuid>`
let mut parts = entry.split(':');

View File

@@ -740,7 +740,7 @@ async fn add_all_recipients_as_contacts(context: &Context, imap: &mut Imap, fold
let display_name_normalized = contact
.display_name
.as_ref()
.map(normalize_name)
.map(|s| normalize_name(s))
.unwrap_or_default();
match Contact::add_or_lookup(

View File

@@ -223,7 +223,7 @@ pub async fn send_locations_to_chat(
.unwrap_or_default();
} else if 0 == seconds && is_sending_locations_before {
let stock_str = stock_str::msg_location_disabled(context).await;
chat::add_info_msg(context, chat_id, stock_str, now).await?;
chat::add_info_msg(context, chat_id, &stock_str, now).await?;
}
context.emit_event(EventType::ChatModified(chat_id));
if 0 != seconds {
@@ -747,7 +747,7 @@ pub(crate) async fn job_maybe_send_locations_ended(
);
let stock_str = stock_str::msg_location_disabled(context).await;
job_try!(chat::add_info_msg(context, chat_id, stock_str, now).await);
job_try!(chat::add_info_msg(context, chat_id, &stock_str, now).await);
context.emit_event(EventType::ChatModified(chat_id));
}
}

View File

@@ -1535,7 +1535,7 @@ async fn ndn_maybe_add_info_msg(
chat::add_info_msg(
context,
chat_id,
text,
&text,
dc_create_smeared_timestamp(context).await,
)
.await?;

View File

@@ -1101,11 +1101,11 @@ impl MimeMessage {
}
}
pub fn repl_msg_by_error(&mut self, error_msg: impl AsRef<str>) {
pub fn repl_msg_by_error(&mut self, error_msg: &str) {
self.is_system_message = SystemMessage::Unknown;
if let Some(part) = self.parts.first_mut() {
part.typ = Viewtype::Text;
part.msg = format!("[{}]", error_msg.as_ref());
part.msg = format!("[{}]", error_msg);
self.parts.truncate(1);
}
}

View File

@@ -277,7 +277,7 @@ impl Peerstate {
let msg = stock_str::contact_setup_changed(context, self.addr.clone()).await;
chat::add_info_msg(context, chat_id, msg, timestamp).await?;
chat::add_info_msg(context, chat_id, &msg, timestamp).await?;
context.emit_event(EventType::ChatModified(chat_id));
} else {
bail!("contact with peerstate.addr {:?} not found", &self.addr);

View File

@@ -282,7 +282,7 @@ async fn decode_openpgp(context: &Context, qr: &str) -> Result<Qr> {
chat::add_info_msg(
context,
chat.id,
format!("{} verified.", peerstate.addr),
&format!("{} verified.", peerstate.addr),
time(),
)
.await?;
@@ -424,7 +424,7 @@ pub async fn set_config_from_qr(context: &Context, qr: &str) -> Result<()> {
grpid,
..
} => {
let chat_id = get_chat_id_by_grpid(context, grpid)
let chat_id = get_chat_id_by_grpid(context, &grpid)
.await?
.map(|(chat_id, _protected, _blocked)| chat_id);
token::save(

View File

@@ -322,8 +322,8 @@ async fn securejoin(context: &Context, qr: &str) -> Result<ChatId, JoinError> {
ChatId::create_multiuser_record(
context,
Chattype::Group,
group_id,
group_name,
&group_id,
&group_name,
Blocked::Not,
ProtectionStatus::Unprotected, // protection is added later as needed
None,
@@ -334,7 +334,7 @@ async fn securejoin(context: &Context, qr: &str) -> Result<ChatId, JoinError> {
chat::add_to_chat_contacts_table(context, chat_id, contact_id).await?;
}
let msg = stock_str::secure_join_started(context, contact_id).await;
chat::add_info_msg(context, chat_id, msg, time()).await?;
chat::add_info_msg(context, chat_id, &msg, time()).await?;
Ok(chat_id)
}
}
@@ -541,7 +541,7 @@ pub(crate) async fn handle_securejoin_handshake(
chat::add_info_msg(
context,
bobstate.chat_id(context).await?,
msg,
&msg,
time(),
)
.await?;
@@ -742,7 +742,7 @@ pub(crate) async fn handle_securejoin_handshake(
.get_header(HeaderDef::SecureJoinGroup)
.map(|s| s.as_str())
.unwrap_or_else(|| "");
if let Err(err) = chat::get_chat_id_by_grpid(context, &field_grpid).await {
if let Err(err) = chat::get_chat_id_by_grpid(context, field_grpid).await {
warn!(context, "Failed to lookup chat_id from grpid: {}", err);
return Err(
err.context(format!("Chat for group {} not found", &field_grpid))
@@ -852,7 +852,7 @@ async fn secure_connection_established(
) -> Result<(), Error> {
let contact = Contact::get_by_id(context, contact_id).await?;
let msg = stock_str::contact_verified(context, contact.get_name_n_addr()).await;
chat::add_info_msg(context, chat_id, msg, time()).await?;
chat::add_info_msg(context, chat_id, &msg, time()).await?;
context.emit_event(EventType::ChatModified(chat_id));
Ok(())
}

View File

@@ -71,7 +71,7 @@ impl<'a> BobStateHandle<'a> {
pub async fn chat_id(&self, context: &Context) -> Result<ChatId> {
match self.bobstate.invite {
QrInvite::Group { ref grpid, .. } => {
if let Some((chat_id, _, _)) = chat::get_chat_id_by_grpid(context, &grpid).await? {
if let Some((chat_id, _, _)) = chat::get_chat_id_by_grpid(context, grpid).await? {
Ok(chat_id)
} else {
bail!("chat not found")