2 use crate::str as core_str;
3 use crate::fmt::{self, Write};
6 /// Lossy UTF-8 string.
7 #[unstable(feature = "str_internals", issue = "0")]
13 pub fn from_str(s: &str) -> &Utf8Lossy {
14 Utf8Lossy::from_bytes(s.as_bytes())
17 pub fn from_bytes(bytes: &[u8]) -> &Utf8Lossy {
18 unsafe { mem::transmute(bytes) }
21 pub fn chunks(&self) -> Utf8LossyChunksIter<'_> {
22 Utf8LossyChunksIter { source: &self.bytes }
27 /// Iterator over lossy UTF-8 string
28 #[unstable(feature = "str_internals", issue = "0")]
29 #[allow(missing_debug_implementations)]
30 pub struct Utf8LossyChunksIter<'a> {
34 #[unstable(feature = "str_internals", issue = "0")]
35 #[derive(PartialEq, Eq, Debug)]
36 pub struct Utf8LossyChunk<'a> {
37 /// Sequence of valid chars.
38 /// Can be empty between broken UTF-8 chars.
40 /// Single broken char, empty if none.
41 /// Empty iff iterator item is last.
45 impl<'a> Iterator for Utf8LossyChunksIter<'a> {
46 type Item = Utf8LossyChunk<'a>;
48 fn next(&mut self) -> Option<Utf8LossyChunk<'a>> {
49 if self.source.is_empty() {
53 const TAG_CONT_U8: u8 = 128;
54 fn safe_get(xs: &[u8], i: usize) -> u8 {
55 *xs.get(i).unwrap_or(&0)
59 while i < self.source.len() {
62 let byte = unsafe { *self.source.get_unchecked(i) };
68 let w = core_str::utf8_char_width(byte);
70 macro_rules! error { () => ({
72 let r = Utf8LossyChunk {
73 valid: core_str::from_utf8_unchecked(&self.source[0..i_]),
74 broken: &self.source[i_..i],
76 self.source = &self.source[i..];
83 if safe_get(self.source, i) & 192 != TAG_CONT_U8 {
89 match (byte, safe_get(self.source, i)) {
90 (0xE0, 0xA0 ..= 0xBF) => (),
91 (0xE1 ..= 0xEC, 0x80 ..= 0xBF) => (),
92 (0xED, 0x80 ..= 0x9F) => (),
93 (0xEE ..= 0xEF, 0x80 ..= 0xBF) => (),
99 if safe_get(self.source, i) & 192 != TAG_CONT_U8 {
105 match (byte, safe_get(self.source, i)) {
106 (0xF0, 0x90 ..= 0xBF) => (),
107 (0xF1 ..= 0xF3, 0x80 ..= 0xBF) => (),
108 (0xF4, 0x80 ..= 0x8F) => (),
114 if safe_get(self.source, i) & 192 != TAG_CONT_U8 {
118 if safe_get(self.source, i) & 192 != TAG_CONT_U8 {
130 let r = Utf8LossyChunk {
131 valid: unsafe { core_str::from_utf8_unchecked(self.source) },
140 impl fmt::Display for Utf8Lossy {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 // If we're the empty string then our iterator won't actually yield
143 // anything, so perform the formatting manually
144 if self.bytes.is_empty() {
148 for Utf8LossyChunk { valid, broken } in self.chunks() {
149 // If we successfully decoded the whole chunk as a valid string then
150 // we can return a direct formatting of the string which will also
151 // respect various formatting flags if possible.
152 if valid.len() == self.bytes.len() {
153 assert!(broken.is_empty());
158 if !broken.is_empty() {
159 f.write_char(char::REPLACEMENT_CHARACTER)?;
166 impl fmt::Debug for Utf8Lossy {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 for Utf8LossyChunk { valid, broken } in self.chunks() {
173 // Here we partially parse UTF-8 again which is suboptimal.
176 for (i, c) in valid.char_indices() {
177 let esc = c.escape_debug();
178 // If char needs escaping, flush backlog so far and write, else skip
180 f.write_str(&valid[from..i])?;
184 from = i + c.len_utf8();
187 f.write_str(&valid[from..])?;
190 // Broken parts of string as hex escape.
192 write!(f, "\\x{:02x}", b)?;