| 19 | |
| 20 | #[test] |
| 21 | fn test_to_utf8() { |
| 22 | let s = "Hé€lo, 世界!😀"; |
| 23 | let is_little_endian = false; |
| 24 | let utf16_bytes = s.encode_utf16().collect::<Vec<u16>>(); |
| 25 | println!("==========init utf16:"); |
| 26 | let utf16_strings: Vec<String> = utf16_bytes |
| 27 | .iter() |
| 28 | .map(|&byte| format!("0x{byte:04x}")) |
| 29 | .collect(); |
| 30 | println!("{}", utf16_strings.join(",")); |
| 31 | let utf8_bytes = to_utf8(&utf16_bytes, is_little_endian).unwrap(); |
| 32 | println!("==========utf8:"); |
| 33 | let utf8_strings: Vec<String> = utf8_bytes |
| 34 | .iter() |
| 35 | .map(|&byte| format!("0x{byte:02x}")) |
| 36 | .collect(); |
| 37 | println!("{}", utf8_strings.join(",")); |
| 38 | // final UTF-8 string |
| 39 | let final_string = String::from_utf8(utf8_bytes.clone()).unwrap(); |
| 40 | println!("final string: {final_string}"); |
| 41 | assert_eq!(s, final_string); |
| 42 | } |
| 43 | |
| 44 | // For test |
| 45 | fn swap_endian(value: u16) -> u16 { |