Lossily converts the string to UTF-8. Returns a UTF-8 `&str` slice if the contents are well-formed in UTF-8. Surrogates are replaced with `"\u{FFFD}"` (the replacement character “�”). This only copies the data if necessary (if it contains any surrogate).
(&self)
| 875 | /// |
| 876 | /// This only copies the data if necessary (if it contains any surrogate). |
| 877 | pub fn to_string_lossy(&self) -> Cow<'_, str> { |
| 878 | let Some((surrogate_pos, _)) = self.next_surrogate(0) else { |
| 879 | return Cow::Borrowed(unsafe { str::from_utf8_unchecked(&self.bytes) }); |
| 880 | }; |
| 881 | let wtf8_bytes = &self.bytes; |
| 882 | let mut utf8_bytes = Vec::with_capacity(self.len()); |
| 883 | utf8_bytes.extend_from_slice(&wtf8_bytes[..surrogate_pos]); |
| 884 | utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes()); |
| 885 | let mut pos = surrogate_pos + 3; |
| 886 | loop { |
| 887 | match self.next_surrogate(pos) { |
| 888 | Some((surrogate_pos, _)) => { |
| 889 | utf8_bytes.extend_from_slice(&wtf8_bytes[pos..surrogate_pos]); |
| 890 | utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes()); |
| 891 | pos = surrogate_pos + 3; |
| 892 | } |
| 893 | None => { |
| 894 | utf8_bytes.extend_from_slice(&wtf8_bytes[pos..]); |
| 895 | return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) }); |
| 896 | } |
| 897 | } |
| 898 | } |
| 899 | } |
| 900 | |
| 901 | /// Converts the WTF-8 string to potentially ill-formed UTF-16 |
| 902 | /// and return an iterator of 16-bit code units. |