1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
use std::char::ParseCharError;
use std::cmp::Ordering;
use std::fmt;
use std::fmt::{Debug, Display, Formatter, Write};
use std::hash::{Hash, Hasher};
use std::iter::{once, FusedIterator, Once};
use std::ops::Range;
use std::str::FromStr;

use crate::validations::{TAG_CONT, TAG_FOUR_B, TAG_THREE_B, TAG_TWO_B};

// JavaCodePoint is guaranteed to have the same repr as a u32, with valid values
// of between 0 and 0x10FFFF, the same as a unicode code point. Surrogate code
// points are valid values of this type.
#[derive(Copy, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct JavaCodePoint {
    #[cfg(target_endian = "little")]
    lower: u16,
    upper: SeventeenValues,
    #[cfg(target_endian = "big")]
    lower: u16,
}

#[repr(u16)]
#[derive(Copy, Clone, PartialEq, Eq)]
#[allow(unused)]
enum SeventeenValues {
    V0,
    V1,
    V2,
    V3,
    V4,
    V5,
    V6,
    V7,
    V8,
    V9,
    V10,
    V11,
    V12,
    V13,
    V14,
    V15,
    V16,
}

impl JavaCodePoint {
    pub const MAX: JavaCodePoint = JavaCodePoint::from_char(char::MAX);
    pub const REPLACEMENT_CHARACTER: JavaCodePoint =
        JavaCodePoint::from_char(char::REPLACEMENT_CHARACTER);

    /// See [`char::from_u32`]
    ///
    /// ```
    /// # use java_string::JavaCodePoint;
    /// let c = JavaCodePoint::from_u32(0x2764);
    /// assert_eq!(Some(JavaCodePoint::from_char('❤')), c);
    ///
    /// assert_eq!(None, JavaCodePoint::from_u32(0x110000));
    /// ```
    #[inline]
    #[must_use]
    pub const fn from_u32(i: u32) -> Option<JavaCodePoint> {
        if i <= 0x10ffff {
            unsafe { Some(Self::from_u32_unchecked(i)) }
        } else {
            None
        }
    }

    /// # Safety
    /// The argument must be within the valid Unicode code point range of 0 to
    /// 0x10FFFF inclusive. Surrogate code points are allowed.
    #[inline]
    #[must_use]
    pub const unsafe fn from_u32_unchecked(i: u32) -> JavaCodePoint {
        // SAFETY: the caller checks that the argument can be represented by this type
        std::mem::transmute(i)
    }

    /// Converts a `char` to a code point.
    #[inline]
    #[must_use]
    pub const fn from_char(char: char) -> JavaCodePoint {
        unsafe {
            // SAFETY: all chars are valid code points
            JavaCodePoint::from_u32_unchecked(char as u32)
        }
    }

    /// Converts this code point to a `u32`.
    ///
    /// ```
    /// # use java_string::JavaCodePoint;
    /// assert_eq!(65, JavaCodePoint::from_char('A').as_u32());
    /// assert_eq!(0xd800, JavaCodePoint::from_u32(0xd800).unwrap().as_u32());
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_u32(self) -> u32 {
        unsafe {
            // SAFETY: JavaCodePoint has the same repr as a u32
            let result = std::mem::transmute::<Self, u32>(self);

            if result > 0x10ffff {
                // SAFETY: JavaCodePoint can never have a value > 0x10FFFF.
                // This statement may allow the optimizer to remove branches in the calling code
                // associated with out of bounds chars.
                std::hint::unreachable_unchecked();
            }

            result
        }
    }

    /// Converts this code point to a `char`.
    ///
    /// ```
    /// # use java_string::JavaCodePoint;
    /// assert_eq!(Some('a'), JavaCodePoint::from_char('a').as_char());
    /// assert_eq!(None, JavaCodePoint::from_u32(0xd800).unwrap().as_char());
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_char(self) -> Option<char> {
        char::from_u32(self.as_u32())
    }

    /// # Safety
    /// The caller must ensure that this code point is not a surrogate code
    /// point.
    #[inline]
    #[must_use]
    pub unsafe fn as_char_unchecked(self) -> char {
        char::from_u32_unchecked(self.as_u32())
    }

