Skip to content

Commit 4919988

Browse files
committed
Auto merge of #91241 - dtolnay:firstchunk, r=oli-obk
Eliminate an unreachable codepath from String::from_utf8_lossy `Utf8Lossy`'s `Iterator` implementation ensures that only the **final** chunk has an empty slice for `broken`: https://github.com/rust-lang/rust/blob/dd549dcab404ec4c7d07b5a83aca5bdd7171138f/library/core/src/str/lossy.rs#L46-L47 Thus the only way the **first** chunk could have an empty `broken` is if it is the **final** chunk, i.e. there is only one chunk total. And the only way that there could be one chunk total with an empty `broken` is if the whole input is valid utf8 and non-empty. That condition has already been handled by an early return, so at the point that the first `REPLACEMENT` is being pushed, it's impossible for `first_broken` to be empty.
2 parents 686e313 + 9125dd7 commit 4919988

File tree

1 file changed

+5
-7
lines changed

1 file changed

+5
-7
lines changed

Diff for: library/alloc/src/string.rs

+5-7
Original file line numberDiff line numberDiff line change
@@ -558,13 +558,13 @@ impl String {
558558
pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> {
559559
let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks();
560560

561-
let (first_valid, first_broken) = if let Some(chunk) = iter.next() {
561+
let first_valid = if let Some(chunk) = iter.next() {
562562
let lossy::Utf8LossyChunk { valid, broken } = chunk;
563-
if valid.len() == v.len() {
564-
debug_assert!(broken.is_empty());
563+
if broken.is_empty() {
564+
debug_assert_eq!(valid.len(), v.len());
565565
return Cow::Borrowed(valid);
566566
}
567-
(valid, broken)
567+
valid
568568
} else {
569569
return Cow::Borrowed("");
570570
};
@@ -573,9 +573,7 @@ impl String {
573573

574574
let mut res = String::with_capacity(v.len());
575575
res.push_str(first_valid);
576-
if !first_broken.is_empty() {
577-
res.push_str(REPLACEMENT);
578-
}
576+
res.push_str(REPLACEMENT);
579577

580578
for lossy::Utf8LossyChunk { valid, broken } in iter {
581579
res.push_str(valid);

0 commit comments

Comments
 (0)