Convert a string to ascii compatible, escaping unicode-s into escape sequences.
(value: &Wtf8)
| 431 | /// Convert a string to ascii compatible, escaping unicode-s into escape |
| 432 | /// sequences. |
| 433 | pub fn to_ascii(value: &Wtf8) -> AsciiString { |
| 434 | let mut ascii = Vec::new(); |
| 435 | for cp in value.code_points() { |
| 436 | if cp.is_ascii() { |
| 437 | ascii.push(cp.to_u32() as u8); |
| 438 | } else { |
| 439 | let c = cp.to_u32(); |
| 440 | let hex = if c < 0x100 { |
| 441 | format!("\\x{c:02x}") |
| 442 | } else if c < 0x10000 { |
| 443 | format!("\\u{c:04x}") |
| 444 | } else { |
| 445 | format!("\\U{c:08x}") |
| 446 | }; |
| 447 | ascii.append(&mut hex.into_bytes()); |
| 448 | } |
| 449 | } |
| 450 | unsafe { AsciiString::from_ascii_unchecked(ascii) } |
| 451 | } |
| 452 | |
| 453 | #[derive(Clone, Copy)] |
| 454 | pub struct UnicodeEscapeCodepoint(pub CodePoint); |
no test coverage detected