Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up String::from_utf16 #55530

Merged
merged 1 commit into from
Nov 15, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/liballoc/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,15 @@ impl String {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
let mut ret = String::with_capacity(v.len());
ljedrz marked this conversation as resolved.
Show resolved Hide resolved
for c in decode_utf16(v.iter().cloned()) {
if let Ok(c) = c {
ret.push(c);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to have a comment explaining why the code works this way instead of the more "obvious" collect call.

Basically, what you wrote in the PR should be in the code.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea; since it is already rolled up, I can add this comment afterwards, along with some other assorted code adjustments.

} else {
return Err(FromUtf16Error(()));
}
}
Ok(ret)
}

/// Decode a UTF-16 encoded slice `v` into a `String`, replacing
Expand Down