mkwebfont_hb-subset 0.5.0

A wrapper for HarfBuzz font subsetting API
Documentation
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
//! Set represents a mathematical set of integer values.
//!
//! While set in this module can be used as a general-purpose set in Rust code, it is recommended that you instead use
//! [`std::collections::BTreeSet`] or [`std::collections::HashSet`] as those are implemented directly in Rust and do not
//! rely on FFI to work.
//!
//! Sets are used in HarfBuzz in some non-shaping APIs to query certain sets of characters or glyphs, or other integer
//! values.

use std::{
    any::TypeId,
    fmt,
    hash::Hash,
    iter::{FilterMap, FusedIterator},
    marker::PhantomData,
    ops::{Bound, RangeBounds},
};

use crate::{sys, AllocationError, Tag};

/// Set objects represent a mathematical set of integer values.
pub struct Set<'a, T>(InnerSet, PhantomData<(&'a (), T)>);

impl<T> Set<'static, T> {
    /// Creates a new, initially empty set.
    #[doc(alias = "hb_set_create")]
    pub fn new() -> Result<Self, AllocationError> {
        let set = unsafe { sys::hb_set_create() };
        if set.is_null() {
            return Err(AllocationError);
        }
        Ok(Self(InnerSet(set), PhantomData))
    }
}

impl<'a, T> Set<'a, T> {
    /// Tests whether set is empty i.e. contains no elements.
    #[doc(alias = "hb_set_is_empty")]
    pub fn is_empty(&self) -> bool {
        (unsafe { sys::hb_set_is_empty(self.as_raw()) }) != 0
    }

    /// Returns the number of elements in the set.
    ///
    /// Note that this returns the number of elements in the underlying raw set over [`u32`], *not* the number of
    /// elements that can be represented as `T`. This is especially evident when the set is over [`char`]s and invalid
    /// code points have been added with [`Self::insert_range`].
    /// ```
    /// # use hb_subset::set::CharSet;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut set = CharSet::new()?;
    /// set.insert_range('\u{D7FF}'..'\u{E000}'); // Add all surrogate pairs (and \u{D7FF} for technical reasons)
    /// assert_eq!(set.len(), 2049);
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "hb_set_get_population")]
    pub fn len(&self) -> usize {
        (unsafe { sys::hb_set_get_population(self.as_raw()) }) as usize
    }

    /// Clears out the contents of a set.
    #[doc(alias = "hb_set_clear")]
    pub fn clear(&mut self) {
        unsafe { sys::hb_set_clear(self.as_raw()) }
    }

    /// Makes the contents of `self` equal to the contents of `other`.
    #[doc(alias = "hb_set_set")]
    pub fn copy_from(&mut self, other: &Self) {
        unsafe { sys::hb_set_set(self.as_raw(), other.as_raw()) }
    }

    /// Tests whether `self` contains `other` set.
    #[doc(alias = "hb_set_is_subset")]
    pub fn contains_set(&self, other: &Self) -> bool {
        (unsafe { sys::hb_set_is_subset(other.as_raw(), self.as_raw()) }) != 0
    }

    /// Constructs a copy of the set with `'static` lifetime.
    #[doc(alias = "hb_set_copy")]
    pub fn clone_static(&self) -> Set<'static, T> {
        Set(InnerSet(unsafe { sys::hb_set_copy(self.as_raw()) }), PhantomData)
    }
}

