]> git.proxmox.com Git - rustc.git/blame - vendor/utf-8/tests/shared/string_from_utf8_lossy.rs
New upstream version 1.46.0+dfsg1
[rustc.git] / vendor / utf-8 / tests / shared / string_from_utf8_lossy.rs
CommitLineData
83c7162d
XL
1use std::borrow::Cow;
2use utf8::{decode, DecodeError, REPLACEMENT_CHARACTER};
3
4/// A re-implementation of String::from_utf8_lossy
5pub fn string_from_utf8_lossy(input: &[u8]) -> Cow<str> {
6 let mut result = decode(input);
7 if let Ok(s) = result {
8 return s.into()
9 }
10 let mut string = String::with_capacity(input.len() + REPLACEMENT_CHARACTER.len());
11 loop {
12 match result {
13 Ok(s) => {
14 string.push_str(s);
15 return string.into()
16 }
17 Err(DecodeError::Incomplete { valid_prefix, .. }) => {
18 string.push_str(valid_prefix);
19 string.push_str(REPLACEMENT_CHARACTER);
20 return string.into()
21 }
22 Err(DecodeError::Invalid { valid_prefix, remaining_input, .. }) => {
23 string.push_str(valid_prefix);
24 string.push_str(REPLACEMENT_CHARACTER);
25 result = decode(remaining_input);
26 }
27 }
28 }
29}