1#[allow(
60 unused_imports,
61 clippy::wildcard_imports,
62 reason = "Standard workspace crate prelude"
63)]
64pub(crate) use ctb_utilities::*;
65
66use anyhow::{Context, Result, ensure};
67use ctb_utilities::circular_dep_unicode::{
68 ucs2decode, ucs2encode, unpaired_surrogates_to_scalars,
69};
70
71pub fn encode_wtf8_single(int_value: u32) -> Result<Vec<u8>> {
76 ensure!(
77 int_value <= 0x10FFFF,
78 format!("WTF-8: Codepoint {int_value} out of range")
79 );
80 fn create_byte(int_value: u32, shift: u32) -> Result<u8> {
81 u8::try_from(((int_value >> shift) & 0x3F) | 0x80)
82 .context("Failed to create byte")
83 }
84
85 let mut symbol = Vec::new();
86 if (int_value & 0xFFFFFF80) == 0 {
87 symbol.push(u8::try_from(int_value).context("Failed to create byte")?);
89 } else {
90 if (int_value & 0xFFFFF800) == 0 {
91 symbol.push(
93 u8::try_from((int_value >> 6) & 0x1F | 0xC0)
94 .context("Failed to create byte")?,
95 );
96 } else if (int_value & 0xFFFF0000) == 0 {
97 symbol.push(
99 u8::try_from((int_value >> 12) & 0x0F | 0xE0)
100 .context("Failed to create byte")?,
101 );
102 symbol.push(create_byte(int_value, 6)?);
103 } else if (int_value & 0xFFE00000) == 0 {
104 symbol.push(
106 u8::try_from((int_value >> 18) & 0x07 | 0xF0)
107 .context("Failed to create byte")?,
108 );
109 symbol.push(create_byte(int_value, 12)?);
110 symbol.push(create_byte(int_value, 6)?);
111 }
112 symbol.push(
113 u8::try_from((int_value & 0x3F) | 0x80)
114 .context("Failed to create byte")?,
115 );
116 }
117 Ok(symbol)
118}
119
120pub fn encode_wtf8_from_scalars(codepoints: &[u32]) -> Result<Vec<u8>> {
126 let mut out = Vec::new();
127 let mut i = 0;
128 while i < codepoints.len() {
129 let cp = *codepoints.get(i).context("Invalid codepoint index")?;
130 if (0xD800..=0xDBFF).contains(&cp)
132 && i.saturating_add(1) < codepoints.len()
133 {
134 let next = *codepoints
135 .get(i.saturating_add(1))
136 .context("Invalid surrogate pair index")?;
137 if (0xDC00..=0xDFFF).contains(&next) {
138 let high = cp;
140 let low = next;
141 let full = 0x10000u32.saturating_add(
142 ((high.saturating_sub(0xD800)) << 10)
143 | (low.saturating_sub(0xDC00)),
144 );
145 out.extend(encode_wtf8_single(full)?);
146 i = i.saturating_add(2);
147 continue;
148 }
149 }
150 out.extend(encode_wtf8_single(cp)?);
152 i = i.saturating_add(1);
153 }
154 Ok(out)
155}
156
157pub fn encode_wtf8_from_ucs2(ucs2: &[u16]) -> Result<Vec<u8>> {
160 let codepoints = ucs2decode(ucs2);
161 encode_wtf8_from_scalars(codepoints.as_slice())
162}
163
164fn read_continuation_byte(input: &[u8], byte_index: &mut usize) -> Result<u8> {
165 if *byte_index >= input.len() {
166 return Err(anyhow::anyhow!("WTF-8: Invalid byte index"));
167 }
168 let continuation_byte = *input
169 .get(*byte_index)
170 .context("WTF-8: Invalid byte index")?;
171 *byte_index = byte_index.saturating_add(1);
172 if (continuation_byte & 0xC0) == 0x80 {
173 Ok(continuation_byte & 0x3F)
174 } else {
175 Err(anyhow::anyhow!("WTF-8: Invalid continuation byte"))
177 }
178}
179
180pub fn decode_wtf8_single(
183 byte_array_input: &[u8],
184) -> anyhow::Result<(u32, usize), anyhow::Error> {
185 let mut byte_index = 0;
186 let byte_count = byte_array_input.len();
187
188 if byte_index > byte_count {
189 return Err(anyhow::anyhow!("Invalid WTF-8 sequence"));
190 }
191 if byte_index == byte_count {
192 return Err(anyhow::anyhow!(
193 "The original WTF-8 returned false here, not sure why"
194 ));
195 }
196
197 let byte1 = *byte_array_input
198 .get(byte_index)
199 .context("Invalid WTF-8 sequence")?;
200 byte_index = byte_index.saturating_add(1);
201
202 if (byte1 & 0x80) == 0 {
204 return Ok((u32::from(byte1), 1));
205 }
206
207 if (byte1 & 0xE0) == 0xC0 {
209 let byte2 = read_continuation_byte(byte_array_input, &mut byte_index)?;
210 let int_value = (u32::from(byte1 & 0x1F) << 6) | u32::from(byte2);
211 if int_value >= 0x80 {
212 return Ok((int_value, 2));
213 }
214 return Err(anyhow::anyhow!("WTF-8: Invalid 2-byte sequence"));
215 }
216
217 if (byte1 & 0xF0) == 0xE0 {
219 let byte2 = read_continuation_byte(byte_array_input, &mut byte_index)?;
220 let byte3 = read_continuation_byte(byte_array_input, &mut byte_index)?;
221 let int_value = (u32::from(byte1 & 0x0F) << 12)
222 | (u32::from(byte2) << 6)
223 | u32::from(byte3);
224 if int_value >= 0x0800 {
225 return Ok((int_value, 3));
226 }
227 return Err(anyhow::anyhow!("WTF-8: Invalid 3-byte sequence"));
228 }
229
230 if (byte1 & 0xF8) == 0xF0 {
232 let byte2 = read_continuation_byte(byte_array_input, &mut byte_index)?;
233 let byte3 = read_continuation_byte(byte_array_input, &mut byte_index)?;
234 let byte4 = read_continuation_byte(byte_array_input, &mut byte_index)?;
235 let int_value = (u32::from(byte1 & 0x0F)) << 18
236 | (u32::from(byte2)) << 12
237 | (u32::from(byte3)) << 6
238 | u32::from(byte4);
239 if (0x010000..=0x10FFFF).contains(&int_value) {
240 return Ok((int_value, 4));
241 }
242 }
243
244 Err(anyhow::anyhow!("WTF-8: Invalid 4-byte sequence"))
245}
246
247pub fn decode_wtf8_to_ucs2(byte_array_input: &[u8]) -> Result<Vec<u16>> {
249 let mut codepoints_with_unpaired_surrogates: Vec<u16> = Vec::new();
250 let mut byte_index = 0;
251 while byte_index < byte_array_input.len() {
252 let sub_slice = byte_array_input
253 .get(byte_index..)
254 .context("WTF-8: Invalid byte index")?;
255 let (cp, len) = decode_wtf8_single(sub_slice).context(format!(
256 "WTF-8: Invalid byte sequence at index {byte_index}"
257 ))?;
258 if cp > 0xFFFF {
259 let surrogates = ucs2encode(&[cp]).context(format!(
260 "WTF-8: Failed to convert codepoint to unpaired surrogates: {cp:?}"
261 ))?;
262 codepoints_with_unpaired_surrogates.extend(surrogates);
263 } else {
264 codepoints_with_unpaired_surrogates
265 .push(u16::try_from(cp).context("Failed to create u16")?);
266 }
267 byte_index = byte_index.saturating_add(len);
268 }
269
270 Ok(codepoints_with_unpaired_surrogates)
271}
272
273pub fn decode_wtf8_to_scalars(byte_array_input: &[u8]) -> Result<Vec<u32>> {
275 let codepoints_with_unpaired_surrogates =
276 decode_wtf8_to_ucs2(byte_array_input)
277 .context("WTF-8: Failed to decode to UCS-2")?;
278 let codepoints_as_u32: Vec<u32> = codepoints_with_unpaired_surrogates
279 .iter()
280 .map(|&cp| u32::from(cp))
281 .collect();
282 Ok(unpaired_surrogates_to_scalars(&codepoints_as_u32))
283}
284
285pub fn is_unpackable_wtf8(byte_array_input: &[u8]) -> bool {
287 decode_wtf8_single(byte_array_input).is_ok()
288}
289
290#[cfg(test)]
291#[allow(
292 clippy::panic,
293 clippy::expect_used,
294 clippy::unwrap_used,
295 clippy::unwrap_in_result,
296 clippy::panic_in_result_fn,
297 clippy::indexing_slicing,
298 clippy::arithmetic_side_effects,
299 reason = "Standard repository test boilerplate"
300)]
301mod tests {
302 use ctb_utilities::circular_dep_unicode::{
303 UNICODE_HISTORIC_MAX, UNICODE_MAX,
304 };
305
306 use super::*;
307
308 struct TestCase {
311 decoded: &'static [u16],
312 encoded: &'static [u8],
313 description: &'static str,
314 }
315
316 #[crate::ctb_test]
317 fn test_wtf8_encode_decode() -> Result<()> {
318 let cases = [
319 TestCase {
321 decoded: &[0x0000],
322 encoded: b"\0",
323 description: "U+0000",
324 },
325 TestCase {
326 decoded: &[0x005C],
327 encoded: b"\x5C",
328 description: "U+005C",
329 },
330 TestCase {
331 decoded: &[0x007F],
332 encoded: b"\x7F",
333 description: "U+007F",
334 },
335 TestCase {
337 decoded: &[0x0080],
338 encoded: &[0xC2, 0x80],
339 description: "U+0080",
340 },
341 TestCase {
342 decoded: &[0x05CA],
343 encoded: &[0xD7, 0x8A],
344 description: "U+05CA",
345 },
346 TestCase {
347 decoded: &[0x07FF],
348 encoded: &[0xDF, 0xBF],
349 description: "U+07FF",
350 },
351 TestCase {
353 decoded: &[0x0800],
354 encoded: &[0xE0, 0xA0, 0x80],
355 description: "U+0800",
356 },
357 TestCase {
358 decoded: &[0x2C3C],
359 encoded: &[0xE2, 0xB0, 0xBC],
360 description: "U+2C3C",
361 },
362 TestCase {
363 decoded: &[0xFFFF],
364 encoded: &[0xEF, 0xBF, 0xBF],
365 description: "U+FFFF",
366 },
367 TestCase {
371 decoded: &[0xD800],
372 encoded: &[0xED, 0xA0, 0x80],
373 description: "U+D800",
374 },
375 TestCase {
376 decoded: &[0xD800, 0xD800],
377 encoded: &[0xED, 0xA0, 0x80, 0xED, 0xA0, 0x80],
378 description: "High surrogate followed by another high surrogate",
379 },
380 TestCase {
381 decoded: &[0xD800, 0x41_u16],
382 encoded: &[0xED, 0xA0, 0x80, b'A'],
383 description: "High surrogate followed by a symbol that is not a surrogate",
384 },
385 TestCase {
386 decoded: &[0xD800, 0xD834, 0xDF06, 0xD800],
387 encoded: &[
388 0xED, 0xA0, 0x80, 0xF0, 0x9D, 0x8C, 0x86, 0xED, 0xA0, 0x80,
389 ],
390 description: "Unmatched high surrogate, followed by a surrogate pair, followed by an unmatched high surrogate",
391 },
392 TestCase {
393 decoded: &[0xD9AF],
394 encoded: &[0xED, 0xA6, 0xAF],
395 description: "U+D9AF",
396 },
397 TestCase {
398 decoded: &[0xDBFF],
399 encoded: &[0xED, 0xAF, 0xBF],
400 description: "U+DBFF",
401 },
402 TestCase {
404 decoded: &[0xDC00],
405 encoded: &[0xED, 0xB0, 0x80],
406 description: "U+DC00",
407 },
408 TestCase {
409 decoded: &[0xDC00, 0xDC00],
410 encoded: &[0xED, 0xB0, 0x80, 0xED, 0xB0, 0x80],
411 description: "Low surrogate followed by another low surrogate",
412 },
413 TestCase {
414 decoded: &[0xDC00, 0x41_u16],
415 encoded: &[0xED, 0xB0, 0x80, b'A'],
416 description: "Low surrogate followed by a symbol that is not a surrogate",
417 },
418 TestCase {
419 decoded: &[0xDC00, 0xD834, 0xDF06, 0xDC00],
420 encoded: &[
421 0xED, 0xB0, 0x80, 0xF0, 0x9D, 0x8C, 0x86, 0xED, 0xB0, 0x80,
422 ],
423 description: "Unmatched low surrogate, followed by a surrogate pair, followed by an unmatched low surrogate",
424 },
425 TestCase {
426 decoded: &[0xDEEE],
427 encoded: &[0xED, 0xBB, 0xAE],
428 description: "U+DEEE",
429 },
430 TestCase {
431 decoded: &[0xDFFF],
432 encoded: &[0xED, 0xBF, 0xBF],
433 description: "U+DFFF",
434 },
435 TestCase {
437 decoded: &[0xD800, 0xDC00],
439 encoded: &[0xF0, 0x90, 0x80, 0x80],
440 description: "U+10000",
441 },
442 TestCase {
443 decoded: &[0xD834, 0xDF06],
445 encoded: &[0xF0, 0x9D, 0x8C, 0x86],
446 description: "U+1D306",
447 },
448 TestCase {
449 decoded: &[0xDBFF, 0xDFFF],
451 encoded: &[0xF4, 0x8F, 0xBF, 0xBF],
452 description: "U+10FFFF",
453 },
454 ];
455 for case in &cases {
456 let encoded = encode_wtf8_from_ucs2(case.decoded)?;
458 assert_eq!(encoded, case.encoded, "Encoding: {}", case.description);
459 let decoded = decode_wtf8_to_ucs2(case.encoded);
461 if let Ok(decoded) = &decoded {
462 assert_eq!(
463 decoded.as_slice(),
464 case.decoded,
465 "Decoding: {}, encoded: {:?}, decoded: {:?}, expected: {:?}",
466 case.description,
467 case.encoded,
468 decoded,
469 case.decoded
470 );
471 } else {
472 panic!(
473 "Decoding error for case '{}':\n error: {:?}\n encoded: {:?}\n expected decoded: {:?}",
474 case.description,
475 decoded.err(),
476 case.encoded,
477 case.decoded,
478 );
479 }
480 }
481 Ok(())
482 }
483
484 #[crate::ctb_test]
485 fn test_wtf8_decode_errors() {
486 decode_wtf8_single(&[0xFF]).unwrap_err();
488 decode_wtf8_single(&[0xE9, 0x00, 0x00]).unwrap_err();
490 decode_wtf8_single(&[0xC2, 0xFF, 0xFF]).unwrap_err();
492 decode_wtf8_single(&[0xC2, 0xEF, 0xBF, 0xBF]).unwrap_err();
493 decode_wtf8_single(&[0xF0, 0x9D]).unwrap_err();
495 decode_wtf8_to_scalars(&[0xFD, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF])
496 .unwrap_err(); }
498
499 #[crate::ctb_test]
500 fn test_encode_wtf8_single_basic() {
501 assert_eq!(encode_wtf8_single(0x00).unwrap(), vec![0x00]);
503 assert_eq!(encode_wtf8_single(0x7F).unwrap(), vec![0x7F]);
504 assert_eq!(encode_wtf8_single(0x80).unwrap(), vec![0xC2, 0x80]);
506 assert_eq!(encode_wtf8_single(0x7FF).unwrap(), vec![0xDF, 0xBF]);
507 assert_eq!(encode_wtf8_single(0x800).unwrap(), vec![0xE0, 0xA0, 0x80]);
509 assert_eq!(encode_wtf8_single(0xFFFF).unwrap(), vec![0xEF, 0xBF, 0xBF]);
510 assert_eq!(
512 encode_wtf8_single(0x10000).unwrap(),
513 vec![0xF0, 0x90, 0x80, 0x80]
514 );
515 assert_eq!(
516 encode_wtf8_single(UNICODE_MAX).unwrap(),
517 vec![0xF4, 0x8F, 0xBF, 0xBF]
518 );
519 encode_wtf8_single(UNICODE_HISTORIC_MAX).unwrap_err();
520 }
521
522 #[crate::ctb_test]
523 fn test_encode_wtf8_from_scalars_surrogates() {
524 assert_eq!(
526 encode_wtf8_from_scalars(&[0xD800]).unwrap(),
527 vec![0xED, 0xA0, 0x80]
528 );
529 assert_eq!(
531 encode_wtf8_from_scalars(&[0xD834, 0xDF06]).unwrap(),
532 vec![0xF0, 0x9D, 0x8C, 0x86]
533 );
534 assert_eq!(
536 encode_wtf8_from_scalars(&[0xD800, 0xD834, 0xDF06, 0xD800])
537 .unwrap(),
538 vec![0xED, 0xA0, 0x80, 0xF0, 0x9D, 0x8C, 0x86, 0xED, 0xA0, 0x80]
539 );
540 }
541
542 #[crate::ctb_test]
543 fn test_decode_wtf8_to_scalars_basic() {
544 assert_eq!(decode_wtf8_to_scalars(&[0x00]).unwrap(), vec![0x00]);
546 assert_eq!(decode_wtf8_to_scalars(&[0xC2, 0x80]).unwrap(), vec![0x80]);
548 assert_eq!(
550 decode_wtf8_to_scalars(&[0xE0, 0xA0, 0x80]).unwrap(),
551 vec![0x800]
552 );
553 assert_eq!(
555 decode_wtf8_to_scalars(&[0xF0, 0x90, 0x80, 0x80]).unwrap(),
556 vec![0x10000]
557 );
558 assert_eq!(
559 decode_wtf8_to_scalars(&[0xF4, 0x8F, 0xBF, 0xBF]).unwrap(),
560 vec![UNICODE_MAX]
561 );
562 decode_wtf8_to_scalars(&[0xFD, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF])
563 .unwrap_err();
564 }
565
566 #[crate::ctb_test]
567 fn test_is_unpackable_wtf8() {
568 assert!(is_unpackable_wtf8(&[0x00]));
569 assert!(is_unpackable_wtf8(b"AAAA"));
570 assert!(is_unpackable_wtf8(&[b'A', b'A', b'A', 0xE0, 0xA0, 0x80]));
571 assert!(is_unpackable_wtf8(&[0xE0, 0xA0, 0x80, b'A', b'A', b'A']));
572 assert!(is_unpackable_wtf8(&[0xC2, 0x80]));
573 assert!(is_unpackable_wtf8(&[0xE0, 0xA0, 0x80]));
574 assert!(is_unpackable_wtf8(&[0xF0, 0x90, 0x80, 0x80]));
575 assert!(!is_unpackable_wtf8(&[0xC2])); assert!(!is_unpackable_wtf8(&[0xF0, 0x90])); assert!(!is_unpackable_wtf8(&[0xFF])); }
579}