impl<'a, T> Set<'a, T>
where T: Into<u32>
{
    /// Tests whether a value belongs to set.
    #[doc(alias = "hb_set_has")]
    pub fn contains(&self, value: T) -> bool {
        (unsafe { sys::hb_set_has(self.as_raw(), value.into()) }) != 0
    }

    /// Inserts a value to set.
    ///
    /// # Panics
    ///
    /// Will panic if `value` is [`sys::HB_SET_VALUE_INVALID`].
    #[doc(alias = "hb_set_add")]
    pub fn insert(&mut self, value: T) {
        let value = value.into();
        assert_ne!(value, sys::HB_SET_VALUE_INVALID);
        unsafe { sys::hb_set_add(self.as_raw(), value) }
    }

    /// Removes a value from set.
    #[doc(alias = "hb_set_del")]
    pub fn remove(&mut self, value: T) {
        unsafe { sys::hb_set_del(self.as_raw(), value.into()) }
    }

    /// Converts a range to inclusive bounds.
    fn range_to_bounds(range: impl RangeBounds<T>) -> Option<(u32, u32)>
    where T: Clone + 'static {
        fn bound_to_u32<T: Clone + Into<u32>>(bound: Bound<&T>) -> Bound<u32> {
            match bound {
                Bound::Included(b) => Bound::Included(b.clone().into()),
                Bound::Excluded(b) => Bound::Excluded(b.clone().into()),
                Bound::Unbounded => Bound::Unbounded,
            }
        }
        let lower = match bound_to_u32(range.start_bound()) {
            Bound::Included(lower) => lower,
            Bound::Excluded(lower) => {
                if lower == u32::MAX {
                    return None;
                } else {
                    lower + 1
                }
            }
            Bound::Unbounded => 0,
        };
        let upper = match bound_to_u32(range.end_bound()) {
            Bound::Included(upper) => {
                assert_ne!(upper, sys::HB_SET_VALUE_INVALID);
                upper
            }
            Bound::Excluded(upper) => {
                if upper == 0 {
                    return None;
                } else {
                    upper - 1
                }
            }
            Bound::Unbounded => {
                // Optimization to allow half-open intervals with character sets
                if TypeId::of::<T>() == TypeId::of::<char>() {
                    char::MAX as u32
                } else {
                    u32::MAX - 1
                }
            }
        };
        if upper < lower {
            return None;
        }
        Some((lower, upper))
    }

    /// Inserts a range of values to set.
    ///
    /// # Panics
    ///
    /// Will panic if `range` explicitly contains [`sys::HB_SET_VALUE_INVALID`]:
    /// ```should_panic
    /// # use hb_subset::set::U32Set;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// U32Set::new()?.insert_range(u32::MAX-10..=u32::MAX);
    /// # Ok(())
    /// # }
    /// ```
    /// These still work:
    /// ```
    /// # use hb_subset::set::U32Set;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// U32Set::new()?.insert_range(u32::MAX-10..);
    /// U32Set::new()?.insert_range(u32::MAX-10..u32::MAX);
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "hb_set_add_range")]
    pub fn insert_range(&mut self, range: impl RangeBounds<T>)
    where T: Clone + 'static {
        let Some((lower, upper)) = Self::range_to_bounds(range) else {
            return;
        };
        unsafe { sys::hb_set_add_range(self.as_raw(), lower, upper) }
    }

    /// Removes a range of values from set.
    #[doc(alias = "hb_set_del_range")]
    pub fn remove_range(&mut self, range: impl RangeBounds<T>)
    where T: Clone + 'static {
        // TODO: Assert that sys::HB_SET_VALUE_INVALID is u32::MAX like it should be
        #[allow(clippy::assertions_on_constants, clippy::absurd_extreme_comparisons)]
        const _: () = assert!(u32::MAX <= sys::HB_SET_VALUE_INVALID);
        let Some((lower, upper)) = Self::range_to_bounds(range) else {
            return;
        };
        unsafe { sys::hb_set_del_range(self.as_raw(), lower, upper) }
    }
}

impl<'a, T> Set<'a, T>
where T: TryFrom<u32>
{
    /// Constructs an iterator over the set.
    #[doc(alias = "hb_set_next")]
    #[doc(alias = "hb_set_previous")]
    pub fn iter(&self) -> Iter<'_, 'a, T> {
        Iter(IterImpl::new(self).filter_map(|v| v.try_into().ok()))
    }
}

impl<'a, T> Set<'a, T> {
    /// Converts the set into raw [`sys::hb_set_t`] pointer.
    ///
    /// This method transfers the ownership of the set to the caller. It is up to the caller to call
    /// [`sys::hb_set_destroy`] to free the pointer, or call [`Self::from_raw`] to convert it back into [`Set`].
    pub fn into_raw(self) -> *mut sys::hb_set_t {
        let ptr = self.0 .0;
        std::mem::forget(self);
        ptr
    }