    /// See [`char::encode_utf16`]
    ///
    /// ```
    /// # use java_string::JavaCodePoint;
    /// assert_eq!(
    ///     2,
    ///     JavaCodePoint::from_char('𝕊')
    ///         .encode_utf16(&mut [0; 2])
    ///         .len()
    /// );
    /// assert_eq!(
    ///     1,
    ///     JavaCodePoint::from_u32(0xd800)
    ///         .unwrap()
    ///         .encode_utf16(&mut [0; 2])
    ///         .len()
    /// );
    /// ```
    /// ```should_panic
    /// # use java_string::JavaCodePoint;
    /// // Should panic
    /// JavaCodePoint::from_char('𝕊').encode_utf16(&mut [0; 1]);
    /// ```
    #[inline]
    pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
        if let Some(char) = self.as_char() {
            char.encode_utf16(dst)
        } else {
            dst[0] = self.as_u32() as u16;
            &mut dst[..1]
        }
    }

    /// Encodes this `JavaCodePoint` into semi UTF-8, that is, UTF-8 with
    /// surrogate code points. See also [`char::encode_utf8`].
    ///
    /// ```
    /// # use java_string::JavaCodePoint;
    /// assert_eq!(
    ///     2,
    ///     JavaCodePoint::from_char('ß')
    ///         .encode_semi_utf8(&mut [0; 4])
    ///         .len()
    /// );
    /// assert_eq!(
    ///     3,
    ///     JavaCodePoint::from_u32(0xd800)
    ///         .unwrap()
    ///         .encode_semi_utf8(&mut [0; 4])
    ///         .len()
    /// );
    /// ```
    /// ```should_panic
    /// # use java_string::JavaCodePoint;
    /// // Should panic
    /// JavaCodePoint::from_char('ß').encode_semi_utf8(&mut [0; 1]);
    /// ```
    #[inline]
    pub fn encode_semi_utf8(self, dst: &mut [u8]) -> &mut [u8] {
        let len = self.len_utf8();
        let code = self.as_u32();
        match (len, &mut dst[..]) {
            (1, [a, ..]) => {
                *a = code as u8;
            }
            (2, [a, b, ..]) => {
                *a = (code >> 6 & 0x1f) as u8 | TAG_TWO_B;
                *b = (code & 0x3f) as u8 | TAG_CONT;
            }
            (3, [a, b, c, ..]) => {
                *a = (code >> 12 & 0x0f) as u8 | TAG_THREE_B;
                *b = (code >> 6 & 0x3f) as u8 | TAG_CONT;
                *c = (code & 0x3f) as u8 | TAG_CONT;
            }
            (4, [a, b, c, d, ..]) => {
                *a = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
                *b = (code >> 12 & 0x3f) as u8 | TAG_CONT;
                *c = (code >> 6 & 0x3f) as u8 | TAG_CONT;
                *d = (code & 0x3f) as u8 | TAG_CONT;
            }
            _ => panic!(
                "encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
                len,
                code,
                dst.len()
            ),
        }
        &mut dst[..len]
    }

    /// See [`char::eq_ignore_ascii_case`].
    #[inline]
    pub fn eq_ignore_ascii_case(&self, other: &JavaCodePoint) -> bool {
        match (self.as_char(), other.as_char()) {
            (Some(char1), Some(char2)) => char1.eq_ignore_ascii_case(&char2),
            (None, None) => self == other,
            _ => false,
        }
    }

    /// See [`char::escape_debug`].
    ///
    /// ```
    /// # use java_string::JavaCodePoint;
    /// assert_eq!(
    ///     "a",
    ///     JavaCodePoint::from_char('a').escape_debug().to_string()
    /// );
    /// assert_eq!(
    ///     "\\n",
    ///     JavaCodePoint::from_char('\n').escape_debug().to_string()
    /// );
    /// assert_eq!(
    ///     "\\u{d800}",
    ///     JavaCodePoint::from_u32(0xd800)
    ///         .unwrap()
    ///         .escape_debug()
    ///         .to_string()
    /// );
    /// ```
    #[inline]
    #[must_use]
    pub fn escape_debug(self) -> CharEscapeIter {
        self.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL)
    }

    #[inline]
    #[must_use]
    pub(crate) fn escape_debug_ext(self, args: EscapeDebugExtArgs) -> CharEscapeIter {
        const NULL: u32 = '\0' as u32;
        const TAB: u32 = '\t' as u32;
        const CARRIAGE_RETURN: u32 = '\r' as u32;
        const LINE_FEED: u32 = '\n' as u32;
        const SINGLE_QUOTE: u32 = '\'' as u32;
        const DOUBLE_QUOTE: u32 = '"' as u32;
        const BACKSLASH: u32 = '\\' as u32;

        unsafe {
            // SAFETY: all characters specified are in ascii range
            match self.as_u32() {
                NULL => CharEscapeIter::new([b'\\', b'0']),
                TAB => CharEscapeIter::new([b'\\', b't']),
                CARRIAGE_RETURN => CharEscapeIter::new([b'\\', b'r']),
                LINE_FEED => CharEscapeIter::new([b'\\', b'n']),
                SINGLE_QUOTE if args.escape_single_quote => CharEscapeIter::new([b'\\', b'\'']),
                DOUBLE_QUOTE if args.escape_double_quote => CharEscapeIter::new([b'\\', b'"']),
                BACKSLASH => CharEscapeIter::new([b'\\', b'\\']),
                _ if self.is_printable() => {
                    // SAFETY: surrogate code points are not printable
                    CharEscapeIter::printable(self.as_char_unchecked())
                }
                _ => self.escape_unicode(),
            }
        }
    }

    #[inline]
    fn is_printable(self) -> bool {
        let Some(char) = self.as_char() else {
            return false;
        };
        if matches!(char, '\\' | '\'' | '"') {
            return true;
        }
        char.escape_debug().next() != Some('\\')
    }

    /// See [`char::escape_default`].
    ///
    /// ```
    /// # use java_string::JavaCodePoint;
    /// assert_eq!(
    ///     "a",
    ///     JavaCodePoint::from_char('a').escape_default().to_string()
    /// );
    /// assert_eq!(
    ///     "\\n",
    ///     JavaCodePoint::from_char('\n').escape_default().to_string()
    /// );
    /// assert_eq!(
    ///     "\\u{d800}",
    ///     JavaCodePoint::from_u32(0xd800)
    ///         .unwrap()
    ///         .escape_default()
    ///         .to_string()
    /// );
    /// ```
    #[inline]
    #[must_use]
    pub fn escape_default(self) -> CharEscapeIter {
        const TAB: u32 = '\t' as u32;
        const CARRIAGE_RETURN: u32 = '\r' as u32;
        const LINE_FEED: u32 = '\n' as u32;
        const SINGLE_QUOTE: u32 = '\'' as u32;
        const DOUBLE_QUOTE: u32 = '"' as u32;
        const BACKSLASH: u32 = '\\' as u32;

        unsafe {
            // SAFETY: all characters specified are in ascii range
            match self.as_u32() {
                TAB => CharEscapeIter::new([b'\\', b't']),
                CARRIAGE_RETURN => CharEscapeIter::new([b'\\', b'r']),
                LINE_FEED => CharEscapeIter::new([b'\\', b'n']),
                SINGLE_QUOTE => CharEscapeIter::new([b'\\', b'\'']),
                DOUBLE_QUOTE => CharEscapeIter::new([b'\\', b'"']),
                BACKSLASH => CharEscapeIter::new([b'\\', b'\\']),
                0x20..=0x7e => CharEscapeIter::new([self.as_u32() as u8]),
                _ => self.escape_unicode(),
            }
        }
    }

    /// See [`char::escape_unicode`].
    ///
    /// ```
    /// # use java_string::JavaCodePoint;
    /// assert_eq!(
    ///     "\\u{2764}",
    ///     JavaCodePoint::from_char('❤').escape_unicode().to_string()
    /// );
    /// assert_eq!(
    ///     "\\u{d800}",
    ///     JavaCodePoint::from_u32(0xd800)
    ///         .unwrap()
    ///         .escape_unicode()
    ///         .to_string()
    /// );
    /// ```
    #[inline]
    #[must_use]
    pub fn escape_unicode(self) -> CharEscapeIter {
        let x = self.as_u32();

        let mut arr = [0; 10];
        arr[0] = b'\\';
        arr[1] = b'u';
        arr[2] = b'{';

        let number_len = if x == 0 {
            1
        } else {
            ((x.ilog2() >> 2) + 1) as usize
        };
        arr[3 + number_len] = b'}';
        for hexit in 0..number_len {
            arr[2 + number_len - hexit] = b"0123456789abcdef"[((x >> (hexit << 2)) & 15) as usize];
        }

        CharEscapeIter {
            inner: EscapeIterInner::Escaped(EscapeIterEscaped {
                bytes: arr,
                range: 0..number_len + 4,
            }),
        }
    }

    /// See [`char::is_alphabetic`].
    #[inline]
    #[must_use]
    pub fn is_alphabetic(self) -> bool {
        self.as_char().is_some_and(|char| char.is_alphabetic())
    }

    /// See [`char::is_alphanumeric`].
    #[inline]
    #[must_use]
    pub fn is_alphanumeric(self) -> bool {
        self.as_char().is_some_and(|char| char.is_alphanumeric())
    }

    /// See [`char::is_ascii`].
    #[inline]
    #[must_use]
    pub fn is_ascii(self) -> bool {
        self.as_u32() <= 0x7f
    }

    /// See [`char::is_ascii_alphabetic`].
    #[inline]
    #[must_use]
    pub const fn is_ascii_alphabetic(self) -> bool {
        self.is_ascii_lowercase() || self.is_ascii_uppercase()
    }

    /// See [`char::is_ascii_alphanumeric`].
    #[inline]
    #[must_use]
    pub const fn is_ascii_alphanumeric(self) -> bool {
        self.is_ascii_alphabetic() || self.is_ascii_digit()
    }

    /// See [`char::is_ascii_control`].
    #[inline]
    #[must_use]
    pub const fn is_ascii_control(self) -> bool {
        matches!(self.as_u32(), 0..=0x1f | 0x7f)
    }

    /// See [`char::is_ascii_digit`].
    #[inline]
    #[must_use]
    pub const fn is_ascii_digit(self) -> bool {
        const ZERO: u32 = '0' as u32;
        const NINE: u32 = '9' as u32;
        matches!(self.as_u32(), ZERO..=NINE)
    }

    /// See [`char::is_ascii_graphic`].
    #[inline]
    #[must_use]
    pub const fn is_ascii_graphic(self) -> bool {
        matches!(self.as_u32(), 0x21..=0x7e)
    }

    /// See [`char::is_ascii_hexdigit`].
    #[inline]
    #[must_use]
    pub const fn is_ascii_hexdigit(self) -> bool {
        const LOWER_A: u32 = 'a' as u32;
        const LOWER_F: u32 = 'f' as u32;
        const UPPER_A: u32 = 'A' as u32;
        const UPPER_F: u32 = 'F' as u32;
        self.is_ascii_digit() || matches!(self.as_u32(), (LOWER_A..=LOWER_F) | (UPPER_A..=UPPER_F))
    }

    /// See [`char::is_ascii_lowercase`].
    #[inline]
    #[must_use]
    pub const fn is_ascii_lowercase(self) -> bool {
        const A: u32 = 'a' as u32;
        const Z: u32 = 'z' as u32;
        matches!(self.as_u32(), A..=Z)
    }

    /// See [`char::is_ascii_octdigit`].
    #[inline]
    #[must_use]
    pub const fn is_ascii_octdigit(self) -> bool {
        const ZERO: u32 = '0' as u32;
        const SEVEN: u32 = '7' as u32;
        matches!(self.as_u32(), ZERO..=SEVEN)
    }

    /// See [`char::is_ascii_punctuation`].
    #[inline]
    #[must_use]
    pub const fn is_ascii_punctuation(self) -> bool {
        matches!(
            self.as_u32(),
            (0x21..=0x2f) | (0x3a..=0x40) | (0x5b..=0x60) | (0x7b..=0x7e)
        )
    }

    /// See [`char::is_ascii_uppercase`].
    #[inline]
    #[must_use]
    pub const fn is_ascii_uppercase(self) -> bool {
        const A: u32 = 'A' as u32;
        const Z: u32 = 'Z' as u32;
        matches!(self.as_u32(), A..=Z)
    }

    /// See [`char::is_ascii_whitespace`].
    #[inline]
    #[must_use]
    pub const fn is_ascii_whitespace(self) -> bool {
        const SPACE: u32 = ' ' as u32;
        const HORIZONTAL_TAB: u32 = '\t' as u32;
        const LINE_FEED: u32 = '\n' as u32;
        const FORM_FEED: u32 = 0xc;
        const CARRIAGE_RETURN: u32 = '\r' as u32;
        matches!(
            self.as_u32(),
            SPACE | HORIZONTAL_TAB | LINE_FEED | FORM_FEED | CARRIAGE_RETURN
        )
    }

    /// See [`char::is_control`].
    #[inline]
    #[must_use]
    pub fn is_control(self) -> bool {
        self.as_char().is_some_and(|char| char.is_control())
    }

    /// See [`char::is_digit`].
    #[inline]
    #[must_use]
    pub fn is_digit(self, radix: u32) -> bool {
        self.to_digit(radix).is_some()
    }

    /// See [`char::is_lowercase`].
    #[inline]
    #[must_use]
    pub fn is_lowercase(self) -> bool {
        self.as_char().is_some_and(|char| char.is_lowercase())
    }

    /// See [`char::is_numeric`].
    #[inline]
    #[must_use]
    pub fn is_numeric(self) -> bool {
        self.as_char().is_some_and(|char| char.is_numeric())
    }

    /// See [`char::is_uppercase`].
    #[inline]
    #[must_use]
    pub fn is_uppercase(self) -> bool {
        self.as_char().is_some_and(|char| char.is_uppercase())
    }

    /// See [`char::is_whitespace`].
    #[inline]
    #[must_use]
    pub fn is_whitespace(self) -> bool {
        self.as_char().is_some_and(|char| char.is_whitespace())
    }

    /// See [`char::len_utf16`]. Surrogate code points return 1.
    ///
    /// ```
    /// # use java_string::JavaCodePoint;
    ///
    /// let n = JavaCodePoint::from_char('ß').len_utf16();
    /// assert_eq!(n, 1);
    ///
    /// let len = JavaCodePoint::from_char('💣').len_utf16();
    /// assert_eq!(len, 2);
    ///
    /// assert_eq!(1, JavaCodePoint::from_u32(0xd800).unwrap().len_utf16());
    /// ```
    #[inline]
    #[must_use]
    pub const fn len_utf16(self) -> usize {
        if let Some(char) = self.as_char() {
            char.len_utf16()
        } else {
            1 // invalid code points are encoded as 1 utf16 code point anyway
        }
    }

    /// See [`char::len_utf8`]. Surrogate code points return 3.
    ///
    /// ```
    /// # use java_string::JavaCodePoint;
    ///
    /// let len = JavaCodePoint::from_char('A').len_utf8();
    /// assert_eq!(len, 1);
    ///
    /// let len = JavaCodePoint::from_char('ß').len_utf8();
    /// assert_eq!(len, 2);
    ///
    /// let len = JavaCodePoint::from_char('ℝ').len_utf8();
    /// assert_eq!(len, 3);
    ///
    /// let len = JavaCodePoint::from_char('💣').len_utf8();
    /// assert_eq!(len, 4);
    ///
    /// let len = JavaCodePoint::from_u32(0xd800).unwrap().len_utf8();
    /// assert_eq!(len, 3);
    /// ```
    #[inline]
    #[must_use]
    pub const fn len_utf8(self) -> usize {
        if let Some(char) = self.as_char() {
            char.len_utf8()
        } else {
            3 // invalid code points are all length 3 in semi-valid utf8
        }
    }

    /// See [`char::make_ascii_lowercase`].
    #[inline]
    pub fn make_ascii_lowercase(&mut self) {
        *self = self.to_ascii_lowercase();
    }

    /// See [`char::make_ascii_uppercase`].
    #[inline]
    pub fn make_ascii_uppercase(&mut self) {
        *self = self.to_ascii_uppercase();
    }

    /// See [`char::to_ascii_lowercase`].
    ///
    /// ```
    /// # use java_string::JavaCodePoint;
    ///
    /// let ascii = JavaCodePoint::from_char('A');
    /// let non_ascii = JavaCodePoint::from_char('❤');
    ///
    /// assert_eq!('a', ascii.to_ascii_lowercase());
    /// assert_eq!('❤', non_ascii.to_ascii_lowercase());
    /// ```
    #[inline]
    #[must_use]
    pub const fn to_ascii_lowercase(self) -> JavaCodePoint {
        if self.is_ascii_uppercase() {
            unsafe {
                // SAFETY: all lowercase chars are valid chars
                Self::from_u32_unchecked(self.as_u32() + 32)
            }
        } else {
            self
        }
    }

    /// See [`char::to_ascii_uppercase`].
    ///
    /// ```
    /// # use java_string::JavaCodePoint;
    ///
    /// let ascii = JavaCodePoint::from_char('a');
    /// let non_ascii = JavaCodePoint::from_char('❤');
    ///
    /// assert_eq!('A', ascii.to_ascii_uppercase());
    /// assert_eq!('❤', non_ascii.to_ascii_uppercase());
    /// ```
    #[inline]
    #[must_use]
    pub const fn to_ascii_uppercase(self) -> JavaCodePoint {
        if self.is_ascii_lowercase() {
            unsafe {
                // SAFETY: all uppercase chars are valid chars
                Self::from_u32_unchecked(self.as_u32() - 32)
            }
        } else {
            self
        }
    }

    /// See [`char::to_digit`].
    #[inline]
    #[must_use]
    pub const fn to_digit(self, radix: u32) -> Option<u32> {
        if let Some(char) = self.as_char() {
            char.to_digit(radix)
        } else {
            None
        }
    }

    /// See [`char::to_lowercase`].
    #[inline]
    #[must_use]
    pub fn to_lowercase(self) -> ToLowercase {
        match self.as_char() {
            Some(char) => ToLowercase::char(char.to_lowercase()),
            None => ToLowercase::invalid(self),
        }
    }

    /// See [`char::to_uppercase`].
    #[inline]
    #[must_use]
    pub fn to_uppercase(self) -> ToUppercase {
        match self.as_char() {
            Some(char) => ToUppercase::char(char.to_uppercase()),
            None => ToUppercase::invalid(self),
        }
    }
}

