ctb_formats_encoding/
unicode.rs1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29pub fn utf8_to_utf32be(input: &[u8]) -> Result<Vec<u8>> {
30 let s = std::str::from_utf8(input).context("invalid UTF-8 sequence")?;
31 let mut result = Vec::with_capacity(s.len().saturating_mul(4));
32 for c in s.chars() {
33 result.extend_from_slice(&u32::from(c).to_be_bytes());
34 }
35 Ok(result)
36}
37
38pub fn utf32be_to_utf8(input: &[u8]) -> Result<Vec<u8>> {
39 if !input.len().is_multiple_of(4) {
40 bail!("input length must be a multiple of 4");
41 }
42 let mut result = Vec::with_capacity(input.len());
43 for chunk in input.chunks_exact(4) {
44 let bytes: [u8; 4] = chunk.try_into().context("invalid chunk size")?;
45 let code_point = u32::from_be_bytes(bytes);
46 let c =
47 char::from_u32(code_point).context("invalid unicode code point")?;
48 let mut buf = [0u8; 4];
49 let utf8_str = c.encode_utf8(&mut buf);
50 result.extend_from_slice(utf8_str.as_bytes());
51 }
52 Ok(result)
53}
54
55#[cfg(test)]
56#[allow(
57 clippy::panic,
58 clippy::expect_used,
59 clippy::unwrap_used,
60 clippy::unwrap_in_result,
61 clippy::panic_in_result_fn,
62 clippy::indexing_slicing,
63 clippy::arithmetic_side_effects,
64 reason = "Standard repository test boilerplate"
65)]
66mod tests {
67 use super::*;
68
69 #[crate::ctb_test]
70 fn test_utf_conversions() {
71 let original_str = "Hello, World! 🌄 ñ ü á";
72 let original_bytes = original_str.as_bytes();
73
74 let utf32 = utf8_to_utf32be(original_bytes).unwrap();
75 let decoded = utf32be_to_utf8(&utf32).unwrap();
76
77 assert_eq!(std::str::from_utf8(&decoded).unwrap(), original_str);
78
79 let spec_utf8 = "Ma\u{10000}".as_bytes();
81 let spec_expected_utf32 = [
82 0x00, 0x00, 0x00, 0x4D, 0x00, 0x00, 0x00, 0x61, 0x00, 0x01, 0x00, 0x00, ];
86 let spec_utf32 = utf8_to_utf32be(spec_utf8).unwrap();
87 assert_eq!(spec_utf32, spec_expected_utf32);
88
89 let spec_decoded = utf32be_to_utf8(&spec_expected_utf32).unwrap();
90 assert_eq!(spec_decoded, spec_utf8);
91
92 utf8_to_utf32be(&[0xff, 0xff]).unwrap_err();
94 utf32be_to_utf8(&[0, 0, 0]).unwrap_err();
95 utf32be_to_utf8(&[0xff, 0xff, 0xff, 0xff]).unwrap_err(); }
97}