    /// Exposes the raw inner pointer without transferring the ownership.
    ///
    /// Unlike [`Self::into_raw`], this method does not transfer the ownership of the pointer to the caller.
    pub fn as_raw(&self) -> *mut sys::hb_set_t {
        self.0 .0
    }

    /// Constructs a set from raw [`sys::hb_set_t`] pointer.
    ///
    /// # Safety
    /// The given `set` pointer must either be constructed by some Harfbuzz function, or be returned from
    /// [`Self::into_raw`].
    pub unsafe fn from_raw(set: *mut sys::hb_set_t) -> Self {
        Self(InnerSet(set), PhantomData)
    }
}

impl<'a, T> Hash for Set<'a, T> {
    #[doc(alias = "hb_set_hash")]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        unsafe { sys::hb_set_hash(self.as_raw()) }.hash(state);
    }
}

impl<'a, T> PartialEq for Set<'a, T> {
    #[doc(alias = "hb_set_is_equal")]
    fn eq(&self, other: &Self) -> bool {
        (unsafe { sys::hb_set_is_equal(self.as_raw(), other.as_raw()) }) != 0
    }
}

impl<'a, T> Eq for Set<'a, T> where T: Eq {}

impl<'a, T> Clone for Set<'a, T> {
    fn clone(&self) -> Self {
        self.clone_static()
    }
}

impl<'a, T> fmt::Debug for Set<'a, T>
where T: TryFrom<u32> + fmt::Debug
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self).finish()
    }
}

impl<'a, T> FromIterator<T> for Set<'a, T>
where T: Into<u32>
{
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut set = Set::new().unwrap();
        for item in iter {
            set.insert(item);
        }
        set
    }
}

impl<'s, 'a, T> IntoIterator for &'s Set<'a, T>
where T: TryFrom<u32>
{
    type Item = T;
    type IntoIter = Iter<'s, 'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Iterator over [`Set`].
///
/// Use [`Set::iter`] to construct a [`Iter`].
pub struct Iter<'s, 'a, T>(IterFilter<'s, 'a, T>);
type IterFilter<'s, 'a, T> = FilterMap<IterImpl<'s, 'a, T>, fn(u32) -> Option<T>>;

impl<'s, 'a, T> Iterator for Iter<'s, 'a, T>
where T: TryFrom<u32>
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

impl<'s, 'a, T> DoubleEndedIterator for Iter<'s, 'a, T>
where T: TryFrom<u32>
{
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back()
    }
}

impl<'s, 'a, T> FusedIterator for Iter<'s, 'a, T> where T: TryFrom<u32> {}

/// Actual implementation for [`Iter`].
///
/// This implementation does not care whether the target type can or cannot represent the target type. It just returns
/// [`u32`], no matter what. [`Iter`] is responsible to then filter out invalid values.
struct IterImpl<'s, 'a, T>(&'s Set<'a, T>, u32, u32);

impl<'s, 'a, T> IterImpl<'s, 'a, T> {
    const LAST_VALUE: u32 = sys::HB_SET_VALUE_INVALID - 1;
    fn new(set: &'s Set<'a, T>) -> Self {
        #[allow(clippy::assertions_on_constants, clippy::absurd_extreme_comparisons)]
        const _: () = assert!(u32::MAX == sys::HB_SET_VALUE_INVALID);
        Self(set, sys::HB_SET_VALUE_INVALID, sys::HB_SET_VALUE_INVALID)
    }

    fn mark_ended(&mut self) {
        self.1 = Self::LAST_VALUE;
        self.2 = 0;
    }
}

impl<'s, 'a, T> Iterator for IterImpl<'s, 'a, T> {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        match self.1 {
            Self::LAST_VALUE => {
                // Previously last possible value was returned, so the iterator must have been exhausted
                None
            }
            _ => {
                let has_value =
                    (unsafe { sys::hb_set_next(self.0.as_raw(), &mut self.1 as *mut u32) }) != 0;
                if has_value {
                    if self.1 >= self.2 {
                        self.mark_ended();
                        None
                    } else {
                        Some(self.1)
                    }
                } else {
                    self.mark_ended();
                    None
                }
            }
        }
    }
}

