From 8354a954b2b0c25ee142475de88328cb8f49d270 Mon Sep 17 00:00:00 2001 From: "Neal H. Walfield" Date: Tue, 23 Jan 2024 16:11:43 +0100 Subject: openpgp: Avoid unnecessary heap allocations when creating UserIDs. - When creating a `UserID`, avoid unnecessary heap allocations by making better use of what we have. For example, we can directly convert a `String` to a `Vec` without allocating a `Vec`, and copying the contents. --- openpgp/src/packet/userid.rs | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) (limited to 'openpgp') diff --git a/openpgp/src/packet/userid.rs b/openpgp/src/packet/userid.rs index 0b8b0ae6..53613d4d 100644 --- a/openpgp/src/packet/userid.rs +++ b/openpgp/src/packet/userid.rs @@ -1,3 +1,4 @@ +use std::borrow::Cow; use std::fmt; use std::str; use std::hash::{Hash, Hasher}; @@ -498,26 +499,22 @@ impl From<&[u8]> for UserID { impl<'a> From<&'a str> for UserID { fn from(u: &'a str) -> Self { - let b = u.as_bytes(); - let mut v = Vec::with_capacity(b.len()); - v.extend_from_slice(b); - v.into() + u.as_bytes().into() } } impl From for UserID { fn from(u: String) -> Self { - let u = &u[..]; - u.into() + u.into_bytes().into() } } -impl<'a> From<::std::borrow::Cow<'a, str>> for UserID { - fn from(u: ::std::borrow::Cow<'a, str>) -> Self { - let b = u.as_bytes(); - let mut v = Vec::with_capacity(b.len()); - v.extend_from_slice(b); - v.into() +impl<'a> From> for UserID { + fn from(u: Cow<'a, str>) -> Self { + match u { + Cow::Owned(u) => u.into(), + Cow::Borrowed(u) => u.into(), + } } } -- cgit v1.2.3