From 8e659921312830b91d2a48aafa36fb1a49cba5bc Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Sun, 18 Oct 2020 15:14:32 +0200 Subject: [PATCH] impl: improve ByteVec::into_string_lossy It now re-uses to_str_lossy() (which is more efficient than looping over v.chars() like this did), and no longer allocates in the case where it was already valid utf-8. Closes #76 --- src/ext_vec.rs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/ext_vec.rs b/src/ext_vec.rs index 9792c38..6f6db56 100644 --- a/src/ext_vec.rs +++ b/src/ext_vec.rs @@ -425,15 +425,14 @@ pub trait ByteVec: Sealed { where Self: Sized, { - let v = self.as_vec(); - if let Ok(allutf8) = v.to_str() { - return allutf8.to_string(); - } - let mut dst = String::with_capacity(v.len()); - for ch in v.chars() { - dst.push(ch); + match self.as_vec().to_str_lossy() { + Cow::Borrowed(_) => { + // SAFETY: to_str_lossy() returning a Cow::Borrowed guarantees + // the entire string is valid utf8. + unsafe { self.into_string_unchecked() } + } + Cow::Owned(s) => s, } - dst } /// Unsafely convert this byte string into a `String`, without checking for