Skip to content

Commit

Permalink
impl: improve ByteVec::into_string_lossy
Browse files Browse the repository at this point in the history
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
  • Loading branch information
m-ou-se authored and BurntSushi committed Oct 18, 2020
1 parent 2122e1e commit 8e65992
Showing 1 changed file with 7 additions and 8 deletions.
15 changes: 7 additions & 8 deletions src/ext_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 8e65992

Please sign in to comment.