Convert the Python string data to a Rust string. Returns a borrow into the original string data if possible. Data that isn't valid in its encoding will be replaced with U+FFFD REPLACEMENT CHARACTER.
(self)
| 211 | /// Data that isn't valid in its encoding will be replaced |
| 212 | /// with U+FFFD REPLACEMENT CHARACTER. |
| 213 | pub fn to_string_lossy(self) -> Cow<'a, str> { |
| 214 | match self { |
| 215 | PyStringData::Utf8(data) => String::from_utf8_lossy(data), |
| 216 | PyStringData::Latin1(data) => { |
| 217 | if data.is_ascii() { |
| 218 | Cow::Borrowed(unsafe { str::from_utf8_unchecked(data) }) |
| 219 | } else { |
| 220 | Cow::Owned(data.iter().map(|&b| b as char).collect()) |
| 221 | } |
| 222 | } |
| 223 | PyStringData::Utf16(data) => Cow::Owned(String::from_utf16_lossy(data)), |
| 224 | PyStringData::Utf32(data) => Cow::Owned( |
| 225 | data.iter() |
| 226 | .map(|&u| char::from_u32(u).unwrap_or('\u{FFFD}')) |
| 227 | .collect(), |
| 228 | ), |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | impl PyString { |