impl Debug for JavaCodePoint {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_char('\'')?;
        for c in self.escape_debug_ext(EscapeDebugExtArgs {
            escape_single_quote: true,
            escape_double_quote: false,
        }) {
            f.write_char(c)?;
        }
        f.write_char('\'')
    }
}

impl Default for JavaCodePoint {
    #[inline]
    fn default() -> Self {
        JavaCodePoint::from_char('\0')
    }
}

impl Display for JavaCodePoint {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Display::fmt(&self.as_char().unwrap_or(char::REPLACEMENT_CHARACTER), f)
    }
}

impl From<JavaCodePoint> for u32 {
    #[inline]
    fn from(value: JavaCodePoint) -> Self {
        value.as_u32()
    }
}

impl From<u8> for JavaCodePoint {
    #[inline]
    fn from(value: u8) -> Self {
        JavaCodePoint::from_char(char::from(value))
    }
}

impl FromStr for JavaCodePoint {
    type Err = ParseCharError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        char::from_str(s).map(JavaCodePoint::from_char)
    }
}

impl Hash for JavaCodePoint {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}

impl Ord for JavaCodePoint {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_u32().cmp(&other.as_u32())
    }
}

impl PartialOrd for JavaCodePoint {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialOrd<char> for JavaCodePoint {
    #[inline]
    fn partial_cmp(&self, other: &char) -> Option<Ordering> {
        self.partial_cmp(&JavaCodePoint::from_char(*other))
    }
}

impl PartialOrd<JavaCodePoint> for char {
    #[inline]
    fn partial_cmp(&self, other: &JavaCodePoint) -> Option<Ordering> {
        JavaCodePoint::from_char(*self).partial_cmp(other)
    }
}

impl PartialEq<char> for JavaCodePoint {
    #[inline]
    fn eq(&self, other: &char) -> bool {
        self == &JavaCodePoint::from_char(*other)
    }
}

impl PartialEq<JavaCodePoint> for char {
    #[inline]
    fn eq(&self, other: &JavaCodePoint) -> bool {
        &JavaCodePoint::from_char(*self) == other
    }
}

pub(crate) struct EscapeDebugExtArgs {
    pub(crate) escape_single_quote: bool,
    pub(crate) escape_double_quote: bool,
}

impl EscapeDebugExtArgs {
    pub(crate) const ESCAPE_ALL: Self = Self {
        escape_single_quote: true,
        escape_double_quote: true,
    };
}

#[derive(Clone, Debug)]
pub struct CharEscapeIter {
    inner: EscapeIterInner,
}

#[derive(Clone, Debug)]
enum EscapeIterInner {
    Printable(Once<char>),
    Escaped(EscapeIterEscaped),
}

impl Display for EscapeIterInner {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            EscapeIterInner::Printable(char) => char.clone().try_for_each(|ch| f.write_char(ch)),
            EscapeIterInner::Escaped(escaped) => Display::fmt(escaped, f),
        }
    }
}