impl<'s, 'a, T> DoubleEndedIterator for IterImpl<'s, 'a, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        match self.2 {
            0 => {
                // 0 has been returned, so nothing can be returned from this iterator anymore
                None
            }
            _ => {
                let has_value =
                    (unsafe { sys::hb_set_previous(self.0.as_raw(), &mut self.2 as *mut u32) })
                        != 0;
                if has_value {
                    if self.1 != sys::HB_SET_VALUE_INVALID && self.1 >= self.2 {
                        self.mark_ended();
                        None
                    } else {
                        Some(self.2)
                    }
                } else {
                    self.mark_ended();
                    None
                }
            }
        }
    }
}

/// Implementation detail of Set to hide source reference from drop check.
///
/// If the pointer was directly contained in [`Set`] with `Drop` implemented, the following code would not compile:
/// ```
/// # use hb_subset::*;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut subset = SubsetInput::new()?;
/// let mut unicode_set = subset.unicode_set();
/// // drop(unicode_set);                               // This needs to be called to delete unicode_set,
/// # let font = FontFace::new(Blob::from_bytes(&[])?)?;
/// let new_font = subset.subset_font(&font)?;  // otherwise this line would not compile as unicode_set is already
///                                                     // holding a mutable reference to subset.
/// # Ok(())
/// # }
/// ```
struct InnerSet(*mut sys::hb_set_t);

impl Drop for InnerSet {
    #[doc(alias = "hb_set_destroy")]
    fn drop(&mut self) {
        unsafe { sys::hb_set_destroy(self.0) }
    }
}

/// Set over unicodecode points.
pub type CharSet<'a> = Set<'a, char>;

/// Set over [`u32`]s, except [`u32::MAX`].
///
/// Trying to insert [`u32::MAX`] will cause a panic. [`U32Set`] is commonly used to represent sets of glyph IDs.
pub type U32Set<'a> = Set<'a, u32>;

