Skip to content

Commit 8e65992

Browse files
m-ou-seBurntSushi
authored andcommitted
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
1 parent 2122e1e commit 8e65992

File tree

1 file changed

+7
-8
lines changed

1 file changed

+7
-8
lines changed

src/ext_vec.rs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -425,15 +425,14 @@ pub trait ByteVec: Sealed {
425425
where
426426
Self: Sized,
427427
{
428-
let v = self.as_vec();
429-
if let Ok(allutf8) = v.to_str() {
430-
return allutf8.to_string();
431-
}
432-
let mut dst = String::with_capacity(v.len());
433-
for ch in v.chars() {
434-
dst.push(ch);
428+
match self.as_vec().to_str_lossy() {
429+
Cow::Borrowed(_) => {
430+
// SAFETY: to_str_lossy() returning a Cow::Borrowed guarantees
431+
// the entire string is valid utf8.
432+
unsafe { self.into_string_unchecked() }
433+
}
434+
Cow::Owned(s) => s,
435435
}
436-
dst
437436
}
438437

439438
/// Unsafely convert this byte string into a `String`, without checking for

0 commit comments

Comments
 (0)