closed_interval_set/
lib.rs

1//! The `closed_interval_set` crate manipulates disjoint unions of
2//! closed intervals that are represented as vectors ([`RangeVec`]) or
3//! iterators ([`NormalizedRangeIter`]) of pairs of endpoints.  These
4//! intervals are always closed (inclusive at both ends), so the
5//! crate can naturally represent both the empty set (no interval),
6//! and the universe (a closed interval from min to max).
7//!
8//! The crate is designed for usage patterns where sets are
9//! constructed ahead of time (perhaps by combining different sets
10//! together), then frozen (as vectors, internally) for read-only
11//! access.  That said, its iterator implementations of set
12//! [complementation](`NormalizedRangeIter::complement`),
13//! [union](`NormalizedRangeIter::union`), and
14//! [intersection](`NormalizedRangeIter::intersect`) are closed over
15//! the [`NormalizedRangeIter`] trait, so it's reasonable to build up
16//! complex expressions of type-erased [`NormalizedRangeIter`]s
17//! before materializing the result to a [`RangeVec`].
18//!
19//! Using this crate usually starts by constructing [`Vec`]s of closed
20//! ranges (of pairs of [`Endpoint`]s), and passing that to
21//! [`RangeVec::from_vec`].  From that point, we have access to the
22//! set operations on [`RangeVec`] and [`NormalizedRangeIter`].  The
23//! toplevel functions (e.g., [`intersect_vec`] and [`normalize_vec`])
24//! may be helpful to avoid excessive chaining or in subtle
25//! situations, e.g., when the compiler knows whether the input is a
26//! [`RangeVec`] or a [`Vec`] (or [`SmallVec`]) but it's annoying to
27//! track by hand.
28//!
29//! Complementation is tricky when one handles only closed intervals.
30//! We assume [`Endpoint`] types can enumerate values in total order
31//! via [`Endpoint::decrease_toward`] and [`Endpoint::increase_toward`].
32//! That's nonsense for [densely ordered sets](https://en.wikipedia.org/wiki/Dense_order)
33//! like \\(\mathbb{Q},\\) but tends to work OK on computers: it's trivial
34//! to enumerate bounded integers, and there is such a total order for
35//! the finite set of floating point values.  Mathematically, this sorted
36//! enumeration of floating point values makes no sense, nevertheless,
37//! it can be useful in some domains, e.g., static program analysis.
38//!
39//! All operations take at most linear space and \\(\mathcal{O}(n \log
40//! n)\\) time, where \\(n\\) is the total number of ranges in all the
41//! inputs, before any normalization (simplification).  Set operations
42//! on [`NormalizedRangeIter`] always use constant space, and many
43//! operations on [`RangeVec`] reuse storage.
44//!
45//! The container type ([`SmallVec`]`<[_; 2]>`) is hardcoded, for
46//! simplicity.  The [`Endpoint`] trait, however, is fully generic.
47//! This crate comes with implementations of [`Endpoint`] for all
48//! primitive fixed-width integer types ([`i8`], [`i16`], [`i32`], [`i64`],
49//! [`i128`], [`u8`], [`u16`], [`u32`], [`u64`] and [`u128`]), for
50//! [`isize`] and [`usize`], and for the standard floating point
51//! types [`f32`] and [`f64`] (from \\(-\infty\\) to \\(+\infty\\),
52//! with \\(-0\\) and \\(+0\\) as distinct values, and excluding NaNs).
53//!
54//! [`SmallVec`]: https://docs.rs/smallvec/latest/smallvec/struct.SmallVec.html
55//! [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
56
57#![deny(missing_docs)]
58// https://github.com/taiki-e/cargo-llvm-cov?tab=readme-ov-file#exclude-code-from-coverage
59#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
60// `cargo build --target thumbv6m-none-eabi` is (maybe?) a decent way to check we don't
61// indirectly use the full stdlib.
62#![cfg_attr(not(test), no_std)]
63extern crate alloc; // for `alloc::Vec`
64
65use smallvec::SmallVec;
66
67mod complement;
68mod intersection;
69mod intersection_iterator;
70pub mod iterator_wrapper;
71mod normalize;
72mod primitive_endpoint;
73mod range_case;
74mod range_vec;
75mod slice_sequence;
76mod union;
77mod union_iterator;
78
79pub use range_case::RangeCase;
80pub use range_vec::RangeVec;
81
82pub use normalize::is_normalized;
83pub use normalize::normalize_vec;
84
85pub use complement::complement_vec;
86pub use intersection::intersect_vec;
87pub use union::union_vec;
88
89/// Inline storage (in ranges) reserved in a [`RangeVec`].
90///
91/// Controlled by the `inline_storage` feature, which is enabled by
92/// default.  When the `inline_storage` feature is *not* enabled,
93/// this constant is set to 0.
94pub const INLINE_SIZE: usize = if cfg!(feature = "inline_storage") {
95    2
96} else {
97    0
98};
99
100/// Our internal storage type for [`RangeVec`].
101type Backing<T> = SmallVec<[(T, T); INLINE_SIZE]>;
102
103/// An [`Endpoint`] is the left or right limit of a closed interval
104/// `[left, right]`.
105///
106/// [`Endpoint`] types must have maximum and minimum values.  For
107/// bounded integer types, that's simply `T::MIN` or `T::MAX`;
108/// in general, types may have to be extended, just like floating
109/// point values have +/- infinity.
110///
111/// [`Endpoint`] types must also be enumerable in both ascending and
112/// descending order.
113///
114/// There is an implementation for all 10 primitive fixed-width
115/// integer types (signed/unsigned 8, 16, 32, 64, and 128 bits), for
116/// [`isize`] and [`usize`], and for the IEEE floating point types
117/// [`f32`] and [`f64`].
118pub trait Endpoint: Copy {
119    /// The minimum value for values of type [`Endpoint`]:
120    ///
121    /// \\[ \forall x : \mathtt{Self}, x \geq \mathtt{Self::min\\_value}() \\]
122    fn min_value() -> Self;
123
124    /// The maximum value for values of type [`Endpoint`]:
125    ///
126    /// \\[ \forall x : \mathtt{Self}, x \leq \mathtt{Self::max\\_value}() \\]
127    fn max_value() -> Self;
128
129    /// Returns whether `self` is comparable.
130    fn is_valid(self) -> bool;
131
132    /// Compares `self <=> other`.  Both `self` and `other` are
133    /// guaranteed to satisfy [`Endpoint::is_valid()`].
134    /// Implementations may return an arbitrary ordering if that's not
135    /// the case.
136    ///
137    /// See [`core::cmp::Ord`]
138    fn cmp_end(self, other: Self) -> core::cmp::Ordering;
139
140    /// Returns the minimum [`Endpoint`] value strictly
141    /// greater than `self`, or `None` if there is no
142    /// such value (iff `self == Self::max_value()`).
143    ///
144    /// \\[ \forall \mathtt{self}, x: \mathtt{Self}, x > \mathtt{self} \Rightarrow x \geq \mathtt{self.next\\_after}() \\]
145    #[inline(always)]
146    fn next_after(self) -> Option<Self> {
147        self.increase_toward(Self::max_value())
148    }
149
150    /// Returns the maximum [`Endpoint`] value strictly
151    /// less than `self`, or `None` if there is no
152    /// such value (iff `self == Self::min_value()`).
153    ///
154    /// \\[ \forall \mathtt{self}, x: \mathtt{Self}, x < \mathtt{self} \Rightarrow x \leq \mathtt{self.prev\\_before}() \\]
155    #[inline(always)]
156    fn prev_before(self) -> Option<Self> {
157        self.decrease_toward(Self::min_value())
158    }
159
160    /// Returns [`prev_before()`] iff `other < self`, and [`None`]
161    /// otherwise.
162    ///
163    /// In practice, it's usually easier to directly implement this
164    /// method instead of [`prev_before()`] (`other < self` guarantees
165    /// there is a previous value for `self`), so [`prev_before()`] is
166    /// implemented in terms of [`Self::decrease_toward()`].
167    ///
168    /// [`prev_before()`]: `Self::prev_before`
169    fn decrease_toward(self, other: Self) -> Option<Self>;
170
171    /// Returns [`next_after()`] iff `other > self`, and [`None`]
172    /// otherwise.
173    ///
174    /// In practice, it's usually easier to directly implement this
175    /// method instead of [`next_after()`] (`other > self` guarantees
176    /// there is a next value for `self`), so [`next_after()`] is
177    /// implemented in terms of [`Self::increase_toward()`].
178    ///
179    /// [`next_after()`]: `Self::next_after`
180    fn increase_toward(self, other: Self) -> Option<Self>;
181
182    /// Compares two ranges of endpoints.
183    #[doc(hidden)]
184    #[inline(always)]
185    fn cmp_range(left: (Self, Self), right: (Self, Self)) -> core::cmp::Ordering {
186        match left.0.cmp_end(right.0) {
187            core::cmp::Ordering::Equal => left.1.cmp_end(right.1),
188            any => any,
189        }
190    }
191
192    /// Returns the max of two endpoints.
193    #[doc(hidden)]
194    #[inline(always)]
195    fn bot_end(self, other: Self) -> Self {
196        core::cmp::min_by(self, other, |x, y| Self::cmp_end(*x, *y))
197    }
198
199    /// Returns the min of two endpoints.
200    #[doc(hidden)]
201    #[inline(always)]
202    fn top_end(self, other: Self) -> Self {
203        core::cmp::max_by(self, other, |x, y| Self::cmp_end(*x, *y))
204    }
205}
206
207/// We represent closed ranges as pairs of [`Endpoint`]s.
208type Pair<T> = (T, T);
209
210mod private {
211    pub trait Sealed {}
212}
213
214/// A [`ClosedRange`] represents a closed range of values with pairs
215/// of [`Endpoint`]s.
216///
217/// This trait stands for `(T, T)` `&(T, T)`, where `T` implements
218/// [`Endpoint`].
219///
220/// The [`ClosedRange`] trait is sealed and cannot be implemented for
221/// types outside this crate.  External code *may* have to write down
222/// the trait's name, but most likely shouldn't try to actually invoke
223/// any method on that trait.
224pub trait ClosedRange: Copy + private::Sealed {
225    /// The type of the endpoints for this range.
226    #[doc(hidden)]
227    type EndT: Endpoint;
228
229    /// Returns a copy of the range represented by this
230    /// [`ClosedRange`] instance.
231    #[doc(hidden)]
232    fn get(self) -> Pair<Self::EndT>;
233}
234
235/// A [`NormalizedRangeIter`] yields a sorted sequence of
236/// non-overlapping, non-adjacent, non-empty closed ranges.
237///
238/// It's hard to check for this property at runtime, so this
239/// trait is sealed.
240pub trait NormalizedRangeIter: private::Sealed + Iterator<Item: ClosedRange> {
241    /// Determines whether this range iterator is equivalent to
242    /// (represents the same set of values as) another.
243    ///
244    /// This operation takes constant space and time linear in
245    /// the shorter length of the two input iterators.
246    fn eqv(
247        mut self,
248        other: impl IntoNormalizedRangeIter<
249            IntoIter: Iterator<Item: ClosedRange<EndT = <Self::Item as ClosedRange>::EndT>>,
250        >,
251    ) -> bool
252    where
253        Self: Sized,
254    {
255        use core::cmp::Ordering;
256
257        let mut other = other.into_iter();
258        loop {
259            // No need to fuse, we bail as soon as one iterator returns `None`.
260            match (self.next(), other.next()) {
261                (Some(a), Some(b)) => {
262                    if Endpoint::cmp_range(a.get(), b.get()) != Ordering::Equal {
263                        return false;
264                    }
265                }
266                (None, None) => return true,
267                _ => return false,
268            }
269        }
270    }
271
272    /// Returns an iterator for the complement of this normalized range iterator.
273    ///
274    /// Running the resulting iterator to exhaustion takes constant space and time
275    /// linear in the length of the input iterator.
276    ///
277    /// The result is also a [`NormalizedRangeIter`].
278    #[inline(always)]
279    fn complement(self) -> complement::ComplementIterator<Self>
280    where
281        Self: Sized,
282    {
283        complement::ComplementIterator::new(self)
284    }
285
286    /// Returns an iterator for the intersection of this normalized range iterator
287    /// and another [`RangeVec`] of normalized ranges.
288    ///
289    /// Running the resulting iterator to exhaustion takes constant space and
290    /// \\(\mathcal{O}(\min(m + n, m \log n))\\) time, where \\(m\\) is the
291    /// size of `self`, and \\(n\\) that of `other`.
292    ///
293    /// The result is also a [`NormalizedRangeIter`].
294    #[inline(always)]
295    fn intersect_vec<'a>(
296        self,
297        other: &'a RangeVec<<Self::Item as ClosedRange>::EndT>,
298    ) -> intersection::IntersectionIterator<'a, Self>
299    where
300        Self: 'a + Sized,
301    {
302        // Unsafe because the interface assumes both arguments are normalized.
303        unsafe { crate::intersection::intersect(self, other) }
304    }
305
306    /// Returns an iterator for the intersection of this normalized range iterator
307    /// and another iterator of normalized ranges.
308    ///
309    /// Running the resulting iterator to exhaustion takes constant space and
310    /// time linear in the total length of the two input iterators.
311    ///
312    /// The result is also a [`NormalizedRangeIter`].
313    #[inline(always)]
314    fn intersect<Other>(
315        self,
316        other: Other,
317    ) -> intersection_iterator::LinearIntersectionIterator<
318        <Self::Item as ClosedRange>::EndT,
319        Self,
320        <Other as IntoIterator>::IntoIter,
321    >
322    where
323        Self: Sized,
324        Other: IntoNormalizedRangeIter<
325            IntoIter: NormalizedRangeIter<
326                Item: ClosedRange<EndT = <Self::Item as ClosedRange>::EndT>,
327            >,
328        >,
329    {
330        intersection_iterator::LinearIntersectionIterator::new(self, other.into_iter())
331    }
332
333    /// Returns an interator for the union of this normalized range
334    /// iterator and another normalized range iterator.
335    ///
336    /// Running the resulting iterator to exhaustion takes constant space and
337    /// time linear in the total length of the two input iterators.
338    ///
339    /// The result is also a [`NormalizedRangeIter`].
340    #[inline(always)]
341    fn union<Other>(
342        self,
343        other: Other,
344    ) -> union_iterator::UnionIterator<
345        <Self::Item as ClosedRange>::EndT,
346        Self,
347        <Other as IntoIterator>::IntoIter,
348    >
349    where
350        Self: Sized,
351        Other: IntoNormalizedRangeIter<
352            IntoIter: NormalizedRangeIter<
353                Item: ClosedRange<EndT = <Self::Item as ClosedRange>::EndT>,
354            >,
355        >,
356    {
357        union_iterator::UnionIterator::new(self, other.into_iter())
358    }
359
360    /// Collects the contents of a [`NormalizedRangeIter`] into a [`RangeVec`].
361    ///
362    /// This takes time linear in the length of the input iterator (in addition
363    /// to the resources used by the iterator itself).
364    fn collect_range_vec(self) -> RangeVec<<Self::Item as ClosedRange>::EndT>
365    where
366        Self: Sized,
367    {
368        #[cfg(feature = "internal_checks")]
369        let hint = self.size_hint();
370
371        let inner: SmallVec<[_; INLINE_SIZE]> = self.map(|range| range.get()).collect();
372
373        #[cfg(feature = "internal_checks")]
374        {
375            assert!(hint.0 <= inner.len());
376            assert!(inner.len() <= hint.1.unwrap_or(usize::MAX));
377            assert!(is_normalized(&inner));
378        }
379
380        unsafe { RangeVec::new_unchecked(inner) }
381    }
382}
383
384/// Boxes of iterators are iterators.
385impl<T: NormalizedRangeIter + ?Sized> private::Sealed for alloc::boxed::Box<T> {}
386impl<T: NormalizedRangeIter + ?Sized> NormalizedRangeIter for alloc::boxed::Box<T> {}
387
388/// A [`IntoNormalizedRangeIter`] is an [`IntoIterator`] that turns
389/// into an [`NormalizedRangeIter`].
390pub trait IntoNormalizedRangeIter: IntoIterator<IntoIter: NormalizedRangeIter> {}
391
392impl<T: IntoIterator<IntoIter: NormalizedRangeIter>> IntoNormalizedRangeIter for T {}
393
394impl<T: Endpoint> private::Sealed for (T, T) {}
395
396impl<T: Endpoint> ClosedRange for (T, T) {
397    type EndT = T;
398
399    #[inline(always)]
400    fn get(self) -> (T, T) {
401        self
402    }
403}
404
405impl<T: Endpoint> private::Sealed for &(T, T) {}
406
407impl<T: Endpoint> ClosedRange for &(T, T) {
408    type EndT = T;
409
410    #[inline(always)]
411    fn get(self) -> (T, T) {
412        *self
413    }
414}
415
416/// The return type of `ClosedRange::get()`.
417type ClosedRangeVal<T> = Pair<<T as ClosedRange>::EndT>;
418
419#[cfg(test)]
420#[cfg_attr(coverage_nightly, coverage(off))]
421fn ranges_to_bits(ranges: &[(u8, u8)]) -> alloc::vec::Vec<bool> {
422    use alloc::vec;
423
424    let mut marks = vec![false; 256];
425
426    for (start, stop) in ranges.iter().copied() {
427        if start <= stop {
428            for i in start..=stop {
429                marks[i as usize] = true;
430            }
431        }
432    }
433
434    marks
435}
436
437#[cfg(test)]
438#[cfg_attr(coverage_nightly, coverage(off))]
439mod test {
440    use super::*;
441    use alloc::vec;
442    use alloc::vec::Vec;
443
444    #[test]
445    fn test_min_max() {
446        assert_eq!(<u8 as Endpoint>::min_value(), 0);
447        assert_eq!(<u8 as Endpoint>::max_value(), 255);
448
449        assert_eq!(<i8 as Endpoint>::min_value(), -128);
450        assert_eq!(<i8 as Endpoint>::max_value(), 127);
451
452        assert_eq!(<i32 as Endpoint>::min_value(), i32::MIN);
453        assert_eq!(<i32 as Endpoint>::max_value(), i32::MAX);
454
455        assert_eq!(<isize as Endpoint>::min_value(), isize::MIN);
456        assert_eq!(<isize as Endpoint>::max_value(), isize::MAX);
457
458        assert_eq!(<usize as Endpoint>::min_value(), usize::MIN);
459        assert_eq!(<usize as Endpoint>::max_value(), usize::MAX);
460    }
461
462    #[test]
463    fn test_prev_next_u64() {
464        assert_eq!(0u64.prev_before(), None);
465        assert_eq!(0u64.next_after(), Some(1));
466
467        assert_eq!(u64::MAX.prev_before(), Some(u64::MAX - 1));
468        assert_eq!(u64::MAX.next_after(), None);
469
470        assert_eq!(0u64.decrease_toward(0u64), None);
471        assert_eq!(0u64.increase_toward(10u64), Some(1));
472
473        assert_eq!(1u64.decrease_toward(0u64), Some(0u64));
474        assert_eq!(1u64.decrease_toward(1u64), None);
475        assert_eq!(1u64.decrease_toward(2u64), None);
476
477        assert_eq!(1u64.increase_toward(0u64), None);
478        assert_eq!(1u64.increase_toward(1u64), None);
479        assert_eq!(1u64.increase_toward(2u64), Some(2u64));
480
481        assert_eq!(u64::MAX.increase_toward(u64::MAX), None);
482        assert_eq!(u64::MAX.decrease_toward(0), Some(u64::MAX - 1));
483    }
484
485    #[test]
486    fn test_closed_range() {
487        let ranges = vec![(1u8, 2u8), (10u8, 4u8)];
488
489        assert_eq!(
490            &ranges.iter().map(ClosedRange::get).collect::<Vec<_>>(),
491            &ranges
492        );
493        assert_eq!(
494            ranges
495                .clone()
496                .into_iter()
497                .map(ClosedRange::get)
498                .collect::<Vec<_>>(),
499            ranges
500        );
501    }
502
503    #[test]
504    fn test_chain_boxed_iter() {
505        let mut acc: Option<Box<dyn NormalizedRangeIter<Item = (u8, u8)>>> = None;
506
507        for i in 1u8..=4u8 {
508            let vec = RangeVec::from_vec(vec![(2 * i, 10 * i)]);
509
510            acc = match acc.take() {
511                None => Some(Box::new(vec.into_iter())),
512                Some(acc) if i % 2 == 0 => Some(Box::new(acc.intersect(vec.into_iter()))),
513                Some(acc) => Some(Box::new(acc.intersect_vec(Box::leak(Box::new(vec))))),
514            };
515        }
516
517        // Intersection is (8u8, 10u8); union with [0, 6]
518        let singleton: SmallVec<[(u8, u8); 1]> = smallvec::smallvec![(0, 6)];
519        acc = Some(Box::new(
520            acc.unwrap().union(RangeVec::from_smallvec(singleton)),
521        ));
522
523        let expected = RangeVec::from_vec(vec![(7u8, 7u8), (11u8, 255u8)]);
524        assert!(acc.unwrap().complement().eqv(expected));
525    }
526
527    proptest::proptest! {
528        #[test]
529        fn test_increase(x: u8) {
530            assert_eq!(<u8 as Endpoint>::max_value(), u8::MAX);
531
532            if x != u8::MAX {
533                assert_eq!(x.next_after(), Some(x + 1));
534            } else {
535                assert_eq!(x.next_after(), None);
536            }
537        }
538
539        #[test]
540        fn test_decrease(x: u8) {
541            assert_eq!(<u8 as Endpoint>::min_value(), 0u8);
542
543            if x != 0u8 {
544                assert_eq!(x.prev_before(), Some(x - 1));
545            } else {
546                assert_eq!(x.prev_before(), None);
547            }
548        }
549
550        #[test]
551        fn test_toward(x: u8, y: u8) {
552            let (x, y) = (x.min(y), x.max(y));
553
554            assert_eq!(x.decrease_toward(y), None);
555            assert_eq!(y.increase_toward(x), None);
556
557            if x == y {
558                assert_eq!(x.increase_toward(y), None);
559                assert_eq!(x.decrease_toward(y), None);
560                assert_eq!(y.increase_toward(x), None);
561                assert_eq!(y.decrease_toward(x), None);
562            } else {
563                assert_eq!(x.increase_toward(y), Some(x + 1));
564                assert_eq!(y.decrease_toward(x), Some(y - 1));
565            }
566        }
567
568        #[test]
569        fn test_top_bot(x: u8, y: u8) {
570            assert_eq!(x.bot_end(y), x.min(y));
571            assert_eq!(y.bot_end(x), x.min(y));
572
573            assert_eq!(x.top_end(y), x.max(y));
574            assert_eq!(y.top_end(x), x.max(y));
575        }
576
577        #[test]
578        fn test_cmp(x: u8, y: u8) {
579            assert_eq!(x.cmp_end(y), x.cmp(&y));
580            assert_eq!(y.cmp_end(x), y.cmp(&x));
581        }
582
583        #[test]
584        fn test_cmp_range(x: (u8, u8), y: (u8, u8)) {
585            assert_eq!(u8::cmp_range(x, y), x.cmp(&y));
586            assert_eq!(u8::cmp_range(y, x), y.cmp(&x));
587        }
588
589        // Smoke test isize and usize: they're the same as one of the
590        // regular integer types, so not worth fuzzing individually.
591        // However, we still want some coverage.
592        #[test]
593        fn test_increase_isize(x: isize) {
594            assert_eq!(<isize as Endpoint>::max_value(), isize::MAX);
595
596            if x != isize::MAX {
597                assert_eq!(x.next_after(), Some(x + 1));
598            } else {
599                assert_eq!(x.next_after(), None);
600            }
601        }
602
603        #[test]
604        fn test_decrease_isize(x: isize) {
605            assert_eq!(<isize as Endpoint>::min_value(), isize::MIN);
606
607            if x != isize::MIN {
608                assert_eq!(x.prev_before(), Some(x - 1));
609            } else {
610                assert_eq!(x.prev_before(), None);
611            }
612        }
613
614        #[test]
615        fn test_toward_isize(x: isize, y: isize) {
616            let (x, y) = (x.min(y), x.max(y));
617
618            assert_eq!(x.decrease_toward(y), None);
619            assert_eq!(y.increase_toward(x), None);
620
621            if x == y {
622                assert_eq!(x.increase_toward(y), None);
623                assert_eq!(x.decrease_toward(y), None);
624                assert_eq!(y.increase_toward(x), None);
625                assert_eq!(y.decrease_toward(x), None);
626            } else {
627                assert_eq!(x.increase_toward(y), Some(x + 1));
628                assert_eq!(y.decrease_toward(x), Some(y - 1));
629            }
630        }
631
632        #[test]
633        fn test_top_bot_isize(x: isize, y: isize) {
634            assert_eq!(x.bot_end(y), x.min(y));
635            assert_eq!(y.bot_end(x), x.min(y));
636
637            assert_eq!(x.top_end(y), x.max(y));
638            assert_eq!(y.top_end(x), x.max(y));
639        }
640
641        #[test]
642        fn test_cmp_isize(x: isize, y: isize) {
643            assert_eq!(x.cmp_end(y), x.cmp(&y));
644            assert_eq!(y.cmp_end(x), y.cmp(&x));
645        }
646
647        #[test]
648        fn test_cmp_range_isize(x: (isize, isize), y: (isize, isize)) {
649            assert_eq!(isize::cmp_range(x, y), x.cmp(&y));
650            assert_eq!(isize::cmp_range(y, x), y.cmp(&x));
651        }
652
653        #[test]
654        fn test_increase_usize(x: usize) {
655            assert_eq!(<usize as Endpoint>::max_value(), usize::MAX);
656
657            if x != usize::MAX {
658                assert_eq!(x.next_after(), Some(x + 1));
659            } else {
660                assert_eq!(x.next_after(), None);
661            }
662        }
663
664        #[test]
665        fn test_decrease_usize(x: usize) {
666            assert_eq!(<usize as Endpoint>::min_value(), 0usize);
667
668            if x != usize::MIN {
669                assert_eq!(x.prev_before(), Some(x - 1));
670            } else {
671                assert_eq!(x.prev_before(), None);
672            }
673        }
674
675        #[test]
676        fn test_toward_usize(x: usize, y: usize) {
677            let (x, y) = (x.min(y), x.max(y));
678
679            assert_eq!(x.decrease_toward(y), None);
680            assert_eq!(y.increase_toward(x), None);
681
682            if x == y {
683                assert_eq!(x.increase_toward(y), None);
684                assert_eq!(x.decrease_toward(y), None);
685                assert_eq!(y.increase_toward(x), None);
686                assert_eq!(y.decrease_toward(x), None);
687            } else {
688                assert_eq!(x.increase_toward(y), Some(x + 1));
689                assert_eq!(y.decrease_toward(x), Some(y - 1));
690            }
691        }
692
693        #[test]
694        fn test_top_bot_usize(x: usize, y: usize) {
695            assert_eq!(x.bot_end(y), x.min(y));
696            assert_eq!(y.bot_end(x), x.min(y));
697
698            assert_eq!(x.top_end(y), x.max(y));
699            assert_eq!(y.top_end(x), x.max(y));
700        }
701
702        #[test]
703        fn test_cmp_usize(x: usize, y: usize) {
704            assert_eq!(x.cmp_end(y), x.cmp(&y));
705            assert_eq!(y.cmp_end(x), y.cmp(&x));
706        }
707
708        #[test]
709        fn test_cmp_range_usize(x: (usize, usize), y: (usize, usize)) {
710            assert_eq!(usize::cmp_range(x, y), x.cmp(&y));
711            assert_eq!(usize::cmp_range(y, x), y.cmp(&x));
712        }
713    }
714}