impl CharEscapeIter {
    #[inline]
    fn printable(char: char) -> Self {
        CharEscapeIter {
            inner: EscapeIterInner::Printable(once(char)),
        }
    }

    /// # Safety
    /// Assumes that the input byte array is ASCII
    #[inline]
    unsafe fn new<const N: usize>(bytes: [u8; N]) -> Self {
        assert!(N <= 10, "Too many bytes in escape iter");
        let mut ten_bytes = [0; 10];
        ten_bytes[..N].copy_from_slice(&bytes);
        CharEscapeIter {
            inner: EscapeIterInner::Escaped(EscapeIterEscaped {
                bytes: ten_bytes,
                range: 0..N,
            }),
        }
    }
}

impl Iterator for CharEscapeIter {
    type Item = char;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.inner {
            EscapeIterInner::Printable(printable) => printable.next(),
            EscapeIterInner::Escaped(escaped) => escaped.next(),
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        match &self.inner {
            EscapeIterInner::Printable(printable) => printable.size_hint(),
            EscapeIterInner::Escaped(escaped) => escaped.size_hint(),
        }
    }
}

impl ExactSizeIterator for CharEscapeIter {
    #[inline]
    fn len(&self) -> usize {
        match &self.inner {
            EscapeIterInner::Printable(printable) => printable.len(),
            EscapeIterInner::Escaped(escaped) => escaped.len(),
        }
    }
}