/// Set over [`Tag`]s.
pub type TagSet<'a> = Set<'a, Tag>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_empty_works() {
        let mut set = U32Set::new().unwrap();
        assert!(set.is_empty());
        assert!(set.is_empty());
        set.insert(10);
        assert!(!set.is_empty());
        set.insert(20);
        assert!(!set.is_empty());
        set.remove(10);
        assert!(!set.is_empty());
        set.remove(20);
        assert!(set.is_empty());
    }

    #[test]
    fn len_works() {
        let mut set = U32Set::new().unwrap();
        assert_eq!(set.len(), 0);
        set.insert(10);
        assert_eq!(set.len(), 1);
        set.insert_range(5..15);
        assert_eq!(set.len(), 10);
        set.remove(13);
        assert_eq!(set.len(), 9);
    }

    #[test]
    fn clear_empties_set() {
        let mut set = U32Set::new().unwrap();
        set.insert_range(123..456);
        assert!(!set.is_empty());
        assert_eq!(set.len(), 333);
        set.clear();
        assert!(set.is_empty());
        assert_eq!(set.len(), 0);
    }

    #[test]
    #[should_panic]
    fn cannot_insert_u32_max() {
        let mut set = U32Set::new().unwrap();
        set.insert(u32::MAX);
    }

    #[test]
    #[should_panic]
    fn cannot_insert_range_u32_max() {
        let mut set = U32Set::new().unwrap();
        set.insert_range(..=u32::MAX);
    }

    #[test]
    fn does_not_contain_u32_max() {
        let mut set = U32Set::new().unwrap();
        set.insert_range(..);
        assert!(!set.contains(u32::MAX));
    }

    #[test]
    fn can_contain_max_value() {
        let mut set = U32Set::new().unwrap();
        set.insert(u32::MAX - 1);
        assert!(set.contains(u32::MAX - 1));
        assert!(!set.is_empty());
        assert_eq!(set.len(), 1);
    }

    #[test]
    fn copy_from_works() {
        let mut a = U32Set::new().unwrap();
        a.insert(5);
        let mut b = U32Set::new().unwrap();
        b.insert(10);
        assert_eq!(a.iter().collect::<Vec<_>>(), [5]);
        assert_eq!(b.iter().collect::<Vec<_>>(), [10]);
        a.copy_from(&b);
        assert_eq!(a.iter().collect::<Vec<_>>(), [10]);
        b.insert(1);
        assert_eq!(a.iter().collect::<Vec<_>>(), [10]);
        a.remove(10);
        assert_eq!(b.iter().collect::<Vec<_>>(), [1, 10]);
    }

    #[test]
    fn contains_its_subset() {
        let mut a = U32Set::new().unwrap();
        a.insert_range(5..=15);
        a.insert_range(55..=65);
        assert!(a.contains_set(&a));
        let mut b = U32Set::new().unwrap();
        b.insert_range(7..=14);
        b.insert(60);
        assert!(b.contains_set(&b));
        assert!(a.contains_set(&b));
        assert!(!b.contains_set(&a));
        b.insert(65);
        assert!(a.contains_set(&b));
        b.insert(66);
        assert!(!a.contains_set(&b));
        assert!(!b.contains_set(&a));
    }

    #[test]
    fn contains_inserted_values() {
        let mut set = U32Set::new().unwrap();
        set.insert(1);
        assert!(!set.contains(3));
        set.insert(1);
        assert!(!set.contains(3));
        set.insert(3);
        assert!(set.contains(3));
        set.remove(1);
        assert!(set.contains(3));
        set.remove(3);
        assert!(!set.contains(3));
    }

    #[test]
    fn range_insertions_and_deletions_work() {
        let mut set = U32Set::new().unwrap();
        set.insert_range(0..100);
        assert_eq!(set.len(), 100);
        set.remove_range(21..=30);
        assert_eq!(set.len(), 90);
        set.remove_range(90..200);
        assert_eq!(set.len(), 80);
    }

    #[test]
    fn convert_into_raw_and_back() {
        let set = U32Set::new().unwrap();
        let set_ptr = set.into_raw();
        let set = unsafe { U32Set::from_raw(set_ptr) };
        drop(set);
    }

    #[test]
    fn equal_works() {
        let mut a = U32Set::new().unwrap();
        for i in 0..10 {
            a.insert(i);
        }
        assert_eq!(a, a);
        let mut b = U32Set::new().unwrap();
        assert_ne!(a, b);
        b.insert_range(0..10);
        assert_eq!(a, b);
    }

    #[test]
    fn debug_works() {
        let mut set = U32Set::new().unwrap();
        set.insert_range(3..=5);
        set.insert(7);
        let mut str = String::new();
        use fmt::Write;
        write!(&mut str, "{set:?}").unwrap();
        assert_eq!(str, "{3, 4, 5, 7}");
    }

    #[test]
    fn cloned_set_does_not_modify_original() {
        let mut a = U32Set::new().unwrap();
        a.insert(3);
        a.insert(5);
        let mut b = a.clone();
        assert_eq!(a.len(), 2);
        assert_eq!(b.len(), 2);
        a.insert(10);
        assert_eq!(a.len(), 3);
        assert_eq!(b.len(), 2);
        b.remove(3);
        assert_eq!(a.len(), 3);
        assert_eq!(b.len(), 1);
    }

    #[test]
    fn iter_works() {
        let mut set = U32Set::new().unwrap();
        assert!(set.iter().next().is_none());
        set.insert(0);
        assert_eq!(set.iter().collect::<Vec<_>>(), [0]);
        set.insert(0);
        assert_eq!(set.iter().collect::<Vec<_>>(), [0]);
        set.insert(10);
        assert_eq!(set.iter().collect::<Vec<_>>(), [0, 10]);
        set.insert_range(6..12);
        assert_eq!(set.iter().collect::<Vec<_>>(), [0, 6, 7, 8, 9, 10, 11]);
        set.remove_range(8..=10);
        assert_eq!(set.iter().collect::<Vec<_>>(), [0, 6, 7, 11]);
    }

    #[test]
    fn iter_near_max_works() {
        let mut set = U32Set::new().unwrap();
        set.insert(u32::MAX - 3);
        set.insert(u32::MAX - 2);
        assert_eq!(set.iter().collect::<Vec<_>>(), [u32::MAX - 3, u32::MAX - 2]);
        set.insert(u32::MAX - 1);
        assert_eq!(set.iter().collect::<Vec<_>>(), [u32::MAX - 3, u32::MAX - 2, u32::MAX - 1]);
        set.clear();
        assert!(set.is_empty());
        set.insert_range((Bound::Excluded(u32::MAX - 3), Bound::Unbounded));
        assert_eq!(set.iter().collect::<Vec<_>>(), [u32::MAX - 2, u32::MAX - 1]);
    }

    #[test]
    fn iter_of_invalid_codepoints_works() {
        let mut set = CharSet::new().unwrap();
        set.insert_range('\u{D7FF}'..'\u{E001}'); // Add all surrogate pairs, and then some
        assert_eq!(set.iter().collect::<Vec<_>>(), ['\u{D7FF}', '\u{E000}']);

        let mut set = CharSet::new().unwrap();
        set.insert_range('\u{10FFFF}'..);
        assert_eq!(set.iter().collect::<Vec<_>>(), ['\u{10FFFF}']);
    }

    #[test]
    fn iter_is_fused() {
        fn assert_fused(mut iter: impl Iterator) {
            while let Some(_) = iter.next() {}
            for _ in 0..10 {
                assert!(iter.next().is_none());
            }
            // Believe that iterator is fused after it has returned 11 Nones
        }
        let mut set = U32Set::new().unwrap();
        assert_fused(set.iter());
        assert_fused(set.iter().rev());
        set.insert(0);
        assert_fused(set.iter());
        assert_fused(set.iter().rev());
        set.insert(1);
        assert_fused(set.iter());
        assert_fused(set.iter().rev());
        set.insert(u32::MAX - 3);
        assert_fused(set.iter());
        assert_fused(set.iter().rev());
        set.insert(u32::MAX - 2);
        assert_fused(set.iter());
        assert_fused(set.iter().rev());
        set.insert(u32::MAX - 1);
        assert_fused(set.iter());
        assert_fused(set.iter().rev());

        let mut iter = set.iter();
        assert_eq!(iter.next_back(), Some(u32::MAX - 1));
        assert_fused(iter);

        let mut iter = set.iter().rev();
        assert_eq!(iter.next_back(), Some(0));
        assert_fused(iter);
    }

    #[test]
    fn iter_next_back_works() {
        let mut set = U32Set::new().unwrap();
        assert!(set.iter().next().is_none());
        set.insert(0);
        set.insert_range(6..12);
        assert_eq!(set.iter().rev().collect::<Vec<_>>(), [11, 10, 9, 8, 7, 6, 0]);
        set.remove_range(8..=10);
        assert_eq!(set.iter().rev().collect::<Vec<_>>(), [11, 7, 6, 0]);

        let mut iter = set.iter();
        assert_eq!(iter.next(), Some(0));
        assert_eq!(iter.next_back(), Some(11));
        assert_eq!(iter.next_back(), Some(7));
        assert_eq!(iter.next(), Some(6));
        assert_eq!(iter.next(), None);
        assert_eq!(iter.next_back(), None);

        let mut iter = set.iter();
        assert_eq!(iter.next_back(), Some(11));
        assert_eq!(iter.next_back(), Some(7));
        assert_eq!(iter.next(), Some(0));
        assert_eq!(iter.next(), Some(6));
        assert_eq!(iter.next_back(), None);
        assert_eq!(iter.next(), None);

        let mut iter = set.iter();
        assert_eq!(iter.next_back(), Some(11));
        assert_eq!(iter.next_back(), Some(7));
        assert_eq!(iter.next(), Some(0));
        assert_eq!(iter.next_back(), Some(6));
        assert_eq!(iter.next_back(), None);
        assert_eq!(iter.next(), None);

        let mut iter = set.iter();
        assert_eq!(iter.next_back(), Some(11));
        assert_eq!(iter.next_back(), Some(7));
        assert_eq!(iter.next(), Some(0));
        assert_eq!(iter.next_back(), Some(6));
        assert_eq!(iter.next(), None);
        assert_eq!(iter.next_back(), None);
    }
}