]>
Commit | Line | Data |
---|---|---|
83c7162d XL |
1 | use std::borrow::Cow; |
2 | use utf8::{decode, DecodeError, REPLACEMENT_CHARACTER}; | |
3 | ||
4 | /// A re-implementation of String::from_utf8_lossy | |
5 | pub 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 | } |