impl FusedIterator for CharEscapeIter {}

impl Display for CharEscapeIter {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Display::fmt(&self.inner, f)
    }
}

#[derive(Clone, Debug)]
struct EscapeIterEscaped {
    // SAFETY: all values must be in the ASCII range
    bytes: [u8; 10],
    // SAFETY: range must not be out of bounds for length 10
    range: Range<usize>,
}

impl Iterator for EscapeIterEscaped {
    type Item = char;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.range.next().map(|index| unsafe {
            // SAFETY: the range is never out of bounds for length 10
            char::from(*self.bytes.get_unchecked(index))
        })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.range.size_hint()
    }

    #[inline]
    fn count(self) -> usize {
        self.range.len()
    }
}

impl ExactSizeIterator for EscapeIterEscaped {
    #[inline]
    fn len(&self) -> usize {
        self.range.len()
    }
}

impl FusedIterator for EscapeIterEscaped {}

impl Display for EscapeIterEscaped {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let str = unsafe {
            // SAFETY: all bytes are in ASCII range, and range is in bounds for length 10
            std::str::from_utf8_unchecked(self.bytes.get_unchecked(self.range.clone()))
        };
        f.write_str(str)
    }
}

pub type ToLowercase = CharIterDelegate<std::char::ToLowercase>;
pub type ToUppercase = CharIterDelegate<std::char::ToUppercase>;

