1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::{Result, anyhow, bail};
30
31use ctb_formats_utf8::first_char_of_utf8_string;
32
33pub fn utf8_char_array_from_byte_array(bytes: &[u8]) -> Result<Vec<u32>> {
36 let mut out: Vec<u8> = Vec::new();
37 let mut i = 0;
38 while i < bytes.len() {
39 let slice = bytes.get(i..).ok_or_else(|| {
40 anyhow!(
41 "Index {i} out of bounds for byte slice of len {}",
42 bytes.len()
43 )
44 })?;
45 let (mut temp, consumed) = first_char_of_utf8_string(slice)?;
46 out.append(&mut temp);
47 i = i.saturating_add(consumed);
48 }
49 Ok(String::from_utf8(out)
50 .context("first_char_of_utf8_string should produce valid UTF-8")?
51 .chars()
52 .map(u32::from)
53 .collect())
54}
55
56pub fn byte_array_from_utf8_char_array(codepoints: &[u32]) -> Result<Vec<u8>> {
59 let mut out = Vec::new();
60 for &cp in codepoints {
61 if let Some(ch) = std::char::from_u32(cp) {
62 let mut buf = [0u8; 4];
63 let encoded = ch.encode_utf8(&mut buf);
64 out.extend_from_slice(encoded.as_bytes());
65 } else {
66 return Err(anyhow!("Invalid Unicode scalar value: {cp}"));
67 }
68 }
69 Ok(out)
70}
71
72pub fn unicode_scalar_from_utf8(bytes: &[u8]) -> Result<u32> {
73 let (codepoint, len) = first_utf8_codepoint(bytes)?;
74
75 if len > bytes.len() {
76 Err(anyhow!("This function is for a single character"))
77 } else {
78 Ok(codepoint)
79 }
80}
81
82pub fn first_utf8_codepoint(bytes: &[u8]) -> Result<(u32, usize)> {
84 if bytes.is_empty() {
85 return Ok((0, 0));
86 }
87 for end in 1..=bytes.len().min(4) {
89 let slice = bytes
90 .get(..end)
91 .ok_or_else(|| anyhow!("End index {end} out of bounds"))?;
92 if let Ok(s) = std::str::from_utf8(slice) {
93 if let Some(ch) = s.chars().next() {
94 return Ok((u32::from(ch), ch.len_utf8()));
95 }
96 }
97 }
98 bail!("Invalid UTF-8 sequence")
100}
101
102#[expect(
104 clippy::expect_used,
105 reason = "non-empty bytes check at function start guarantees len >= 1, so index len - 1 is in bounds"
106)]
107pub fn last_utf8_codepoint(bytes: &[u8]) -> (u32, usize) {
108 if bytes.is_empty() {
109 return (0, 0);
110 }
111 let len = bytes.len();
113 for start in (0.max(len.saturating_sub(4))..len).rev() {
114 if let Some(slice) = bytes.get(start..) {
115 if let Ok(s) = std::str::from_utf8(slice) {
116 if let Some(ch) = s.chars().next() {
117 return (u32::from(ch), ch.len_utf8());
118 }
119 }
120 }
121 }
122 let last_byte = *bytes
124 .get(len.saturating_sub(1))
125 .expect("non-empty bytes check guarantees len - 1 is in bounds");
126 (u32::from(last_byte), 1)
127}
128
129#[cfg(test)]
130#[allow(
131 clippy::panic,
132 clippy::expect_used,
133 clippy::unwrap_used,
134 clippy::unwrap_in_result,
135 clippy::panic_in_result_fn,
136 clippy::indexing_slicing,
137 clippy::arithmetic_side_effects,
138 reason = "Standard repository test boilerplate"
139)]
140mod tests {
141 use const_default::ConstDefault;
142
143 use crate::formats::utf8::UTF8FormatSettings;
144 use crate::formats::utf8::{dca_from_utf8, dca_to_utf8};
145 use crate::utilities::{assert_vec_u8_ok_eq, assert_vec_u32_ok_eq};
146 use ctb_formats_utilities::{
147 assert_vec_u8_ok_eq_no_warnings, assert_vec_u32_ok_eq_no_warnings,
148 };
149
150 use super::*;
151
152 const SETTINGS: UTF8FormatSettings =
153 <UTF8FormatSettings as ConstDefault>::DEFAULT;
154
155 #[crate::ctb_test]
156 fn test_utf8_char_array_conversion() {
157 let s = "hé🙂";
158 let bytes = s.as_bytes();
159 let cps = utf8_char_array_from_byte_array(bytes).expect("decode cps");
160 let re = byte_array_from_utf8_char_array(&cps).expect("encode bytes");
161 assert_eq!(re, bytes);
162 }
163
164 #[crate::ctb_test]
165 fn test_format_utf8_conversions() {
166 assert_vec_u32_ok_eq_no_warnings(
169 &[35, 18, 36],
170 dca_from_utf8(&[49, 32, 50], &SETTINGS),
171 );
172
173 assert_vec_u8_ok_eq_no_warnings(
175 &[49, 32, 50],
176 dca_to_utf8(&[35, 18, 36], &SETTINGS),
177 );
178 }
179
180 #[crate::ctb_test]
181 fn test_utf8_byte_array_conversions_work() {
182 let utf8_bytes = [
184 50, 53, 54, 32, 50, 53, 56, 32, 50, 54, 48, 32, 50, 54, 50, 32, 50,
185 54, 52, 32, 50, 54, 51, 32, 53, 55, 32, 56, 54, 32, 57, 51, 32, 57,
186 51, 32, 57, 54, 32, 51, 48, 32, 49, 56, 32, 50, 56, 54, 32, 55, 50,
187 32, 57, 54, 32, 57, 57, 32, 57, 51, 32, 56, 53, 32, 50, 56, 55, 32,
188 49, 57, 32, 49, 56, 32, 50, 56, 52, 32, 50, 54, 49, 32, 50, 53, 57,
189 32, 35, 32, 115, 97, 121, 32, 34, 72, 101, 108, 108, 111, 44, 32,
190 47, 87, 111, 114, 108, 100, 47, 33, 32, 226, 154, 189, 34, 10, 49,
191 32, 50, 32, 35, 32, 226, 154, 189, 10,
192 ];
193 let expected_codepoints = [
194 50, 53, 54, 32, 50, 53, 56, 32, 50, 54, 48, 32, 50, 54, 50, 32, 50,
195 54, 52, 32, 50, 54, 51, 32, 53, 55, 32, 56, 54, 32, 57, 51, 32, 57,
196 51, 32, 57, 54, 32, 51, 48, 32, 49, 56, 32, 50, 56, 54, 32, 55, 50,
197 32, 57, 54, 32, 57, 57, 32, 57, 51, 32, 56, 53, 32, 50, 56, 55, 32,
198 49, 57, 32, 49, 56, 32, 50, 56, 52, 32, 50, 54, 49, 32, 50, 53, 57,
199 32, 35, 32, 115, 97, 121, 32, 34, 72, 101, 108, 108, 111, 44, 32,
200 47, 87, 111, 114, 108, 100, 47, 33, 32, 9917, 34, 10, 49, 32, 50,
201 32, 35, 32, 9917, 10,
202 ];
203 assert_vec_u32_ok_eq(
204 &expected_codepoints,
205 utf8_char_array_from_byte_array(&utf8_bytes),
206 );
207
208 assert_vec_u8_ok_eq(
210 &utf8_bytes,
211 byte_array_from_utf8_char_array(&expected_codepoints),
212 );
213 }
214}