1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29#[expect(
43 clippy::expect_used,
44 reason = "Integer casts and array indexing are provably infallible due to preceding range checks and fixed array bounds"
45)]
46pub fn encode_utf_8e_128_buf(buf: &mut [u8], codepoint: u128) -> usize {
47 if codepoint <= 0x10FFFF {
57 let cp = u32::try_from(codepoint)
58 .expect("codepoint <= 0x10FFFF fits in u32");
59 if cp <= 0x7F {
60 if let Some(b) = buf.get_mut(0) {
61 *b = u8::try_from(cp).expect("cp <= 0x7F fits in u8");
62 }
63 return 1;
64 } else if cp <= 0x7FF {
65 if buf.len() >= 2 {
66 if let Some(b) = buf.get_mut(0) {
67 *b = 0xC0
68 | u8::try_from(cp >> 6)
69 .expect("cp >> 6 for cp <= 0x7FF is <= 31");
70 }
71 if let Some(b) = buf.get_mut(1) {
72 *b = 0x80
73 | u8::try_from(cp & 0x3F).expect("cp & 0x3F is <= 63");
74 }
75 }
76 return 2;
77 } else if cp <= 0xFFFF {
78 if buf.len() >= 3 {
79 if let Some(b) = buf.get_mut(0) {
80 *b = 0xE0
81 | u8::try_from(cp >> 12)
82 .expect("cp >> 12 for cp <= 0xFFFF is <= 15");
83 }
84 if let Some(b) = buf.get_mut(1) {
85 *b = 0x80
86 | u8::try_from((cp >> 6) & 0x3F)
87 .expect("shifted mask is <= 63");
88 }
89 if let Some(b) = buf.get_mut(2) {
90 *b = 0x80
91 | u8::try_from(cp & 0x3F).expect("cp & 0x3F is <= 63");
92 }
93 }
94 return 3;
95 }
96 if buf.len() >= 4 {
97 if let Some(b) = buf.get_mut(0) {
98 *b = 0xF0
99 | u8::try_from(cp >> 18)
100 .expect("cp >> 18 for cp <= 0x10FFFF is <= 4");
101 }
102 if let Some(b) = buf.get_mut(1) {
103 *b = 0x80
104 | u8::try_from((cp >> 12) & 0x3F)
105 .expect("shifted mask is <= 63");
106 }
107 if let Some(b) = buf.get_mut(2) {
108 *b = 0x80
109 | u8::try_from((cp >> 6) & 0x3F)
110 .expect("shifted mask is <= 63");
111 }
112 if let Some(b) = buf.get_mut(3) {
113 *b =
114 0x80 | u8::try_from(cp & 0x3F).expect("cp & 0x3F is <= 63");
115 }
116 }
117 return 4;
118 }
119
120 let leading_zeros = usize::try_from(codepoint.leading_zeros())
123 .expect("u32 leading_zeros (0..=128) fits in usize");
124 let bits = 128usize.saturating_sub(leading_zeros);
125 let mut l = bits.div_ceil(6); if l == 0 {
127 l = 1;
128 }
129 assert!(l <= 22, "Value requires more than 132 bits?");
130
131 assert!(
132 buf.len() >= 2usize.saturating_add(l),
133 "Buffer too small for extended encoding"
134 );
135
136 let mut groups = [0u8; 22];
138 {
139 let mut tmp = codepoint;
140 for i in 0..l {
141 let idx = l.saturating_sub(1).saturating_sub(i);
142 if let Some(g) = groups.get_mut(idx) {
143 *g = u8::try_from(tmp & 0x3F).expect("tmp & 0x3F is <= 63");
144 }
145 tmp >>= 6;
146 }
147 debug_assert!(tmp == 0);
148 }
149
150 debug_assert!(
152 groups.first().copied().expect("groups array has length 22") != 0
153 );
154
155 if let Some(b) = buf.get_mut(0) {
156 *b = 0xFF;
157 }
158 if let Some(b) = buf.get_mut(1) {
159 *b = 0x80 | u8::try_from(l).expect("l <= 22 fits in u8");
160 }
161
162 for i in 0..l {
163 let dest_idx = 2usize.saturating_add(i);
164 if let (Some(b), Some(&g)) = (buf.get_mut(dest_idx), groups.get(i)) {
165 *b = 0x80 | g;
166 }
167 }
168
169 if l == 22 {
172 debug_assert!(
173 (groups.first().copied().expect("groups array has length 22")
174 & 0x3C)
175 == 0,
176 "Non-zero padding bits in 22-byte encoding"
177 );
178 }
179
180 2usize.saturating_add(l)
181}
182
183#[expect(
187 clippy::expect_used,
188 clippy::unwrap_in_result,
189 reason = "Fixed-size 22-element groups array guarantees first element presence and buf slice fits encoded length"
190)]
191pub fn decode_utf_8e_128_buf(bytes: &[u8]) -> Option<(u128, usize)> {
192 let first = *bytes.first()?;
193 if first == 0xFF {
194 let h = *bytes.get(1)?;
196 if (h & 0xC0) != 0x80 {
197 return None;
198 }
199 let l = usize::from(h & 0x3F);
200 if l == 0 || l > 22 {
201 return None;
202 }
203 if bytes.len() < l.saturating_add(2) {
204 return None;
205 }
206
207 let mut groups = [0u8; 22];
209 for i in 0..l {
210 let b = *bytes.get(i.saturating_add(2))?;
211 if (b & 0xC0) != 0x80 {
212 return None;
213 }
214 if let Some(g) = groups.get_mut(i) {
215 *g = b & 0x3F;
216 }
217 }
218
219 if groups.first().copied().expect("groups array has length 22") == 0 {
221 return None;
222 }
223
224 if l == 22
226 && (groups.first().copied().expect("groups array has length 22")
227 & 0x3C)
228 != 0
229 {
230 return None;
231 }
232
233 let total_bits = l.saturating_mul(6);
235 let extra = total_bits.saturating_sub(128); if extra > 4 {
237 return None; }
239
240 let g0 = groups.first().copied().expect("groups array has length 22");
241 if extra > 0 && (g0 >> (6usize.saturating_sub(extra))) != 0 {
243 return None;
244 }
245
246 let mut value: u128 = 0;
247 if extra < 6 {
248 let first_payload_bits = g0
250 & ((1u8 << (6usize.saturating_sub(extra))).saturating_sub(1));
251 value = u128::from(first_payload_bits);
252 }
253 for i in 1..l {
254 if let Some(&g) = groups.get(i) {
255 value = (value << 6) | u128::from(g);
256 }
257 }
258
259 if value <= 0x10FFFF {
261 return None;
262 }
263
264 return Some((value, l.saturating_add(2)));
265 }
266
267 if first < 0x80 {
269 return Some((u128::from(first), 1));
270 }
271
272 let (len, min_val, max_val_mask) = if (first & 0xE0) == 0xC0 {
274 (2usize, 0x80u32, 0x1F)
276 } else if (first & 0xF0) == 0xE0 {
277 (3usize, 0x800u32, 0x0F)
279 } else if (first & 0xF8) == 0xF0 {
280 (4usize, 0x10000u32, 0x07)
282 } else {
283 return None;
284 };
285
286 if bytes.len() < len {
287 return None;
288 }
289
290 let mut val: u32 = u32::from(first & max_val_mask);
291 for i in 1..len {
292 let b = *bytes.get(i)?;
293 if (b & 0xC0) != 0x80 {
294 return None;
295 }
296 val = (val << 6) | u32::from(b & 0x3F);
297 }
298
299 if val < min_val {
301 return None;
302 }
303
304 if val > 0x10FFFF {
306 return None;
307 }
308
309 Some((u128::from(val), len))
315}
316
317#[expect(
320 clippy::expect_used,
321 reason = "encode_utf_8e_128_buf returns length <= 24 which fits in 24-byte buf"
322)]
323pub fn encode_utf_8e_128(codepoint: u128) -> Vec<u8> {
324 let mut buf = [0u8; 24];
325 let encoded_len = encode_utf_8e_128_buf(&mut buf, codepoint);
326 buf.get(..encoded_len)
327 .expect("encoded_len <= 24 fits in buf")
328 .to_vec()
329}
330
331#[must_use]
334pub fn decode_utf_8e_128(bytes: &[u8]) -> Option<(u128, usize)> {
335 if bytes.is_empty() {
336 return None;
337 }
338
339 if let Some(x) = decode_utf_8e_128_buf(bytes) {
340 Some(x)
341 } else {
342 let err_len =
345 determine_utf_8e_128_error_len(bytes).unwrap_or(bytes.len());
346 Some((0xFFFD, err_len))
347 }
348}
349
350#[must_use]
352#[expect(
353 clippy::expect_used,
354 reason = "u32 leading_zeros (0..=128) always fits in usize"
355)]
356pub fn len_utf_8e_128(codepoint: u128) -> usize {
357 if codepoint <= 0x7F {
358 1
359 } else if codepoint <= 0x7FF {
360 2
361 } else if codepoint <= 0xFFFF {
362 3
363 } else if codepoint <= 0x10_FFFF {
364 4
365 } else {
366 let leading_zeros = usize::try_from(codepoint.leading_zeros())
367 .expect("u32 leading_zeros fits in usize");
368 let bits = 128usize.saturating_sub(leading_zeros);
369 let l = bits.div_ceil(6).max(1);
370 2usize.saturating_add(l)
371 }
372}
373
374#[must_use]
382pub fn determine_utf_8e_128_error_len(slice: &[u8]) -> Option<usize> {
383 let first = *slice.first()?;
384 if first < 0x80 {
385 return Some(1);
386 }
387 if first < 0xC2 || (0xF5..=0xFE).contains(&first) {
388 return Some(1);
389 }
390 if first == 0xFF {
391 let Some(&b1) = slice.get(1) else {
392 return None;
393 };
394 if !(0x84..=0x96).contains(&b1) {
395 return Some(1);
396 }
397 let l = usize::from(b1 & 0x3F);
398 let expected_len = 2usize.saturating_add(l);
399 for i in 2..expected_len {
400 let Some(&b) = slice.get(i) else {
401 return None;
402 };
403 if (b & 0xC0) != 0x80 {
404 return Some(i);
405 }
406 if i == 2 {
407 if l == 4 && b < 0x84 {
408 return Some(2);
409 }
410 if l == 22 && !(0x81..=0x83).contains(&b) {
411 return Some(2);
412 }
413 if (5..=21).contains(&l) && b < 0x81 {
414 return Some(2);
415 }
416 } else if i == 3
417 && l == 4
418 && slice.get(2).copied() == Some(0x84)
419 && b < 0x90
420 {
421 return Some(3);
422 }
423 }
424 return Some(expected_len);
425 }
426
427 let (expected_len, min_b1, max_b1) = if first <= 0xDF {
428 (2usize, 0x80u8, 0xBFu8)
429 } else if first == 0xE0 {
430 (3usize, 0xA0u8, 0xBFu8)
431 } else if first <= 0xEF {
432 (3usize, 0x80u8, 0xBFu8)
433 } else if first == 0xF0 {
434 (4usize, 0x90u8, 0xBFu8)
435 } else if first <= 0xF3 {
436 (4usize, 0x80u8, 0xBFu8)
437 } else {
438 (4usize, 0x80u8, 0x8Fu8)
440 };
441
442 for i in 1..expected_len {
443 let Some(&b) = slice.get(i) else {
444 return None;
445 };
446 let (lo, hi) = if i == 1 {
447 (min_b1, max_b1)
448 } else {
449 (0x80u8, 0xBFu8)
450 };
451 if b < lo || b > hi {
452 return Some(i);
453 }
454 }
455 Some(expected_len)
456}
457
458pub const MAX_DCTF_LEN: usize = 23;
460
461#[must_use]
463#[expect(
464 clippy::expect_used,
465 reason = "u32 leading_zeros (0..=128) always fits in usize"
466)]
467pub fn len_dctf(codepoint: u128) -> usize {
468 if codepoint <= 0x7F {
469 1
470 } else if codepoint <= 0x7FF {
471 2
472 } else if codepoint <= 0xFFFF {
473 3
474 } else if codepoint <= 0x1F_FFFF {
475 4
476 } else if codepoint <= 0x3FF_FFFF {
477 5
478 } else if codepoint <= 0x7FFF_FFFF {
479 6
480 } else if codepoint <= 0xF_FFFF_FFFF {
481 7
482 } else {
483 let leading_zeros = usize::try_from(codepoint.leading_zeros())
484 .expect("u32 leading_zeros fits in usize");
485 let bits = 128usize.saturating_sub(leading_zeros);
486 let k = bits.saturating_sub(38).div_ceil(6);
487 8usize.saturating_add(k)
488 }
489}
490
491#[expect(
506 clippy::expect_used,
507 reason = "Bitmask and range-checked shifts guarantee infallible u8/usize conversions"
508)]
509pub fn encode_dctf_buf(buf: &mut [u8], codepoint: u128) -> usize {
510 if codepoint <= 0x7F {
511 assert!(!buf.is_empty(), "Buffer too small for 1-byte DcTF encoding");
512 if let Some(b) = buf.get_mut(0) {
513 *b = u8::try_from(codepoint).expect("<= 0x7F fits in u8");
514 }
515 return 1;
516 }
517
518 if codepoint <= 0xF_FFFF_FFFF {
519 let (len, lead_prefix): (usize, u8) = if codepoint <= 0x7FF {
520 (2, 0xC0)
521 } else if codepoint <= 0xFFFF {
522 (3, 0xE0)
523 } else if codepoint <= 0x1F_FFFF {
524 (4, 0xF0)
525 } else if codepoint <= 0x3FF_FFFF {
526 (5, 0xF8)
527 } else if codepoint <= 0x7FFF_FFFF {
528 (6, 0xFC)
529 } else {
530 (7, 0xFE)
531 };
532 assert!(
533 buf.len() >= len,
534 "Buffer too small for {len}-byte DcTF encoding"
535 );
536 let cont_count = len.saturating_sub(1);
537 let top_shift = cont_count.saturating_mul(6);
538 if let Some(b0) = buf.get_mut(0) {
539 *b0 = lead_prefix
540 | u8::try_from(codepoint >> top_shift)
541 .expect("top bits fit in lead byte payload");
542 }
543 for i in 0..cont_count {
544 let shift = cont_count
545 .saturating_sub(1)
546 .saturating_sub(i)
547 .saturating_mul(6);
548 if let Some(b) = buf.get_mut(1usize.saturating_add(i)) {
549 *b = 0x80
550 | u8::try_from((codepoint >> shift) & 0x3F)
551 .expect("masked 6-bit group fits in u8");
552 }
553 }
554 return len;
555 }
556
557 let leading_zeros = usize::try_from(codepoint.leading_zeros())
559 .expect("u32 leading_zeros fits in usize");
560 let bits = 128usize.saturating_sub(leading_zeros);
561 let k = bits.saturating_sub(38).div_ceil(6);
562 debug_assert!(k <= 15);
563 let cont_count = k.saturating_add(6);
564 let total_len = k.saturating_add(8);
565 assert!(
566 buf.len() >= total_len,
567 "Buffer too small for {total_len}-byte extended DcTF encoding"
568 );
569
570 let top_shift = cont_count.saturating_mul(6);
571 let top_2 = if top_shift < 128 {
572 u8::try_from((codepoint >> top_shift) & 0x03)
573 .expect("2-bit value fits in u8")
574 } else {
575 0
576 };
577 let k_u8 = u8::try_from(k).expect("k <= 15 fits in u8");
578 if let Some(b0) = buf.get_mut(0) {
579 *b0 = 0xFF;
580 }
581 if let Some(b1) = buf.get_mut(1) {
582 *b1 = 0x80 | (k_u8 << 2) | top_2;
583 }
584 for i in 0..cont_count {
585 let shift = cont_count
586 .saturating_sub(1)
587 .saturating_sub(i)
588 .saturating_mul(6);
589 if let Some(b) = buf.get_mut(2usize.saturating_add(i)) {
590 *b = 0x80
591 | u8::try_from((codepoint >> shift) & 0x3F)
592 .expect("masked 6-bit group fits in u8");
593 }
594 }
595 total_len
596}
597
598#[must_use]
603pub fn decode_dctf_buf(bytes: &[u8]) -> Option<(u128, usize)> {
604 let first = *bytes.first()?;
605 if first < 0x80 {
606 return Some((u128::from(first), 1));
607 }
608 if first < 0xC2 {
609 return None;
610 }
611 if first == 0xFF {
612 let b1 = *bytes.get(1)?;
613 if (b1 & 0xC0) != 0x80 {
614 return None;
615 }
616 let k = usize::from((b1 >> 2) & 0x0F);
617 let total_len = 8usize.saturating_add(k);
618 if bytes.len() < total_len {
619 return None;
620 }
621 let mut value = u128::from(b1 & 0x03);
622 for i in 2..total_len {
623 let b = *bytes.get(i)?;
624 if (b & 0xC0) != 0x80 {
625 return None;
626 }
627 value = (value << 6) | u128::from(b & 0x3F);
628 }
629 let min_val = if k == 0 {
630 1u128 << 36
631 } else {
632 1u128 << (32usize.saturating_add(6usize.saturating_mul(k)))
633 };
634 if value < min_val {
635 return None;
636 }
637 return Some((value, total_len));
638 }
639
640 let (len, min_val, lead_mask): (usize, u128, u8) = if (first & 0xE0) == 0xC0
641 {
642 (2, 1u128 << 7, 0x1F)
643 } else if (first & 0xF0) == 0xE0 {
644 (3, 1u128 << 11, 0x0F)
645 } else if (first & 0xF8) == 0xF0 {
646 (4, 1u128 << 16, 0x07)
647 } else if (first & 0xFC) == 0xF8 {
648 (5, 1u128 << 21, 0x03)
649 } else if (first & 0xFE) == 0xFC {
650 (6, 1u128 << 26, 0x01)
651 } else {
652 (7, 1u128 << 31, 0x00)
654 };
655
656 if bytes.len() < len {
657 return None;
658 }
659
660 let mut value = u128::from(first & lead_mask);
661 for i in 1..len {
662 let b = *bytes.get(i)?;
663 if (b & 0xC0) != 0x80 {
664 return None;
665 }
666 value = (value << 6) | u128::from(b & 0x3F);
667 }
668
669 if value < min_val {
670 return None;
671 }
672
673 Some((value, len))
674}
675
676#[must_use]
684pub fn determine_dctf_error_len(slice: &[u8]) -> Option<usize> {
685 let first = *slice.first()?;
686 if first < 0xC2 {
687 return Some(1);
688 }
689 if first == 0xFF {
690 let Some(&b1) = slice.get(1) else {
691 return None;
692 };
693 if (b1 & 0xC0) != 0x80 || b1 == 0x80 {
694 return Some(1);
695 }
696 let k = usize::from((b1 >> 2) & 0x0F);
697 let expected_len = 8usize.saturating_add(k);
698 for i in 2..expected_len {
699 let Some(&b) = slice.get(i) else {
700 return None;
701 };
702 if (b & 0xC0) != 0x80 {
703 return Some(i);
704 }
705 if i == 2 && k >= 1 && (b1 & 0x03) == 0 && b < 0x84 {
706 return Some(2);
707 }
708 }
709 return Some(expected_len);
710 }
711
712 let (expected_len, min_b1): (usize, u8) = if first <= 0xDF {
713 (2, 0x80)
714 } else if first == 0xE0 {
715 (3, 0xA0)
716 } else if first <= 0xEF {
717 (3, 0x80)
718 } else if first == 0xF0 {
719 (4, 0x90)
720 } else if first <= 0xF7 {
721 (4, 0x80)
722 } else if first == 0xF8 {
723 (5, 0x88)
724 } else if first <= 0xFB {
725 (5, 0x80)
726 } else if first == 0xFC {
727 (6, 0x84)
728 } else if first == 0xFD {
729 (6, 0x80)
730 } else {
731 (7, 0x82)
733 };
734
735 for i in 1..expected_len {
736 let Some(&b) = slice.get(i) else {
737 return None;
738 };
739 let lo = if i == 1 { min_b1 } else { 0x80 };
740 if b < lo || b > 0xBF {
741 return Some(i);
742 }
743 }
744 Some(expected_len)
745}
746
747#[must_use]
749#[expect(
750 clippy::expect_used,
751 reason = "encode_dctf_buf returns length <= MAX_DCTF_LEN (23) which fits in buf"
752)]
753pub fn encode_dctf(codepoint: u128) -> Vec<u8> {
754 let mut buf = [0u8; MAX_DCTF_LEN];
755 let encoded_len = encode_dctf_buf(&mut buf, codepoint);
756 buf.get(..encoded_len)
757 .expect("encoded_len <= 23 fits in buf")
758 .to_vec()
759}
760
761#[must_use]
764pub fn decode_dctf(bytes: &[u8]) -> Option<(u128, usize)> {
765 if bytes.is_empty() {
766 return None;
767 }
768
769 if let Some(x) = decode_dctf_buf(bytes) {
770 Some(x)
771 } else {
772 let err_len = determine_dctf_error_len(bytes).unwrap_or(bytes.len());
775 Some((0xFFFD, err_len))
776 }
777}