#[derive(Debug, Clone)]
pub struct CharIterDelegate<I>(CharIterDelegateInner<I>);

impl<I> CharIterDelegate<I> {
    #[inline]
    fn char(iter: I) -> CharIterDelegate<I> {
        CharIterDelegate(CharIterDelegateInner::Char(iter))
    }

    #[inline]
    fn invalid(code_point: JavaCodePoint) -> CharIterDelegate<I> {
        CharIterDelegate(CharIterDelegateInner::Invalid(Some(code_point).into_iter()))
    }
}

#[derive(Debug, Clone)]
enum CharIterDelegateInner<I> {
    Char(I),
    Invalid(std::option::IntoIter<JavaCodePoint>),
}

impl<I> Iterator for CharIterDelegate<I>
where
    I: Iterator<Item = char>,
{
    type Item = JavaCodePoint;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.0 {
            CharIterDelegateInner::Char(char_iter) => {
                char_iter.next().map(JavaCodePoint::from_char)
            }
            CharIterDelegateInner::Invalid(code_point) => code_point.next(),
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        match &self.0 {
            CharIterDelegateInner::Char(char_iter) => char_iter.size_hint(),
            CharIterDelegateInner::Invalid(code_point) => code_point.size_hint(),
        }
    }
}

impl<I> DoubleEndedIterator for CharIterDelegate<I>
where
    I: Iterator<Item = char> + DoubleEndedIterator,
{
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        match &mut self.0 {
            CharIterDelegateInner::Char(char_iter) => {
                char_iter.next_back().map(JavaCodePoint::from_char)
            }
            CharIterDelegateInner::Invalid(code_point) => code_point.next_back(),
        }
    }
}

impl<I> ExactSizeIterator for CharIterDelegate<I> where I: Iterator<Item = char> + ExactSizeIterator {}

impl<I> FusedIterator for CharIterDelegate<I> where I: Iterator<Item = char> + FusedIterator {}