1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use anyhow::{Result, anyhow, bail};
30
31pub const UTF8_REPLACEMENT_CHARACTER: &[u8; 3] = &[0xEF, 0xBF, 0xBD];
32
33#[expect(
35 clippy::expect_used,
36 reason = "end is guaranteed to be a valid char boundary within s"
37)]
38pub fn truncate_to_max_bytes(s: &str, max_len: usize) -> String {
39 if s.len() <= max_len {
40 return s.to_owned();
41 }
42 let mut end = max_len;
44 while end > 0 && !s.is_char_boundary(end) {
45 end = end.saturating_sub(1);
46 }
47 s.get(..end)
48 .expect("end is a valid char boundary within s")
49 .to_owned()
50}
51
52pub fn ellipsize_to_max_bytes(s: &str, max_len: usize) -> String {
54 let start_len = s.len();
55 if start_len <= max_len {
56 return s.to_owned();
57 }
58 let max_len = max_len.saturating_sub(3); format!("{}...", truncate_to_max_bytes(s, max_len))
60}
61
62pub fn to_ascii_translit(input: &str) -> String {
65 deunicode::deunicode(input)
66}
67
68pub fn first_char_of_utf8_string(bytes: &[u8]) -> Result<(Vec<u8>, usize)> {
73 let (bytes, (consumed, _valid)) = _first_char_of_utf8_string(bytes, true)?;
74 Ok((bytes, consumed))
75}
76
77pub fn first_char_of_utf8_string_lossless(
80 bytes: &[u8],
81) -> Result<(Vec<u8>, (usize, bool))> {
82 _first_char_of_utf8_string(bytes, false)
83}
84
85fn _first_char_of_utf8_string(
86 bytes: &[u8],
87 replace_invalid: bool,
88) -> Result<(Vec<u8>, (usize, bool))> {
89 if bytes.is_empty() {
96 return Err(anyhow!("Empty input in first_char_of_utf8_string"));
97 }
98 let mut iter = bytes.utf8_chunks();
99 let chunk = iter.next().ok_or_else(|| {
100 anyhow!("At least some chunk should be found for non-empty string")
101 })?;
102
103 let valid = chunk.valid();
104 if valid.is_empty() {
105 let invalid = chunk.invalid();
106 if !invalid.is_empty() {
107 if replace_invalid {
108 return Ok((vec![0xEF, 0xBF, 0xBD], (invalid.len(), false)));
110 }
111 return Ok((invalid.to_vec(), (invalid.len(), false)));
112 }
113 bail!("Chunk contained neither valid nor invalid data");
114 }
115
116 let first_char = valid
117 .chars()
118 .next()
119 .context("Chunk contains no valid character")?;
120 let out = &mut [0u8; 4];
121 let first_char_len = first_char.encode_utf8(out).len();
122
123 let char_bytes = out
124 .get(..first_char_len)
125 .context("Invalid character length")?
126 .to_vec();
127 Ok((char_bytes, (first_char_len, true)))
128}
129
130pub fn utf8_from_scalar(cp: u32) -> Result<Vec<u8>> {
131 if cp > 0x10FFFF {
132 bail!("Invalid Unicode codepoint U+{cp:X}");
133 }
134 let mut buf = [0u8; 4];
135 let s = char::from_u32(cp)
136 .ok_or_else(|| anyhow!("Invalid Unicode codepoint U+{cp:X}"))?
137 .encode_utf8(&mut buf);
138 Ok(s.as_bytes().to_vec())
139}
140
141#[cfg(test)]
142#[allow(
143 clippy::panic,
144 clippy::expect_used,
145 clippy::unwrap_used,
146 clippy::unwrap_in_result,
147 clippy::panic_in_result_fn,
148 clippy::indexing_slicing,
149 clippy::arithmetic_side_effects,
150 reason = "Standard repository test boilerplate"
151)]
152mod tests {
153 use super::*;
154
155 #[crate::ctb_test]
156 fn test_truncate_to_max_bytes() {
157 assert_eq!(truncate_to_max_bytes("hello", 10), "hello");
158 assert_eq!(truncate_to_max_bytes("hello", 5), "hello");
159 assert_eq!(truncate_to_max_bytes("hello", 3), "hel");
160
161 let s = "日本語";
163 assert_eq!(truncate_to_max_bytes(s, 9), "日本語");
165 assert_eq!(truncate_to_max_bytes(s, 8), "日本");
166 assert_eq!(truncate_to_max_bytes(s, 7), "日本");
167 assert_eq!(truncate_to_max_bytes(s, 6), "日本");
168 assert_eq!(truncate_to_max_bytes(s, 3), "日");
169 assert_eq!(truncate_to_max_bytes(s, 2), "");
170 assert_eq!(truncate_to_max_bytes(s, 0), "");
171 }
172
173 #[crate::ctb_test]
174 fn test_first_char_of_utf8_string_ascii() {
175 let input = b"hello";
176 let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
177 assert_eq!(ch, vec![b'h']);
178 assert_eq!(consumed, 1);
179 }
180
181 #[crate::ctb_test]
182 fn test_first_char_of_utf8_string_multibyte() {
183 let input = "éclair".as_bytes();
184 let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
185 assert_eq!(ch, "é".as_bytes());
186 assert_eq!(consumed, "é".len());
187 }
188
189 #[crate::ctb_test]
190 fn test_first_char_of_utf8_string_astral() {
191 let input = "🥴test".as_bytes();
192 let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
193 assert_eq!(ch, "🥴".as_bytes());
194 assert_eq!(consumed, "🥴".len());
195 }
196
197 #[crate::ctb_test]
198 fn test_first_char_of_utf8_string_invalid() {
199 let input = &[0xFF, 0x61, 0x62];
200 let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
201 assert_eq!(ch, vec![0xEF, 0xBF, 0xBD]); assert_eq!(consumed, 1);
203 }
204
205 #[crate::ctb_test]
206 fn test_first_char_of_utf8_string_overlong() {
207 let input = &[0xC1, 0x81];
208 let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
209 assert_eq!(ch, vec![0xEF, 0xBF, 0xBD]); assert_eq!(consumed, 1);
211 }
212
213 #[crate::ctb_test]
214 fn test_first_char_of_utf8_string_partly_invalid() {
215 let input = &[0xE2, 0x80, 0xA9, 0xFF, 0x61, 0x62];
216 let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
217 assert_eq!(ch, vec![0xE2, 0x80, 0xA9]);
218 assert_eq!(consumed, 3);
219 }
220
221 #[crate::ctb_test]
222 fn test_first_char_of_utf8_string_empty() {
223 let input = b"";
224 let result = first_char_of_utf8_string(input);
225 result.unwrap_err();
226 }
227
228 #[crate::ctb_test]
229 fn test_first_char_of_utf8_string_only_invalid() {
230 let input = &[0xFF, 0xFE];
231 let (ch, consumed) = first_char_of_utf8_string(input).unwrap();
232 assert_eq!(ch, vec![0xEF, 0xBF, 0xBD]);
233 assert_eq!(consumed, 1);
234 }
235
236 #[crate::ctb_test]
237 fn test_first_char_of_utf8_string_lossless_valid() {
238 let input = &[0x61, 0x62];
239 let (ch, (consumed, valid)) =
240 first_char_of_utf8_string_lossless(input).unwrap();
241 assert_eq!(ch, vec![0x61]);
242 assert_eq!(consumed, 1);
243 assert!(valid);
244 }
245
246 #[crate::ctb_test]
247 fn test_first_char_of_utf8_string_lossless_multibyte() {
248 let input = "🥴test".as_bytes();
249 let (ch, (consumed, valid)) =
250 first_char_of_utf8_string_lossless(input).unwrap();
251 assert_eq!(ch, "🥴".as_bytes());
252 assert_eq!(consumed, "🥴".len());
253 assert!(valid);
254 }
255
256 #[crate::ctb_test]
257 fn test_first_char_of_utf8_string_lossless_invalid() {
258 let input = &[0xFF, 0x61, 0x62];
259 let (ch, (consumed, valid)) =
260 first_char_of_utf8_string_lossless(input).unwrap();
261 assert_eq!(ch, vec![0xFF]); assert_eq!(consumed, 1);
263 assert!(!valid);
264 }
265
266 #[crate::ctb_test]
267 fn test_first_char_of_utf8_string_lossless_only_invalid() {
268 let input = &[0xFF, 0xFE];
269 let (ch, (consumed, valid)) =
270 first_char_of_utf8_string_lossless(input).unwrap();
271 assert_eq!(ch, vec![0xFF]);
272 assert_eq!(consumed, 1);
273 assert!(!valid);
274 }
275}