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
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

use alloc::vec;
use alloc::vec::Vec;
use core::{char, cmp::Ordering, ops::RangeBounds};
use potential_utf::PotentialCodePoint;

use crate::codepointinvlist::{utils::deconstruct_range, CodePointInversionList};
use zerovec::{ule::AsULE, ZeroVec};

/// A builder for [`CodePointInversionList`].
///
/// Provides exposure to builder functions and conversion to [`CodePointInversionList`]
#[derive(Default)]
pub struct CodePointInversionListBuilder {
    // A sorted list of even length, with values <= char::MAX + 1
    intervals: Vec<u32>,
}

impl CodePointInversionListBuilder {
    /// Returns empty [`CodePointInversionListBuilder`]
    pub const fn new() -> Self {
        Self { intervals: vec![] }
    }

    /// Returns a [`CodePointInversionList`] and consumes the [`CodePointInversionListBuilder`]
    pub fn build(self) -> CodePointInversionList<'static> {
        let inv_list: ZeroVec<PotentialCodePoint> = self
            .intervals
            .into_iter()
            .map(PotentialCodePoint::from_u24)
            .collect();
        #[allow(clippy::unwrap_used)] // by invariant
        CodePointInversionList::try_from_inversion_list(inv_list).unwrap()
    }

    /// Abstraction for adding/removing a range from start..end
    ///
    /// If add is true add, else remove
    fn add_remove_middle(&mut self, start: u32, end: u32, add: bool) {
        if start >= end || end > char::MAX as u32 + 1 {
            return;
        }
        let start_res = self.intervals.binary_search(&start);
        let end_res = self.intervals.binary_search(&end);
        let mut start_ind = start_res.unwrap_or_else(|x| x);
        let mut end_ind = end_res.unwrap_or_else(|x| x);
        let start_pos_check = (start_ind % 2 == 0) == add;
        let end_pos_check = (end_ind % 2 == 0) == add;
        let start_eq_end = start_ind == end_ind;

        #[allow(clippy::indexing_slicing)] // all indices are binary search results
        if start_eq_end && start_pos_check && end_res.is_err() {
            self.intervals.splice(start_ind..end_ind, [start, end]);
        } else {
            if start_pos_check {
                self.intervals[start_ind] = start;
                start_ind += 1;
            }
            if end_pos_check {
                if end_res.is_ok() {
                    end_ind += 1;
                } else {
                    end_ind -= 1;
                    self.intervals[end_ind] = end;
                }
            }
            if start_ind < end_ind {
                self.intervals.drain(start_ind..end_ind);
            }
        }
    }

    /// Add the range to the [`CodePointInversionListBuilder`]
    ///
    /// Accomplishes this through binary search for the start and end indices and merges intervals
    /// in between with inplace memory. Performs `O(1)` operation if adding to end of list, and `O(N)` otherwise,
    /// where `N` is the number of endpoints.
    fn add(&mut self, start: u32, end: u32) {
        if start >= end {
            return;
        }
        if self.intervals.is_empty() {
            self.intervals.extend_from_slice(&[start, end]);
            return;
        }
        self.add_remove_middle(start, end, true);
    }

    /// Add the character to the [`CodePointInversionListBuilder`]
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionListBuilder;
    /// let mut builder = CodePointInversionListBuilder::new();
    /// builder.add_char('a');
    /// let check = builder.build();
    /// assert_eq!(check.iter_chars().next(), Some('a'));
    /// ```
    pub fn add_char(&mut self, c: char) {
        let to_add = c as u32;
        self.add(to_add, to_add + 1);
    }

    /// Add the code point value to the [`CodePointInversionListBuilder`]
    ///
    /// Note: Even though [`u32`] and [`prim@char`] in Rust are non-negative 4-byte
    /// values, there is an important difference. A [`u32`] can take values up to
    /// a very large integer value, while a [`prim@char`] in Rust is defined to be in
    /// the range from 0 to the maximum valid Unicode Scalar Value.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionListBuilder;
    /// let mut builder = CodePointInversionListBuilder::new();
    /// builder.add32(0x41);
    /// let check = builder.build();
    /// assert!(check.contains32(0x41));
    /// ```
    pub fn add32(&mut self, c: u32) {
        if c <= char::MAX as u32 {
            // we already know 0 <= c  because c: u32
            self.add(c, c + 1);
        }
    }

    /// Add the range of characters to the [`CodePointInversionListBuilder`]
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionListBuilder;
    /// let mut builder = CodePointInversionListBuilder::new();
    /// builder.add_range('A'..='Z');
    /// let check = builder.build();
    /// assert_eq!(check.iter_chars().next(), Some('A'));
    /// ```
    pub fn add_range(&mut self, range: impl RangeBounds<char>) {
        let (start, end) = deconstruct_range(range);
        self.add(start, end);
    }

    /// Add the range of characters, represented as u32, to the [`CodePointInversionListBuilder`]
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionListBuilder;
    /// let mut builder = CodePointInversionListBuilder::new();
    /// builder.add_range32(0xd800..=0xdfff);
    /// let check = builder.build();
    /// assert!(check.contains32(0xd900));
    /// ```
    pub fn add_range32(&mut self, range: impl RangeBounds<u32>) {
        let (start, end) = deconstruct_range(range);
        // Sets that include char::MAX need to allow an end value of MAX + 1
        if start <= end && end <= char::MAX as u32 + 1 {
            self.add(start, end);
        }
    }

    /// Add the [`CodePointInversionList`] reference to the [`CodePointInversionListBuilder`]
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::{
    ///     CodePointInversionList, CodePointInversionListBuilder,
    /// };
    /// let mut builder = CodePointInversionListBuilder::new();
    /// let set = CodePointInversionList::try_from_u32_inversion_list_slice(&[
    ///     0x41, 0x4C,
    /// ])
    /// .unwrap();
    /// builder.add_set(&set);
    /// let check = builder.build();
    /// assert_eq!(check.iter_chars().next(), Some('A'));
    /// ```
    #[allow(unused_assignments)]
    pub fn add_set(&mut self, set: &CodePointInversionList) {
        #[allow(clippy::indexing_slicing)] // chunks
        set.as_inversion_list()
            .as_ule_slice()
            .chunks(2)
            .for_each(|pair| {
                self.add(
                    u32::from(PotentialCodePoint::from_unaligned(pair[0])),
                    u32::from(PotentialCodePoint::from_unaligned(pair[1])),
                )
            });
    }

    /// Removes the range from the [`CodePointInversionListBuilder`]
    ///
    /// Performs binary search to find start and end affected intervals, then removes in an `O(N)` fashion
    /// where `N` is the number of endpoints, with in-place memory.
    fn remove(&mut self, start: u32, end: u32) {
        if start >= end || self.intervals.is_empty() {
            return;
        }
        if let Some(&last) = self.intervals.last() {
            #[allow(clippy::indexing_slicing)]
            // by invariant, if we have a last we have a (different) first
            if start <= self.intervals[0] && end >= last {
                self.intervals.clear();
            } else {
                self.add_remove_middle(start, end, false);
            }
        }
    }

    /// Remove the character from the [`CodePointInversionListBuilder`]
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionListBuilder;
    /// let mut builder = CodePointInversionListBuilder::new();
    /// builder.add_range('A'..='Z');
    /// builder.remove_char('A');
    /// let check = builder.build();
    /// assert_eq!(check.iter_chars().next(), Some('B'));
    pub fn remove_char(&mut self, c: char) {
        self.remove32(c as u32)
    }

    /// See [`Self::remove_char`]
    pub fn remove32(&mut self, c: u32) {
        self.remove(c, c + 1);
    }

    /// Remove the range of characters from the [`CodePointInversionListBuilder`]
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionListBuilder;
    /// let mut builder = CodePointInversionListBuilder::new();
    /// builder.add_range('A'..='Z');
    /// builder.remove_range('A'..='C');
    /// let check = builder.build();
    /// assert_eq!(check.iter_chars().next(), Some('D'));
    pub fn remove_range(&mut self, range: impl RangeBounds<char>) {
        let (start, end) = deconstruct_range(range);
        self.remove(start, end);
    }

    /// See [`Self::remove_range`]
    pub fn remove_range32(&mut self, range: impl RangeBounds<u32>) {
        let (start, end) = deconstruct_range(range);
        self.remove(start, end);
    }

    /// Remove the [`CodePointInversionList`] from the [`CodePointInversionListBuilder`]
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::{CodePointInversionList, CodePointInversionListBuilder};
    /// let mut builder = CodePointInversionListBuilder::new();
    /// let set = CodePointInversionList::try_from_u32_inversion_list_slice(&[0x41, 0x46]).unwrap();
    /// builder.add_range('A'..='Z');
    /// builder.remove_set(&set); // removes 'A'..='E'
    /// let check = builder.build();
    /// assert_eq!(check.iter_chars().next(), Some('F'));
    #[allow(clippy::indexing_slicing)] // chunks
    pub fn remove_set(&mut self, set: &CodePointInversionList) {
        set.as_inversion_list()
            .as_ule_slice()
            .chunks(2)
            .for_each(|pair| {
                self.remove(
                    u32::from(PotentialCodePoint::from_unaligned(pair[0])),
                    u32::from(PotentialCodePoint::from_unaligned(pair[1])),
                )
            });
    }

    /// Retain the specified character in the [`CodePointInversionListBuilder`] if it exists
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionListBuilder;
    /// let mut builder = CodePointInversionListBuilder::new();
    /// builder.add_range('A'..='Z');
    /// builder.retain_char('A');
    /// let set = builder.build();
    /// let mut check = set.iter_chars();
    /// assert_eq!(check.next(), Some('A'));
    /// assert_eq!(check.next(), None);
    /// ```
    pub fn retain_char(&mut self, c: char) {
        self.retain32(c as u32)
    }

    /// See [`Self::retain_char`]
    pub fn retain32(&mut self, c: u32) {
        self.remove(0, c);
        self.remove(c + 1, (char::MAX as u32) + 1);
    }

    /// Retain the range of characters located within the [`CodePointInversionListBuilder`]
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionListBuilder;
    /// let mut builder = CodePointInversionListBuilder::new();
    /// builder.add_range('A'..='Z');
    /// builder.retain_range('A'..='B');
    /// let set = builder.build();
    /// let mut check = set.iter_chars();
    /// assert_eq!(check.next(), Some('A'));
    /// assert_eq!(check.next(), Some('B'));
    /// assert_eq!(check.next(), None);
    /// ```
    pub fn retain_range(&mut self, range: impl RangeBounds<char>) {
        let (start, end) = deconstruct_range(range);
        self.remove(0, start);
        self.remove(end, (char::MAX as u32) + 1);
    }

    /// See [`Self::retain_range`]
    pub fn retain_range32(&mut self, range: impl RangeBounds<u32>) {
        let (start, end) = deconstruct_range(range);
        self.remove(0, start);
        self.remove(end, (char::MAX as u32) + 1);
    }

    /// Retain the elements in the specified set within the [`CodePointInversionListBuilder`]
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::{
    ///     CodePointInversionList, CodePointInversionListBuilder,
    /// };
    /// let mut builder = CodePointInversionListBuilder::new();
    /// let set =
    ///     CodePointInversionList::try_from_u32_inversion_list_slice(&[65, 70])
    ///         .unwrap();
    /// builder.add_range('A'..='Z');
    /// builder.retain_set(&set); // retains 'A'..='E'
    /// let check = builder.build();
    /// assert!(check.contains('A'));
    /// assert!(!check.contains('G'));
    /// ```
    #[allow(clippy::indexing_slicing)] // chunks
    pub fn retain_set(&mut self, set: &CodePointInversionList) {
        let mut prev = 0;
        for pair in set.as_inversion_list().as_ule_slice().chunks(2) {
            let range_start = u32::from(PotentialCodePoint::from_unaligned(pair[0]));
            let range_limit = u32::from(PotentialCodePoint::from_unaligned(pair[1]));
            self.remove(prev, range_start);
            prev = range_limit;
        }
        self.remove(prev, (char::MAX as u32) + 1);
    }

    /// Computes the complement of the argument, adding any elements that do not yet exist in the builder,
    /// and removing any elements that already exist in the builder. See public functions for examples.
    ///
    /// Performs in `O(B + S)`, where `B` is the number of endpoints in the Builder, and `S` is the number
    /// of endpoints in the argument.
    fn complement_list(&mut self, set_iter: impl IntoIterator<Item = u32>) {
        let mut res: Vec<u32> = vec![]; // not the biggest fan of having to allocate new memory
        let mut ai = self.intervals.iter();
        let mut bi = set_iter.into_iter();
        let mut a = ai.next();
        let mut b = bi.next();
        while let (Some(c), Some(d)) = (a, b) {
            match c.cmp(&d) {
                Ordering::Less => {
                    res.push(*c);
                    a = ai.next();
                }
                Ordering::Greater => {
                    res.push(d);
                    b = bi.next();
                }
                Ordering::Equal => {
                    a = ai.next();
                    b = bi.next();
                }
            }
        }
        if let Some(c) = a {
            res.push(*c)
        }
        if let Some(d) = b {
            res.push(d)
        }
        res.extend(ai);
        res.extend(bi);
        self.intervals = res;
    }

    /// Computes the complement of the builder, inverting the builder (any elements in the builder are removed,
    /// while any elements not in the builder are added)
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::{
    ///     CodePointInversionList, CodePointInversionListBuilder,
    /// };
    /// let mut builder = CodePointInversionListBuilder::new();
    /// let set = CodePointInversionList::try_from_u32_inversion_list_slice(&[
    ///     0x0,
    ///     0x41,
    ///     0x46,
    ///     (std::char::MAX as u32) + 1,
    /// ])
    /// .unwrap();
    /// builder.add_set(&set);
    /// builder.complement();
    /// let check = builder.build();
    /// assert_eq!(check.iter_chars().next(), Some('A'));
    /// ```
    pub fn complement(&mut self) {
        if !self.intervals.is_empty() {
            #[allow(clippy::indexing_slicing)] // by invariant
            if self.intervals[0] == 0 {
                self.intervals.drain(0..1);
            } else {
                self.intervals.insert(0, 0);
            }
            if self.intervals.last() == Some(&(char::MAX as u32 + 1)) {
                self.intervals.pop();
            } else {
                self.intervals.push(char::MAX as u32 + 1);
            }
        } else {
            self.intervals
                .extend_from_slice(&[0, (char::MAX as u32 + 1)]);
        }
    }

    /// Complements the character in the builder, adding it if not in the builder, and removing it otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionListBuilder;
    /// let mut builder = CodePointInversionListBuilder::new();
    /// builder.add_range('A'..='D');
    /// builder.complement_char('A');
    /// builder.complement_char('E');
    /// let check = builder.build();
    /// assert!(check.contains('E'));
    /// assert!(!check.contains('A'));
    /// ```
    pub fn complement_char(&mut self, c: char) {
        self.complement32(c as u32);
    }

    /// See [`Self::complement_char`]
    pub fn complement32(&mut self, c: u32) {
        self.complement_list([c, c + 1]);
    }

    /// Complements the range in the builder, adding any elements in the range if not in the builder, and
    /// removing them otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionListBuilder;
    /// let mut builder = CodePointInversionListBuilder::new();
    /// builder.add_range('A'..='D');
    /// builder.complement_range('C'..='F');
    /// let check = builder.build();
    /// assert!(check.contains('F'));
    /// assert!(!check.contains('C'));
    /// ```
    pub fn complement_range(&mut self, range: impl RangeBounds<char>) {
        let (start, end) = deconstruct_range(range);
        self.complement_list([start, end]);
    }

    /// See [`Self::complement_range`]
    pub fn complement_range32(&mut self, range: impl RangeBounds<u32>) {
        let (start, end) = deconstruct_range(range);
        self.complement_list([start, end]);
    }

    /// Complements the set in the builder, adding any elements in the set if not in the builder, and
    /// removing them otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::{
    ///     CodePointInversionList, CodePointInversionListBuilder,
    /// };
    /// let mut builder = CodePointInversionListBuilder::new();
    /// let set = CodePointInversionList::try_from_u32_inversion_list_slice(&[
    ///     0x41, 0x46, 0x4B, 0x5A,
    /// ])
    /// .unwrap();
    /// builder.add_range('C'..='N'); // 67 - 78
    /// builder.complement_set(&set);
    /// let check = builder.build();
    /// assert!(check.contains('Q')); // 81
    /// assert!(!check.contains('N')); // 78
    /// ```
    pub fn complement_set(&mut self, set: &CodePointInversionList) {
        let inv_list_iter_owned = set.as_inversion_list().iter().map(u32::from);
        self.complement_list(inv_list_iter_owned);
    }

    /// Returns whether the build is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::collections::codepointinvlist::CodePointInversionListBuilder;
    /// let mut builder = CodePointInversionListBuilder::new();
    /// let check = builder.build();
    /// assert!(check.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.intervals.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::{CodePointInversionList, CodePointInversionListBuilder};
    use core::char;

    fn generate_tester(ex: &[u32]) -> CodePointInversionListBuilder {
        let check = CodePointInversionList::try_from_u32_inversion_list_slice(ex).unwrap();
        let mut builder = CodePointInversionListBuilder::new();
        builder.add_set(&check);
        builder
    }

    #[test]
    fn test_new() {
        let ex = CodePointInversionListBuilder::new();
        assert!(ex.intervals.is_empty());
    }

    #[test]
    fn test_build() {
        let mut builder = CodePointInversionListBuilder::new();
        builder.add(0x41, 0x42);
        let check: CodePointInversionList = builder.build();
        assert_eq!(check.iter_chars().next(), Some('A'));
    }

    #[test]
    fn test_empty_build() {
        let builder = CodePointInversionListBuilder::new();
        let check: CodePointInversionList = builder.build();
        assert!(check.is_empty());
    }

    #[test]
    fn test_add_to_empty() {
        let mut builder = CodePointInversionListBuilder::new();
        builder.add(0x0, 0xA);
        assert_eq!(builder.intervals, [0x0, 0xA]);
    }

    #[test]
    fn test_add_invalid() {
        let mut builder = CodePointInversionListBuilder::new();
        builder.add(0x0, 0x0);
        builder.add(0x5, 0x0);
        assert!(builder.intervals.is_empty());
    }

    #[test]
    fn test_add_to_start() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0x0, 0x5);
        let expected = [0x0, 0x5, 0xA, 0x14, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_to_start_overlap() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0x0, 0xE);
        let expected = [0x0, 0x14, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_to_end() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0x3C, 0x46);
        let expected = [0xA, 0x14, 0x28, 0x32, 60, 70];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_to_end_overlap() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0x2B, 0x46);
        let expected = [0xA, 0x14, 0x28, 0x46];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_to_middle_no_overlap() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0x19, 0x1B);
        let expected = [0xA, 0x14, 0x19, 0x1B, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_to_middle_inside() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0xA, 0x14);
        let expected = [0xA, 0x14, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_to_middle_left_overlap() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0xF, 0x19);
        let expected = [0xA, 0x19, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_to_middle_right_overlap() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0x1E, 0x28);
        let expected = [0xA, 0x14, 0x1E, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_to_full_encompass() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0x0, 0x3C);
        let expected = [0x0, 0x3C];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_to_partial_encompass() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0x0, 0x23);
        let expected = [0x0, 0x23, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_aligned_front() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(5, 10);
        let expected = [5, 0x14, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_aligned_back() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0x32, 0x37);
        let expected = [0xA, 0x14, 0x28, 0x37];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_aligned_start_middle() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0x14, 0x19);
        let expected = [0xA, 0x19, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_aligned_end_middle() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0x23, 0x28);
        let expected = [0xA, 0x14, 0x23, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_aligned_in_between_end() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x1E, 0x28, 0x32, 0x3C]);
        builder.add(0xF, 0x1E);
        let expected = [0xA, 0x28, 0x32, 0x3C];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_aligned_in_between_start() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x1E, 0x28, 0x32, 0x3C]);
        builder.add(20, 35);
        let expected = [0xA, 0x28, 0x32, 0x3C];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_adjacent_ranges() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.add(0x13, 0x14);
        builder.add(0x14, 0x15);
        builder.add(0x15, 0x16);
        let expected = [0xA, 0x16, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_codepointinversionlist() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        let check = CodePointInversionList::try_from_u32_inversion_list_slice(&[
            0x5, 0xA, 0x16, 0x21, 0x2C, 0x33,
        ])
        .unwrap();
        builder.add_set(&check);
        let expected = [0x5, 0x14, 0x16, 0x21, 0x28, 0x33];
        assert_eq!(builder.intervals, expected);
    }
    #[test]
    fn test_add_char() {
        let mut builder = CodePointInversionListBuilder::new();
        builder.add_char('a');
        let expected = [0x61, 0x62];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_range() {
        let mut builder = CodePointInversionListBuilder::new();
        builder.add_range('A'..='Z');
        let expected = [0x41, 0x5B];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_range32() {
        let mut builder = CodePointInversionListBuilder::new();
        builder.add_range32(0xd800..=0xdfff);
        let expected = [0xd800, 0xe000];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_add_invalid_range() {
        let mut builder = CodePointInversionListBuilder::new();
        builder.add_range('Z'..='A');
        assert!(builder.intervals.is_empty());
    }

    #[test]
    fn test_remove_empty() {
        let mut builder = CodePointInversionListBuilder::new();
        builder.remove(0x0, 0xA);
        assert!(builder.intervals.is_empty());
    }

    #[test]
    fn test_remove_entire_builder() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.remove(0xA, 0x32);
        assert!(builder.intervals.is_empty());
    }

    #[test]
    fn test_remove_entire_range() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.remove(0xA, 0x14);
        let expected = [0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_remove_partial_range_left() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.remove(0xA, 0x2B);
        let expected = [0x2B, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_remove_ne_range() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.remove(0x14, 0x28);
        let expected = [0xA, 0x14, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_remove_partial_range_right() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.remove(0xF, 0x37);
        let expected = [0xA, 0xF];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_remove_middle_range() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.remove(0xC, 0x12);
        let expected = [0xA, 0xC, 0x12, 0x14, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_remove_ne_middle_range() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.remove(0x19, 0x1B);
        let expected = [0xA, 0x14, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_remove_encompassed_range() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32, 70, 80]);
        builder.remove(0x19, 0x37);
        let expected = [0xA, 0x14, 0x46, 0x50];
        assert_eq!(builder.intervals, expected);
    }
    #[test]
    fn test_remove_adjacent_ranges() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.remove(0x27, 0x28);
        builder.remove(0x28, 0x29);
        builder.remove(0x29, 0x2A);
        let expected = [0xA, 0x14, 0x2A, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_remove_char() {
        let mut builder = generate_tester(&[0x41, 0x46]);
        builder.remove_char('A'); // 65
        let expected = [0x42, 0x46];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_remove_range() {
        let mut builder = generate_tester(&[0x41, 0x5A]);
        builder.remove_range('A'..'L'); // 65 - 76
        let expected = [0x4C, 0x5A];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_remove_set() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32, 70, 80]);
        let remove =
            CodePointInversionList::try_from_u32_inversion_list_slice(&[0xA, 0x14, 0x2D, 0x4B])
                .unwrap();
        builder.remove_set(&remove);
        let expected = [0x28, 0x2D, 0x4B, 0x50];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_retain_char() {
        let mut builder = generate_tester(&[0x41, 0x5A]);
        builder.retain_char('A'); // 65
        let expected = [0x41, 0x42];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_retain_range() {
        let mut builder = generate_tester(&[0x41, 0x5A]);
        builder.retain_range('C'..'F'); // 67 - 70
        let expected = [0x43, 0x46];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_retain_range_empty() {
        let mut builder = generate_tester(&[0x41, 0x46]);
        builder.retain_range('F'..'Z');
        assert!(builder.intervals.is_empty());
    }

    #[test]
    fn test_retain_set() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32, 70, 80]);
        let retain = CodePointInversionList::try_from_u32_inversion_list_slice(&[
            0xE, 0x14, 0x19, 0x37, 0x4D, 0x51,
        ])
        .unwrap();
        builder.retain_set(&retain);
        let expected = [0xE, 0x14, 0x28, 0x32, 0x4D, 0x50];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_complement() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.complement();
        let expected = [0x0, 0xA, 0x14, 0x28, 0x32, (char::MAX as u32) + 1];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_complement_empty() {
        let mut builder = generate_tester(&[]);
        builder.complement();
        let expected = [0x0, (char::MAX as u32) + 1];
        assert_eq!(builder.intervals, expected);

        builder.complement();
        let expected: [u32; 0] = [];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_complement_zero_max() {
        let mut builder = generate_tester(&[0x0, 0xA, 0x5A, (char::MAX as u32) + 1]);
        builder.complement();
        let expected = [0xA, 0x5A];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_complement_interior() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.complement_list([0xE, 0x14]);
        let expected = [0xA, 0xE, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_complement_exterior() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.complement_list([0x19, 0x23]);
        let expected = [0xA, 0x14, 0x19, 0x23, 0x28, 0x32];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_complement_larger_list() {
        let mut builder = generate_tester(&[0xA, 0x14, 0x28, 0x32]);
        builder.complement_list([0x1E, 0x37, 0x3C, 0x46]);
        let expected = [0xA, 0x14, 0x1E, 0x28, 0x32, 0x37, 0x3C, 0x46];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_complement_char() {
        let mut builder = generate_tester(&[0x41, 0x4C]); // A - K
        builder.complement_char('A');
        builder.complement_char('L');
        let expected = [0x42, 0x4D];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_complement_range() {
        let mut builder = generate_tester(&[0x46, 0x4C]); // F - K
        builder.complement_range('A'..='Z');
        let expected = [0x41, 0x46, 0x4C, 0x5B];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_complement_set() {
        let mut builder = generate_tester(&[0x43, 0x4E]);
        let set =
            CodePointInversionList::try_from_u32_inversion_list_slice(&[0x41, 0x46, 0x4B, 0x5A])
                .unwrap();
        builder.complement_set(&set);
        let expected = [0x41, 0x43, 0x46, 0x4B, 0x4E, 0x5A];
        assert_eq!(builder.intervals, expected);
    }

    #[test]
    fn test_is_empty() {
        let builder = CodePointInversionListBuilder::new();
        assert!(builder.is_empty());
    }
}