Skip to main content

version_ranges/
lib.rs

1// SPDX-License-Identifier: MPL-2.0
2
3//! This crate contains a performance-optimized type for generic version ranges and operations on
4//! them.
5//!
6//! [`Ranges`] can represent version selectors such as `(>=1, <2) OR (==3) OR (>4)`. Internally,
7//! it is an ordered list of contiguous intervals (segments) with inclusive, exclusive or open-ended
8//! ends, similar to a `Vec<(Bound<T>, Bound<T>)>`.
9//!
10//! You can construct a basic range from one of the following build blocks. All other ranges are
11//! concatenation, union, and complement of these basic ranges.
12//!  - [empty()](Ranges::empty): No version
13//!  - [full()](Ranges::full): All versions
14//!  - [singleton(v)](Ranges::singleton): Only the version v exactly
15//!  - [higher_than(v)](Ranges::higher_than): All versions `v <= versions`
16//!  - [strictly_higher_than(v)](Ranges::strictly_higher_than): All versions `v < versions`
17//!  - [lower_than(v)](Ranges::lower_than): All versions `versions <= v`
18//!  - [strictly_lower_than(v)](Ranges::strictly_lower_than): All versions `versions < v`
19//!  - [between(v1, v2)](Ranges::between): All versions `v1 <= versions < v2`
20//!
21//! [`Ranges`] is generic over any type that implements [`Ord`] + [`Clone`] and can represent all
22//! kinds of slices with ordered coordinates, not just version ranges. While built as a
23//! performance-critical piece of [pubgrub](https://github.com/pubgrub-rs/pubgrub), it can be
24//! adopted for other domains, too.
25//!
26//! Note that there are limitations to the equality implementation: Given a `Ranges<u32>`,
27//! the segments `(Unbounded, Included(42u32))` and `(Included(0), Included(42u32))` as well as
28//! `(Included(1), Included(5))` and  `(Included(1), Included(3)) + (Included(4), Included(5))`
29//! are reported as unequal, even though the match the same versions: We can't tell that there isn't
30//! a version between `0` and `-inf` or `3` and `4` respectively.
31//!
32//! ## Optional features
33//!
34//! * `serde`: serialization and deserialization for the version range, given that the version type
35//!   also supports it.
36//! * `proptest`: Exports are proptest strategy for [`Ranges<u32>`].
37
38#[cfg(feature = "semver")]
39pub mod semver;
40
41use std::borrow::Borrow;
42use std::cmp::Ordering;
43use std::fmt::{Debug, Display, Formatter};
44use std::ops::Bound::{self, Excluded, Included, Unbounded};
45use std::ops::RangeBounds;
46
47#[cfg(any(feature = "proptest", test))]
48use proptest::prelude::*;
49use smallvec::{smallvec, SmallVec};
50
51/// Ranges represents multiple intervals of a continuous range of monotone increasing values.
52///
53/// Internally, [`Ranges`] are an ordered list of segments, where segment is a bounds pair.
54///
55/// Invariants:
56/// 1. The segments are sorted, from lowest to highest (through `Ord`).
57/// 2. Each segment contains at least one version (start < end).
58/// 3. There is at least one version between two segments.
59///
60/// These ensure that equivalent instances have an identical representation, which is important
61/// for `Eq` and `Hash`. Note that this representation cannot strictly guaranty equality of
62/// [`Ranges`] with equality of its representation without also knowing the nature of the underlying
63/// versions. In particular, if the version space is discrete, different representations, using
64/// different types of bounds (exclusive/inclusive) may correspond to the same set of existing
65/// versions. It is a tradeoff we acknowledge, but which makes representations of continuous version
66/// sets more accessible, to better handle features like pre-releases and other types of version
67/// modifiers. For example, `[(Included(3u32), Excluded(7u32))]` and
68/// `[(Included(3u32), Included(6u32))]` refer to the same version set, since there is no version
69/// between 6 and 7, which this crate doesn't know about.
70
71#[derive(Debug, Clone, Eq, PartialEq, Hash)]
72#[cfg_attr(feature = "serde", derive(serde::Serialize))]
73#[cfg_attr(feature = "serde", serde(transparent))]
74pub struct Ranges<V> {
75    /// Profiling in <https://github.com/pubgrub-rs/pubgrub/pull/262#discussion_r1804276278> showed
76    /// that a single stack entry is the most efficient. This is most likely due to `Interval<V>`
77    /// being large.
78    segments: SmallVec<[Interval<V>; 1]>,
79}
80
81/// Describes how one set relates to another.
82///
83/// [`SetRelation::Subset`] takes precedence when the left-hand set is empty and therefore also
84/// disjoint.
85#[derive(Clone, Copy, Debug, Eq, PartialEq)]
86pub enum SetRelation {
87    /// Every value in the left-hand set is also in the right-hand set.
88    Subset,
89    /// The two sets have no values in common.
90    Disjoint,
91    /// The sets overlap, but the left-hand set is not a subset of the right-hand set.
92    Overlapping,
93}
94
95// TODO: Replace the tuple type with a custom enum inlining the bounds to reduce the type's size.
96type Interval<V> = (Bound<V>, Bound<V>);
97
98impl<V> Ranges<V> {
99    /// Empty set of versions.
100    pub fn empty() -> Self {
101        Self {
102            segments: SmallVec::new(),
103        }
104    }
105
106    /// Set of all possible versions
107    pub fn full() -> Self {
108        Self {
109            segments: smallvec![(Unbounded, Unbounded)],
110        }
111    }
112
113    /// Set of all versions higher or equal to some version
114    pub fn higher_than(v: impl Into<V>) -> Self {
115        Self {
116            segments: smallvec![(Included(v.into()), Unbounded)],
117        }
118    }
119
120    /// Set of all versions higher to some version
121    pub fn strictly_higher_than(v: impl Into<V>) -> Self {
122        Self {
123            segments: smallvec![(Excluded(v.into()), Unbounded)],
124        }
125    }
126
127    /// Set of all versions lower to some version
128    pub fn strictly_lower_than(v: impl Into<V>) -> Self {
129        Self {
130            segments: smallvec![(Unbounded, Excluded(v.into()))],
131        }
132    }
133
134    /// Set of all versions lower or equal to some version
135    pub fn lower_than(v: impl Into<V>) -> Self {
136        Self {
137            segments: smallvec![(Unbounded, Included(v.into()))],
138        }
139    }
140
141    /// Set of versions greater or equal to `v1` but less than `v2`.
142    pub fn between(v1: impl Into<V>, v2: impl Into<V>) -> Self {
143        Self {
144            segments: smallvec![(Included(v1.into()), Excluded(v2.into()))],
145        }
146    }
147
148    /// Whether the set is empty, i.e. it has not ranges
149    pub fn is_empty(&self) -> bool {
150        self.segments.is_empty()
151    }
152}
153
154impl<V: Clone> Ranges<V> {
155    /// Set containing exactly one version
156    pub fn singleton(v: impl Into<V>) -> Self {
157        let v = v.into();
158        Self {
159            segments: smallvec![(Included(v.clone()), Included(v))],
160        }
161    }
162
163    /// Returns the complement, which contains everything not included in `self`.
164    pub fn complement(&self) -> Self {
165        match self.segments.first() {
166            // Complement of ∅ is ∞
167            None => Self::full(),
168
169            // Complement of ∞ is ∅
170            Some((Unbounded, Unbounded)) => Self::empty(),
171
172            // First high bound is +∞
173            Some((Included(v), Unbounded)) => Self::strictly_lower_than(v.clone()),
174            Some((Excluded(v), Unbounded)) => Self::lower_than(v.clone()),
175
176            Some((Unbounded, Included(v))) => {
177                Self::negate_segments(Excluded(v.clone()), &self.segments[1..])
178            }
179            Some((Unbounded, Excluded(v))) => {
180                Self::negate_segments(Included(v.clone()), &self.segments[1..])
181            }
182            Some((Included(_), Included(_)))
183            | Some((Included(_), Excluded(_)))
184            | Some((Excluded(_), Included(_)))
185            | Some((Excluded(_), Excluded(_))) => Self::negate_segments(Unbounded, &self.segments),
186        }
187    }
188
189    /// Helper function performing the negation of intervals in segments.
190    fn negate_segments(start: Bound<V>, segments: &[Interval<V>]) -> Self {
191        let mut complement_segments = SmallVec::new();
192        let mut start = start;
193        for (v1, v2) in segments {
194            complement_segments.push((
195                start,
196                match v1 {
197                    Included(v) => Excluded(v.clone()),
198                    Excluded(v) => Included(v.clone()),
199                    Unbounded => unreachable!(),
200                },
201            ));
202            start = match v2 {
203                Included(v) => Excluded(v.clone()),
204                Excluded(v) => Included(v.clone()),
205                Unbounded => Unbounded,
206            }
207        }
208        if !matches!(start, Unbounded) {
209            complement_segments.push((start, Unbounded));
210        }
211
212        Self {
213            segments: complement_segments,
214        }
215    }
216}
217
218impl<V: Ord> Ranges<V> {
219    /// If self contains exactly a single version, return it, otherwise, return [None].
220    pub fn as_singleton(&self) -> Option<&V> {
221        match self.segments.as_slice() {
222            [(Included(v1), Included(v2))] => {
223                if v1 == v2 {
224                    Some(v1)
225                } else {
226                    None
227                }
228            }
229            _ => None,
230        }
231    }
232
233    /// Convert to something that can be used with
234    /// [BTreeMap::range](std::collections::BTreeMap::range).
235    /// All versions contained in self, will be in the output,
236    /// but there may be versions in the output that are not contained in self.
237    /// Returns None if the range is empty.
238    pub fn bounding_range(&self) -> Option<(Bound<&V>, Bound<&V>)> {
239        self.segments.first().map(|(start, _)| {
240            let end = self
241                .segments
242                .last()
243                .expect("if there is a first element, there must be a last element");
244            (start.as_ref(), end.1.as_ref())
245        })
246    }
247
248    /// Returns true if self contains the specified value.
249    pub fn contains<Q>(&self, version: &Q) -> bool
250    where
251        V: Borrow<Q>,
252        Q: ?Sized + PartialOrd,
253    {
254        self.segments
255            .binary_search_by(|segment| {
256                // We have to reverse because we need the segment wrt to the version, while
257                // within bounds tells us the version wrt to the segment.
258                within_bounds(version, segment).reverse()
259            })
260            // An equal interval is one that contains the version
261            .is_ok()
262    }
263
264    /// Returns true if self contains the specified values.
265    ///
266    /// The `versions` iterator must be sorted.
267    /// Functionally equivalent to `versions.map(|v| self.contains(v))`.
268    /// Except it runs in `O(size_of_range + len_of_versions)` not `O(size_of_range * len_of_versions)`
269    pub fn contains_many<'s, I, BV>(&'s self, versions: I) -> impl Iterator<Item = bool> + 's
270    where
271        I: Iterator<Item = BV> + 's,
272        BV: Borrow<V> + 's,
273    {
274        #[cfg(debug_assertions)]
275        let mut last: Option<BV> = None;
276        versions.scan(0, move |i, v| {
277            #[cfg(debug_assertions)]
278            {
279                if let Some(l) = last.as_ref() {
280                    assert!(
281                        l.borrow() <= v.borrow(),
282                        "`contains_many` `versions` argument incorrectly sorted"
283                    );
284                }
285            }
286            while let Some(segment) = self.segments.get(*i) {
287                match within_bounds(v.borrow(), segment) {
288                    Ordering::Less => return Some(false),
289                    Ordering::Equal => return Some(true),
290                    Ordering::Greater => *i += 1,
291                }
292            }
293            #[cfg(debug_assertions)]
294            {
295                last = Some(v);
296            }
297            Some(false)
298        })
299    }
300
301    /// Construct a simple range from anything that impls [RangeBounds] like `v1..v2`.
302    pub fn from_range_bounds<R, IV>(bounds: R) -> Self
303    where
304        R: RangeBounds<IV>,
305        IV: Clone + Into<V>,
306    {
307        let start = match bounds.start_bound() {
308            Included(v) => Included(v.clone().into()),
309            Excluded(v) => Excluded(v.clone().into()),
310            Unbounded => Unbounded,
311        };
312        let end = match bounds.end_bound() {
313            Included(v) => Included(v.clone().into()),
314            Excluded(v) => Excluded(v.clone().into()),
315            Unbounded => Unbounded,
316        };
317        if valid_segment(&start, &end) {
318            Self {
319                segments: smallvec![(start, end)],
320            }
321        } else {
322            Self::empty()
323        }
324    }
325
326    /// See [`Ranges`] for the invariants checked.
327    fn check_invariants(self) -> Self {
328        if cfg!(debug_assertions) {
329            for p in self.segments.as_slice().windows(2) {
330                assert!(end_before_start_with_gap(&p[0].1, &p[1].0));
331            }
332            for (s, e) in self.segments.iter() {
333                assert!(valid_segment(s, e));
334            }
335        }
336        self
337    }
338}
339
340/// Implementing `PartialOrd` for start `Bound` of an interval.
341///
342/// Legend: `∞` is unbounded, `[1,2]` is `>=1,<=2`, `]1,2[` is `>1,<2`.
343///
344/// ```text
345/// left:   ∞-------]
346/// right:    [-----]
347/// left is smaller, since it starts earlier.
348///
349/// left:   [-----]
350/// right:  ]-----]
351/// left is smaller, since it starts earlier.
352/// ```
353fn cmp_bounds_start<V: PartialOrd>(left: Bound<&V>, right: Bound<&V>) -> Option<Ordering> {
354    Some(match (left, right) {
355        // left:   ∞-----
356        // right:  ∞-----
357        (Unbounded, Unbounded) => Ordering::Equal,
358        // left:     [---
359        // right:  ∞-----
360        (Included(_left), Unbounded) => Ordering::Greater,
361        // left:     ]---
362        // right:  ∞-----
363        (Excluded(_left), Unbounded) => Ordering::Greater,
364        // left:   ∞-----
365        // right:    [---
366        (Unbounded, Included(_right)) => Ordering::Less,
367        // left:   [----- OR [----- OR   [-----
368        // right:    [--- OR [----- OR [---
369        (Included(left), Included(right)) => left.partial_cmp(right)?,
370        (Excluded(left), Included(right)) => match left.partial_cmp(right)? {
371            // left:   ]-----
372            // right:    [---
373            Ordering::Less => Ordering::Less,
374            // left:   ]-----
375            // right:  [---
376            Ordering::Equal => Ordering::Greater,
377            // left:     ]---
378            // right:  [-----
379            Ordering::Greater => Ordering::Greater,
380        },
381        // left:   ∞-----
382        // right:    ]---
383        (Unbounded, Excluded(_right)) => Ordering::Less,
384        (Included(left), Excluded(right)) => match left.partial_cmp(right)? {
385            // left:   [-----
386            // right:    ]---
387            Ordering::Less => Ordering::Less,
388            // left:   [-----
389            // right:  ]---
390            Ordering::Equal => Ordering::Less,
391            // left:     [---
392            // right:  ]-----
393            Ordering::Greater => Ordering::Greater,
394        },
395        // left:   ]----- OR ]----- OR   ]---
396        // right:    ]--- OR ]----- OR ]-----
397        (Excluded(left), Excluded(right)) => left.partial_cmp(right)?,
398    })
399}
400
401/// Implementing `PartialOrd` for end `Bound` of an interval.
402///
403/// We flip the unbounded ranges from `-∞` to `∞`, while `V`-valued bounds checks remain the same.
404///
405/// Legend: `∞` is unbounded, `[1,2]` is `>=1,<=2`, `]1,2[` is `>1,<2`.
406///
407/// ```text
408/// left:   [--------∞
409/// right:  [-----]
410/// left is greater, since it starts earlier.
411///
412/// left:   [-----[
413/// right:  [-----]
414/// left is smaller, since it ends earlier.
415/// ```
416fn cmp_bounds_end<V: PartialOrd>(left: Bound<&V>, right: Bound<&V>) -> Option<Ordering> {
417    Some(match (left, right) {
418        // left:   -----∞
419        // right:  -----∞
420        (Unbounded, Unbounded) => Ordering::Equal,
421        // left:   ---]
422        // right:  -----∞
423        (Included(_left), Unbounded) => Ordering::Less,
424        // left:   ---[
425        // right:  -----∞
426        (Excluded(_left), Unbounded) => Ordering::Less,
427        // left:  -----∞
428        // right: ---]
429        (Unbounded, Included(_right)) => Ordering::Greater,
430        // left:   -----] OR -----] OR ---]
431        // right:    ---] OR -----] OR -----]
432        (Included(left), Included(right)) => left.partial_cmp(right)?,
433        (Excluded(left), Included(right)) => match left.partial_cmp(right)? {
434            // left:   ---[
435            // right:  -----]
436            Ordering::Less => Ordering::Less,
437            // left:   -----[
438            // right:  -----]
439            Ordering::Equal => Ordering::Less,
440            // left:   -----[
441            // right:  ---]
442            Ordering::Greater => Ordering::Greater,
443        },
444        (Unbounded, Excluded(_right)) => Ordering::Greater,
445        (Included(left), Excluded(right)) => match left.partial_cmp(right)? {
446            // left:   ---]
447            // right:  -----[
448            Ordering::Less => Ordering::Less,
449            // left:   -----]
450            // right:  -----[
451            Ordering::Equal => Ordering::Greater,
452            // left:   -----]
453            // right:  ---[
454            Ordering::Greater => Ordering::Greater,
455        },
456        // left:   -----[ OR -----[ OR ---[
457        // right:  ---[   OR -----[ OR -----[
458        (Excluded(left), Excluded(right)) => left.partial_cmp(right)?,
459    })
460}
461
462impl<V: PartialOrd> PartialOrd for Ranges<V> {
463    /// A simple ordering scheme where we zip the segments and compare all bounds in order. If all
464    /// bounds are equal, the longer range is considered greater. (And if all zipped bounds are
465    /// equal and we have the same number of segments, the ranges are equal).
466    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
467        for (left, right) in self.segments.iter().zip(other.segments.iter()) {
468            let start_cmp = cmp_bounds_start(left.start_bound(), right.start_bound())?;
469            if start_cmp != Ordering::Equal {
470                return Some(start_cmp);
471            }
472            let end_cmp = cmp_bounds_end(left.end_bound(), right.end_bound())?;
473            if end_cmp != Ordering::Equal {
474                return Some(end_cmp);
475            }
476        }
477        Some(self.segments.len().cmp(&other.segments.len()))
478    }
479}
480
481impl<V: Ord> Ord for Ranges<V> {
482    fn cmp(&self, other: &Self) -> Ordering {
483        self.partial_cmp(other)
484            .expect("PartialOrd must be `Some(Ordering)` for types that implement `Ord`")
485    }
486}
487
488/// The ordering of the version wrt to the interval.
489/// ```text
490///      |-------|
491///   ^      ^      ^
492///   less   equal  greater
493/// ```
494fn within_bounds<Q, V>(version: &Q, segment: &Interval<V>) -> Ordering
495where
496    V: Borrow<Q>,
497    Q: ?Sized + PartialOrd,
498{
499    let below_lower_bound = match segment {
500        (Excluded(start), _) => version <= start.borrow(),
501        (Included(start), _) => version < start.borrow(),
502        (Unbounded, _) => false,
503    };
504    if below_lower_bound {
505        return Ordering::Less;
506    }
507    let below_upper_bound = match segment {
508        (_, Unbounded) => true,
509        (_, Included(end)) => version <= end.borrow(),
510        (_, Excluded(end)) => version < end.borrow(),
511    };
512    if below_upper_bound {
513        return Ordering::Equal;
514    }
515    Ordering::Greater
516}
517
518/// A valid segment is one where at least one version fits between start and end
519fn valid_segment<T: PartialOrd>(start: &Bound<T>, end: &Bound<T>) -> bool {
520    match (start, end) {
521        // Singleton interval are allowed
522        (Included(s), Included(e)) => s <= e,
523        (Included(s), Excluded(e)) => s < e,
524        (Excluded(s), Included(e)) => s < e,
525        (Excluded(s), Excluded(e)) => s < e,
526        (Unbounded, _) | (_, Unbounded) => true,
527    }
528}
529
530/// The end of one interval is before the start of the next one, so they can't be concatenated
531/// into a single interval. The `union` method calling with both intervals and then the intervals
532/// switched. If either is true, the intervals are separate in the union and if both are false, they
533/// are merged.
534/// ```text
535/// True for these two:
536///  |----|
537///                |-----|
538///       ^ end    ^ start
539/// False for these two:
540///  |----|
541///     |-----|
542/// Here it depends: If they both exclude the position they share, there is a version in between
543/// them that blocks concatenation
544///  |----|
545///       |-----|
546/// ```
547fn end_before_start_with_gap<V: PartialOrd>(end: &Bound<V>, start: &Bound<V>) -> bool {
548    match (end, start) {
549        (_, Unbounded) => false,
550        (Unbounded, _) => false,
551        (Included(left), Included(right)) => left < right,
552        (Included(left), Excluded(right)) => left < right,
553        (Excluded(left), Included(right)) => left < right,
554        (Excluded(left), Excluded(right)) => left <= right,
555    }
556}
557
558fn left_start_is_smaller<V: PartialOrd>(left: Bound<V>, right: Bound<V>) -> bool {
559    match (left, right) {
560        (Unbounded, _) => true,
561        (_, Unbounded) => false,
562        (Included(l), Included(r)) => l <= r,
563        (Excluded(l), Excluded(r)) => l <= r,
564        (Included(l), Excluded(r)) => l <= r,
565        (Excluded(l), Included(r)) => l < r,
566    }
567}
568
569fn left_end_is_smaller<V: PartialOrd>(left: Bound<V>, right: Bound<V>) -> bool {
570    match (left, right) {
571        (_, Unbounded) => true,
572        (Unbounded, _) => false,
573        (Included(l), Included(r)) => l <= r,
574        (Excluded(l), Excluded(r)) => l <= r,
575        (Excluded(l), Included(r)) => l <= r,
576        (Included(l), Excluded(r)) => l < r,
577    }
578}
579
580/// Group adjacent versions locations.
581///
582/// ```text
583/// [None, 3, 6, 7, None] -> [(3, 7)]
584/// [3, 6, 7, None] -> [(None, 7)]
585/// [3, 6, 7] -> [(None, None)]
586/// [None, 1, 4, 7, None, None, None, 8, None, 9] -> [(1, 7), (8, 8), (9, None)]
587/// ```
588fn group_adjacent_locations(
589    mut locations: impl Iterator<Item = Option<usize>>,
590) -> impl Iterator<Item = (Option<usize>, Option<usize>)> {
591    // If the first version matched, then the lower bound of that segment is not needed
592    let mut seg = locations.next().flatten().map(|ver| (None, Some(ver)));
593    std::iter::from_fn(move || {
594        for ver in locations.by_ref() {
595            if let Some(ver) = ver {
596                // As long as were still matching versions, we keep merging into the currently matching segment
597                seg = Some((seg.map_or(Some(ver), |(s, _)| s), Some(ver)));
598            } else {
599                // If we have found a version that doesn't match, then right the merge segment and prepare for a new one.
600                if seg.is_some() {
601                    return seg.take();
602                }
603            }
604        }
605        // If the last version matched, then write out the merged segment but the upper bound is not needed.
606        seg.take().map(|(s, _)| (s, None))
607    })
608}
609
610impl<V: Ord + Clone> Ranges<V> {
611    /// Computes the union of this `Ranges` and another.
612    pub fn union(&self, other: &Self) -> Self {
613        let mut output = SmallVec::new();
614        let mut accumulator: Option<(&Bound<_>, &Bound<_>)> = None;
615        let mut left_iter = self.segments.iter().peekable();
616        let mut right_iter = other.segments.iter().peekable();
617        loop {
618            let smaller_interval = match (left_iter.peek(), right_iter.peek()) {
619                (Some((left_start, left_end)), Some((right_start, right_end))) => {
620                    if left_start_is_smaller(left_start.as_ref(), right_start.as_ref()) {
621                        left_iter.next();
622                        (left_start, left_end)
623                    } else {
624                        right_iter.next();
625                        (right_start, right_end)
626                    }
627                }
628                (Some((left_start, left_end)), None) => {
629                    left_iter.next();
630                    (left_start, left_end)
631                }
632                (None, Some((right_start, right_end))) => {
633                    right_iter.next();
634                    (right_start, right_end)
635                }
636                (None, None) => break,
637            };
638
639            if let Some(accumulator_) = accumulator {
640                if end_before_start_with_gap(accumulator_.1, smaller_interval.0) {
641                    output.push((accumulator_.0.clone(), accumulator_.1.clone()));
642                    accumulator = Some(smaller_interval);
643                } else {
644                    let accumulator_end = match (accumulator_.1, smaller_interval.1) {
645                        (_, Unbounded) | (Unbounded, _) => &Unbounded,
646                        (Included(l), Excluded(r) | Included(r)) if l == r => accumulator_.1,
647                        (Included(l) | Excluded(l), Included(r) | Excluded(r)) => {
648                            if l > r {
649                                accumulator_.1
650                            } else {
651                                smaller_interval.1
652                            }
653                        }
654                    };
655                    accumulator = Some((accumulator_.0, accumulator_end));
656                }
657            } else {
658                accumulator = Some(smaller_interval)
659            }
660        }
661
662        if let Some(accumulator) = accumulator {
663            output.push((accumulator.0.clone(), accumulator.1.clone()));
664        }
665
666        Self { segments: output }.check_invariants()
667    }
668
669    /// Computes the intersection of two sets of versions.
670    pub fn intersection(&self, other: &Self) -> Self {
671        let mut output = SmallVec::new();
672        let mut left_iter = self.segments.iter().peekable();
673        let mut right_iter = other.segments.iter().peekable();
674        // By the definition of intersection any point that is matched by the output
675        // must have a segment in each of the inputs that it matches.
676        // Therefore, every segment in the output must be the intersection of a segment from each of the inputs.
677        // It would be correct to do the "O(n^2)" thing, by computing the intersection of every segment from one input
678        // with every segment of the other input, and sorting the result.
679        // We can avoid the sorting by generating our candidate segments with an increasing `end` value.
680        while let Some(((left_start, left_end), (right_start, right_end))) =
681            left_iter.peek().zip(right_iter.peek())
682        {
683            // The next smallest `end` value is going to come from one of the inputs.
684            let left_end_is_smaller = left_end_is_smaller(left_end.as_ref(), right_end.as_ref());
685            // Now that we are processing `end` we will never have to process any segment smaller than that.
686            // We can ensure that the input that `end` came from is larger than `end` by advancing it one step.
687            // `end` is the smaller available input, so we know the other input is already larger than `end`.
688            // Note: We can call `other_iter.next_if( == end)`, but the ends lining up is rare enough that
689            // it does not end up being faster in practice.
690            let (other_start, end) = if left_end_is_smaller {
691                left_iter.next();
692                (right_start, left_end)
693            } else {
694                right_iter.next();
695                (left_start, right_end)
696            };
697            // `start` will either come from the input `end` came from or the other input, whichever one is larger.
698            // The intersection is invalid if `start` > `end`.
699            // But, we already know that the segments in our input are valid.
700            // So we do not need to check if the `start` from the input `end` came from is smaller than `end`.
701            // If the `other_start` is larger than end, then the intersection will be invalid.
702            if !valid_segment(other_start, end) {
703                // Note: We can call `this_iter.next_if(!valid_segment(other_start, this_end))` in a loop.
704                // But the checks make it slower for the benchmarked inputs.
705                continue;
706            }
707            let start = match (left_start, right_start) {
708                (Included(l), Included(r)) => Included(std::cmp::max(l, r)),
709                (Excluded(l), Excluded(r)) => Excluded(std::cmp::max(l, r)),
710
711                (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => {
712                    if i <= e {
713                        Excluded(e)
714                    } else {
715                        Included(i)
716                    }
717                }
718                (s, Unbounded) | (Unbounded, s) => s.as_ref(),
719            };
720            // Now we clone and push a new segment.
721            // By dealing with references until now we ensure that NO cloning happens when we reject the segment.
722            output.push((start.cloned(), end.clone()))
723        }
724
725        Self { segments: output }.check_invariants()
726    }
727
728    /// Return true if there can be no `V` so that `V` is contained in both `self` and `other`.
729    ///
730    /// Note that we don't know that set of all existing `V`s here, so we only check if the segments
731    /// are disjoint, not if no version is contained in both.
732    pub fn is_disjoint(&self, other: &Self) -> bool {
733        // The operation is symmetric
734        let mut left_iter = self.segments.iter().peekable();
735        let mut right_iter = other.segments.iter().peekable();
736
737        while let Some((left, right)) = left_iter.peek().zip(right_iter.peek()) {
738            if !valid_segment(&right.start_bound(), &left.end_bound()) {
739                left_iter.next();
740            } else if !valid_segment(&left.start_bound(), &right.end_bound()) {
741                right_iter.next();
742            } else {
743                return false;
744            }
745        }
746
747        // The remaining element(s) can't intersect anymore
748        true
749    }
750
751    /// Classifies `self` as a subset of, disjoint from, or partially overlapping with `other`.
752    ///
753    /// This combines [`Self::subset_of`] and [`Self::is_disjoint`] into a single traversal.
754    /// An empty `self` is classified as [`SetRelation::Subset`].
755    pub fn relation(&self, other: &Self) -> SetRelation {
756        // Equality is common for long accumulated ranges during PubGrub conflict resolution.
757        if self.segments.len() > 1
758            && self.segments.len() == other.segments.len()
759            && self.segments == other.segments
760        {
761            return SetRelation::Subset;
762        }
763
764        let mut other_iter = other.segments.iter().peekable();
765        let mut is_subset = true;
766        let mut overlaps = false;
767
768        for subset_elem in &self.segments {
769            while other_iter.peek().is_some_and(|containing_elem| {
770                !valid_segment(&subset_elem.start_bound(), &containing_elem.end_bound())
771            }) {
772                other_iter.next();
773            }
774
775            let Some(containing_elem) = other_iter.peek() else {
776                is_subset = false;
777                break;
778            };
779
780            if !valid_segment(&containing_elem.start_bound(), &subset_elem.end_bound()) {
781                is_subset = false;
782                continue;
783            }
784
785            overlaps = true;
786            if !left_start_is_smaller(containing_elem.start_bound(), subset_elem.start_bound())
787                || !left_end_is_smaller(subset_elem.end_bound(), containing_elem.end_bound())
788            {
789                is_subset = false;
790            }
791        }
792
793        if is_subset {
794            SetRelation::Subset
795        } else if overlaps {
796            SetRelation::Overlapping
797        } else {
798            SetRelation::Disjoint
799        }
800    }
801
802    /// Return true if any `V` that is contained in `self` is also contained in `other`.
803    ///
804    /// Note that we don't know that set of all existing `V`s here, so we only check if all
805    /// segments `self` are contained in a segment of `other`.
806    pub fn subset_of(&self, other: &Self) -> bool {
807        // Equality is common for long accumulated ranges during PubGrub conflict resolution.
808        if self.segments.len() > 1
809            && self.segments.len() == other.segments.len()
810            && self.segments == other.segments
811        {
812            return true;
813        }
814
815        let mut containing_iter = other.segments.iter();
816        let mut subset_iter = self.segments.iter();
817        let Some(mut containing_elem) = containing_iter.next() else {
818            // As long as we have subset elements, we need containing elements
819            return subset_iter.next().is_none();
820        };
821
822        for subset_elem in subset_iter {
823            // Check if the current containing element ends before the subset element.
824            // There needs to be another containing element for our subset element in this case.
825            while !valid_segment(&subset_elem.start_bound(), &containing_elem.end_bound()) {
826                if let Some(containing_elem_) = containing_iter.next() {
827                    containing_elem = containing_elem_;
828                } else {
829                    return false;
830                };
831            }
832
833            let start_contained =
834                left_start_is_smaller(containing_elem.start_bound(), subset_elem.start_bound());
835
836            if !start_contained {
837                // The start element is not contained
838                return false;
839            }
840
841            let end_contained =
842                left_end_is_smaller(subset_elem.end_bound(), containing_elem.end_bound());
843
844            if !end_contained {
845                // The end element is not contained
846                return false;
847            }
848        }
849
850        true
851    }
852
853    /// Returns a copy of this set where each segment is widened to the largest interval that
854    /// contains the same given versions, merging segments when no version separates them.
855    ///
856    /// A bound that excludes no existing version cannot influence which versions a set contains,
857    /// so each segment can extend outward up to, and excluding, the nearest version outside the
858    /// segment. For example, with the existing versions `1, 2, 3, 4`, the singleton `{2}` widens
859    /// to `(1, 3)`, and the union `{2} ∪ {3}` widens to `(1, 4)`.
860    ///
861    /// The result is a superset of the input: For every one of the given versions, input and
862    /// output agree on whether it is contained, while versions not in `versions` may be added,
863    /// but are never removed.
864    ///
865    /// See [`Ranges::narrow_versions`] for the display-oriented inverse.
866    ///
867    /// The `versions` slice must be sorted.
868    pub fn widen_versions<BV>(&self, versions: &[BV]) -> Self
869    where
870        BV: Borrow<V>,
871    {
872        debug_assert!(
873            versions.is_sorted_by(|l, r| l.borrow() <= r.borrow()),
874            "`widen_versions` `versions` argument incorrectly sorted"
875        );
876        let mut segments: SmallVec<[Interval<V>; 1]> = SmallVec::new();
877        for segment in &self.segments {
878            // The last version below the segment becomes the new exclusive start bound, the
879            // first version above the segment the new exclusive end bound.
880            let below =
881                versions.partition_point(|v| within_bounds(v.borrow(), segment) == Ordering::Less);
882            let start = if below == 0 {
883                Unbounded
884            } else {
885                Excluded(versions[below - 1].borrow().clone())
886            };
887            let not_above = below
888                + versions[below..]
889                    .partition_point(|v| within_bounds(v.borrow(), segment) != Ordering::Greater);
890            let end = if not_above == versions.len() {
891                Unbounded
892            } else {
893                Excluded(versions[not_above].borrow().clone())
894            };
895            // Merge with the previous segment unless a version separates them.
896            match segments.last_mut() {
897                Some(last) if !end_before_start_with_gap(&last.1, &start) => last.1 = end,
898                _ => segments.push((start, end)),
899            }
900        }
901        Self { segments }.check_invariants()
902    }
903
904    /// Returns a copy of this set where each segment's bounded ends are shrunk to inclusive
905    /// bounds on the outermost given versions the segment contains.
906    ///
907    /// This is the display-oriented inverse of [`Ranges::widen_versions`]: bounds that exclude
908    /// no existing version carry no information, so each segment can shrink to the first and
909    /// last version it contains. For example, with the existing versions `1, 2, 3, 4`, the
910    /// segment `(1, 3)` shrinks to `{2}`. Unbounded ends are kept, so a claim about all
911    /// versions beyond the given ones (e.g. versions not yet published) remains visible:
912    /// `(1, ∞)` shrinks to `[2, ∞)`, not `[2, 4]`. A segment that contains none of the given
913    /// versions is kept unchanged.
914    ///
915    /// The result is a subset of the input: For every one of the given versions, input and
916    /// output agree on whether it is contained, while versions not in `versions` may be
917    /// removed, but are never added.
918    ///
919    /// The `versions` slice must be sorted.
920    pub fn narrow_versions<BV>(&self, versions: &[BV]) -> Self
921    where
922        BV: Borrow<V>,
923    {
924        debug_assert!(
925            versions.is_sorted_by(|l, r| l.borrow() <= r.borrow()),
926            "`narrow_versions` `versions` argument incorrectly sorted"
927        );
928        let mut segments: SmallVec<[Interval<V>; 1]> = SmallVec::new();
929        for segment in &self.segments {
930            // The first and last version inside the segment become the new inclusive bounds.
931            let first =
932                versions.partition_point(|v| within_bounds(v.borrow(), segment) == Ordering::Less);
933            let last = first
934                + versions[first..]
935                    .partition_point(|v| within_bounds(v.borrow(), segment) != Ordering::Greater);
936            if first == last {
937                // The segment contains none of the versions, keep it unchanged.
938                segments.push(segment.clone());
939            } else {
940                let start = match &segment.0 {
941                    Unbounded => Unbounded,
942                    _ => Included(versions[first].borrow().clone()),
943                };
944                let end = match &segment.1 {
945                    Unbounded => Unbounded,
946                    _ => Included(versions[last - 1].borrow().clone()),
947                };
948                segments.push((start, end));
949            }
950        }
951        Self { segments }.check_invariants()
952    }
953
954    /// Returns a simpler representation that contains the same versions.
955    ///
956    /// For every one of the Versions provided in versions the existing range and the simplified range will agree on whether it is contained.
957    /// The simplified version may include or exclude versions that are not in versions as the implementation wishes.
958    ///
959    /// If none of the versions are contained in the original than the range will be returned unmodified.
960    /// If the range includes a single version, it will be returned unmodified.
961    /// If all the versions are contained in the original than the range will be simplified to `full`.
962    ///
963    /// If the given versions are not sorted the correctness of this function is not guaranteed.
964    pub fn simplify<'s, I, BV>(&self, versions: I) -> Self
965    where
966        I: Iterator<Item = BV> + 's,
967        BV: Borrow<V> + 's,
968    {
969        // Do not simplify singletons
970        if self.as_singleton().is_some() {
971            return self.clone();
972        }
973
974        #[cfg(debug_assertions)]
975        let mut last: Option<BV> = None;
976        // Return the segment index in the range for each version in the range, None otherwise
977        let version_locations = versions.scan(0, move |i, v| {
978            #[cfg(debug_assertions)]
979            {
980                if let Some(l) = last.as_ref() {
981                    assert!(
982                        l.borrow() <= v.borrow(),
983                        "`simplify` `versions` argument incorrectly sorted"
984                    );
985                }
986            }
987            while let Some(segment) = self.segments.get(*i) {
988                match within_bounds(v.borrow(), segment) {
989                    Ordering::Less => return Some(None),
990                    Ordering::Equal => return Some(Some(*i)),
991                    Ordering::Greater => *i += 1,
992                }
993            }
994            #[cfg(debug_assertions)]
995            {
996                last = Some(v);
997            }
998            Some(None)
999        });
1000        let mut kept_segments = group_adjacent_locations(version_locations).peekable();
1001
1002        // Do not return null sets
1003        if kept_segments.peek().is_none() {
1004            return self.clone();
1005        }
1006
1007        self.keep_segments(kept_segments)
1008    }
1009
1010    /// Create a new range with a subset of segments at given location bounds.
1011    ///
1012    /// Each new segment is constructed from a pair of segments, taking the
1013    /// start of the first and the end of the second.
1014    fn keep_segments(
1015        &self,
1016        kept_segments: impl Iterator<Item = (Option<usize>, Option<usize>)>,
1017    ) -> Ranges<V> {
1018        let mut segments = SmallVec::new();
1019        for (s, e) in kept_segments {
1020            segments.push((
1021                s.map_or(Unbounded, |s| self.segments[s].0.clone()),
1022                e.map_or(Unbounded, |e| self.segments[e].1.clone()),
1023            ));
1024        }
1025        Self { segments }.check_invariants()
1026    }
1027
1028    /// Iterate over the parts of the range.
1029    pub fn iter(&self) -> impl DoubleEndedIterator<Item = (Bound<&V>, Bound<&V>)> {
1030        self.segments
1031            .iter()
1032            .map(|(start, end)| (start.as_ref(), end.as_ref()))
1033    }
1034}
1035
1036// Newtype to avoid leaking our internal representation.
1037pub struct RangesIter<V>(smallvec::IntoIter<[Interval<V>; 1]>);
1038
1039impl<V> Iterator for RangesIter<V> {
1040    type Item = Interval<V>;
1041
1042    fn next(&mut self) -> Option<Self::Item> {
1043        self.0.next()
1044    }
1045
1046    fn size_hint(&self) -> (usize, Option<usize>) {
1047        (self.0.len(), Some(self.0.len()))
1048    }
1049}
1050
1051impl<V> ExactSizeIterator for RangesIter<V> {}
1052
1053impl<V> DoubleEndedIterator for RangesIter<V> {
1054    fn next_back(&mut self) -> Option<Self::Item> {
1055        self.0.next_back()
1056    }
1057}
1058
1059impl<V> IntoIterator for Ranges<V> {
1060    type Item = (Bound<V>, Bound<V>);
1061    // Newtype to avoid leaking our internal representation.
1062    type IntoIter = RangesIter<V>;
1063
1064    fn into_iter(self) -> Self::IntoIter {
1065        RangesIter(self.segments.into_iter())
1066    }
1067}
1068
1069impl<V: Ord> FromIterator<(Bound<V>, Bound<V>)> for Ranges<V> {
1070    /// Constructor from arbitrary, unsorted and potentially overlapping ranges.
1071    ///
1072    /// This is equivalent, but faster, to computing the [`Ranges::union`] of the
1073    /// [`Ranges::from_range_bounds`] of each segment.
1074    fn from_iter<T: IntoIterator<Item = (Bound<V>, Bound<V>)>>(iter: T) -> Self {
1075        // We have three constraints we need to fulfil:
1076        // 1. The segments are sorted, from lowest to highest (through `Ord`): By sorting.
1077        // 2. Each segment contains at least one version (start < end): By skipping invalid
1078        //    segments.
1079        // 3. There is at least one version between two segments: By merging overlapping elements.
1080        //
1081        // Technically, the implementation has a O(n²) worst case complexity since we're inserting
1082        // and removing. This has two motivations: One is that we don't have any performance
1083        // critical usages of this method as of this writing, so we have no real world benchmark.
1084        // The other is that we get the elements from an iterator, so to avoid moving elements
1085        // around we would first need to build a different, sorted collection with extra
1086        // allocation(s), before we could build our real segments. --Konsti
1087
1088        // For this implementation, we choose to only build a single smallvec and insert or remove
1089        // in it, instead of e.g. collecting the segments into a sorted datastructure first and then
1090        // construction the second smallvec without shifting.
1091        let mut segments: SmallVec<[Interval<V>; 1]> = SmallVec::new();
1092
1093        for segment in iter {
1094            if !valid_segment(&segment.start_bound(), &segment.end_bound()) {
1095                continue;
1096            }
1097            // Find where to insert the new segment
1098            let insertion_point = segments.partition_point(|elem: &Interval<V>| {
1099                cmp_bounds_start(elem.start_bound(), segment.start_bound())
1100                    .unwrap()
1101                    .is_lt()
1102            });
1103            // Is it overlapping with the previous segment?
1104            let previous_overlapping = insertion_point > 0
1105                && !end_before_start_with_gap(
1106                    &segments[insertion_point - 1].end_bound(),
1107                    &segment.start_bound(),
1108                );
1109
1110            // Is it overlapping with the following segment? We'll check if there's more than one
1111            // overlap later.
1112            let next_overlapping = insertion_point < segments.len()
1113                && !end_before_start_with_gap(
1114                    &segment.end_bound(),
1115                    &segments[insertion_point].start_bound(),
1116                );
1117
1118            match (previous_overlapping, next_overlapping) {
1119                (true, true) => {
1120                    // previous:  |------|
1121                    // segment:       |------|
1122                    // following:          |------|
1123                    // final:     |---------------|
1124                    //
1125                    // OR
1126                    //
1127                    // previous:  |------|
1128                    // segment:       |-----------|
1129                    // following:          |----|
1130                    // final:     |---------------|
1131                    //
1132                    // OR
1133                    //
1134                    // previous:  |------|
1135                    // segment:       |----------------|
1136                    // following:          |----|   |------|
1137                    // final:     |------------------------|
1138                    // We merge all three segments into one, which is effectively removing one of
1139                    // two previously inserted and changing the bounds on the other.
1140
1141                    // Remove all elements covered by the final element
1142                    let mut following = segments.remove(insertion_point);
1143                    while insertion_point < segments.len()
1144                        && !end_before_start_with_gap(
1145                            &segment.end_bound(),
1146                            &segments[insertion_point].start_bound(),
1147                        )
1148                    {
1149                        following = segments.remove(insertion_point);
1150                    }
1151
1152                    // Set end to max(segment.end, <last overlapping segment>.end)
1153                    if cmp_bounds_end(segment.end_bound(), following.end_bound())
1154                        .unwrap()
1155                        .is_lt()
1156                    {
1157                        segments[insertion_point - 1].1 = following.1;
1158                    } else {
1159                        segments[insertion_point - 1].1 = segment.1;
1160                    }
1161                }
1162                (true, false) => {
1163                    // previous:  |------|
1164                    // segment:       |------|
1165                    // following:                |------|
1166                    //
1167                    // OR
1168                    //
1169                    // previous:  |----------|
1170                    // segment:       |---|
1171                    // following:                |------|
1172                    //
1173                    // final:     |----------|   |------|
1174                    // We can reuse the existing element by extending it.
1175
1176                    // Set end to max(segment.end, <previous>.end)
1177                    if cmp_bounds_end(
1178                        segments[insertion_point - 1].end_bound(),
1179                        segment.end_bound(),
1180                    )
1181                    .unwrap()
1182                    .is_lt()
1183                    {
1184                        segments[insertion_point - 1].1 = segment.1;
1185                    }
1186                }
1187                (false, true) => {
1188                    // previous:  |------|
1189                    // segment:             |------|
1190                    // following:               |------|
1191                    // final:    |------|   |----------|
1192                    //
1193                    // OR
1194                    //
1195                    // previous:  |------|
1196                    // segment:             |----------|
1197                    // following:               |---|
1198                    // final:    |------|   |----------|
1199                    //
1200                    // OR
1201                    //
1202                    // previous:  |------|
1203                    // segment:             |------------|
1204                    // following:               |---|  |------|
1205                    //
1206                    // final:    |------|   |-----------------|
1207                    // We can reuse the existing element by extending it.
1208
1209                    // Remove all fully covered segments so the next element is the last one that
1210                    // overlaps.
1211                    while insertion_point + 1 < segments.len()
1212                        && !end_before_start_with_gap(
1213                            &segment.end_bound(),
1214                            &segments[insertion_point + 1].start_bound(),
1215                        )
1216                    {
1217                        // We know that the one after also overlaps, so we can drop the current
1218                        // following.
1219                        segments.remove(insertion_point);
1220                    }
1221
1222                    // Set end to max(segment.end, <last overlapping segment>.end)
1223                    if cmp_bounds_end(segments[insertion_point].end_bound(), segment.end_bound())
1224                        .unwrap()
1225                        .is_lt()
1226                    {
1227                        segments[insertion_point].1 = segment.1;
1228                    }
1229                    segments[insertion_point].0 = segment.0;
1230                }
1231                (false, false) => {
1232                    // previous:  |------|
1233                    // segment:             |------|
1234                    // following:                      |------|
1235                    //
1236                    // final:    |------|   |------|   |------|
1237
1238                    // This line is O(n), which makes the algorithm O(n²), but it should be good
1239                    // enough for now.
1240                    segments.insert(insertion_point, segment);
1241                }
1242            }
1243        }
1244
1245        Self { segments }.check_invariants()
1246    }
1247}
1248
1249// REPORT ######################################################################
1250
1251impl<V: Display + Eq> Display for Ranges<V> {
1252    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1253        if self.segments.is_empty() {
1254            write!(f, "∅")?;
1255        } else {
1256            for (idx, segment) in self.segments.iter().enumerate() {
1257                if idx > 0 {
1258                    write!(f, " | ")?;
1259                }
1260                match segment {
1261                    (Unbounded, Unbounded) => write!(f, "*")?,
1262                    (Unbounded, Included(v)) => write!(f, "<={v}")?,
1263                    (Unbounded, Excluded(v)) => write!(f, "<{v}")?,
1264                    (Included(v), Unbounded) => write!(f, ">={v}")?,
1265                    (Included(v), Included(b)) => {
1266                        if v == b {
1267                            write!(f, "=={v}")?
1268                        } else {
1269                            write!(f, ">={v}, <={b}")?
1270                        }
1271                    }
1272                    (Included(v), Excluded(b)) => write!(f, ">={v}, <{b}")?,
1273                    (Excluded(v), Unbounded) => write!(f, ">{v}")?,
1274                    (Excluded(v), Included(b)) => write!(f, ">{v}, <={b}")?,
1275                    (Excluded(v), Excluded(b)) => write!(f, ">{v}, <{b}")?,
1276                };
1277            }
1278        }
1279        Ok(())
1280    }
1281}
1282
1283// SERIALIZATION ###############################################################
1284
1285#[cfg(feature = "serde")]
1286impl<'de, V: serde::Deserialize<'de>> serde::Deserialize<'de> for Ranges<V> {
1287    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1288        // This enables conversion from the "old" discrete implementation of `Ranges` to the new
1289        // bounded one.
1290        //
1291        // Serialization is always performed in the new format.
1292        #[derive(serde::Deserialize)]
1293        #[serde(untagged)]
1294        enum EitherInterval<V> {
1295            B(Bound<V>, Bound<V>),
1296            D(V, Option<V>),
1297        }
1298
1299        let bounds: SmallVec<[EitherInterval<V>; 2]> =
1300            serde::Deserialize::deserialize(deserializer)?;
1301
1302        let mut segments = SmallVec::new();
1303        for i in bounds {
1304            match i {
1305                EitherInterval::B(l, r) => segments.push((l, r)),
1306                EitherInterval::D(l, Some(r)) => segments.push((Included(l), Excluded(r))),
1307                EitherInterval::D(l, None) => segments.push((Included(l), Unbounded)),
1308            }
1309        }
1310
1311        Ok(Ranges { segments })
1312    }
1313}
1314
1315/// Generate version sets from a random vector of deltas between randomly inclusive or exclusive
1316/// bounds.
1317#[cfg(any(feature = "proptest", test))]
1318pub fn proptest_strategy() -> impl Strategy<Value = Ranges<u32>> {
1319    (
1320        any::<bool>(),
1321        prop::collection::vec(any::<(u32, bool)>(), 0..10),
1322    )
1323        .prop_map(|(start_unbounded, deltas)| {
1324            let mut start = if start_unbounded {
1325                Some(Unbounded)
1326            } else {
1327                None
1328            };
1329            let mut largest: u32 = 0;
1330            let mut last_bound_was_inclusive = false;
1331            let mut segments = SmallVec::new();
1332            for (delta, inclusive) in deltas {
1333                // Add the offset to the current bound
1334                largest = match largest.checked_add(delta) {
1335                    Some(s) => s,
1336                    None => {
1337                        // Skip this offset, if it would result in a too large bound.
1338                        continue;
1339                    }
1340                };
1341
1342                let current_bound = if inclusive {
1343                    Included(largest)
1344                } else {
1345                    Excluded(largest)
1346                };
1347
1348                // If we already have a start bound, the next offset defines the complete range.
1349                // If we don't have a start bound, we have to generate one.
1350                if let Some(start_bound) = start.take() {
1351                    // If the delta from the start bound is 0, the only authorized configuration is
1352                    // Included(x), Included(x)
1353                    if delta == 0 && !(matches!(start_bound, Included(_)) && inclusive) {
1354                        start = Some(start_bound);
1355                        continue;
1356                    }
1357                    last_bound_was_inclusive = inclusive;
1358                    segments.push((start_bound, current_bound));
1359                } else {
1360                    // If the delta from the end bound of the last range is 0 and
1361                    // any of the last ending or current starting bound is inclusive,
1362                    // we skip the delta because they basically overlap.
1363                    if delta == 0 && (last_bound_was_inclusive || inclusive) {
1364                        continue;
1365                    }
1366                    start = Some(current_bound);
1367                }
1368            }
1369
1370            // If we still have a start bound, but didn't have enough deltas to complete another
1371            // segment, we add an unbounded upperbound.
1372            if let Some(start_bound) = start {
1373                segments.push((start_bound, Unbounded));
1374            }
1375
1376            Ranges { segments }.check_invariants()
1377        })
1378}
1379
1380#[cfg(test)]
1381pub mod tests {
1382    use proptest::prelude::*;
1383
1384    use super::*;
1385
1386    fn version_strat() -> impl Strategy<Value = u32> {
1387        any::<u32>()
1388    }
1389
1390    proptest! {
1391
1392        // Testing serde ----------------------------------
1393
1394        #[cfg(feature = "serde")]
1395        #[test]
1396        fn serde_round_trip(range in proptest_strategy()) {
1397            let s = ron::ser::to_string(&range).unwrap();
1398            let r = ron::de::from_str(&s).unwrap();
1399            assert_eq!(range, r);
1400        }
1401
1402        // Testing negate ----------------------------------
1403
1404        #[test]
1405        fn negate_is_different(range in proptest_strategy()) {
1406            assert_ne!(range.complement(), range);
1407        }
1408
1409        #[test]
1410        fn double_negate_is_identity(range in proptest_strategy()) {
1411            assert_eq!(range.complement().complement(), range);
1412        }
1413
1414        #[test]
1415        fn negate_contains_opposite(range in proptest_strategy(), version in version_strat()) {
1416            assert_ne!(range.contains(&version), range.complement().contains(&version));
1417        }
1418
1419        // Testing intersection ----------------------------
1420
1421        #[test]
1422        fn intersection_is_symmetric(r1 in proptest_strategy(), r2 in proptest_strategy()) {
1423            assert_eq!(r1.intersection(&r2), r2.intersection(&r1));
1424        }
1425
1426        #[test]
1427        fn intersection_with_any_is_identity(range in proptest_strategy()) {
1428            assert_eq!(Ranges::full().intersection(&range), range);
1429        }
1430
1431        #[test]
1432        fn intersection_with_none_is_none(range in proptest_strategy()) {
1433            assert_eq!(Ranges::empty().intersection(&range), Ranges::empty());
1434        }
1435
1436        #[test]
1437        fn intersection_is_idempotent(r1 in proptest_strategy(), r2 in proptest_strategy()) {
1438            assert_eq!(r1.intersection(&r2).intersection(&r2), r1.intersection(&r2));
1439        }
1440
1441        #[test]
1442        fn intersection_is_associative(r1 in proptest_strategy(), r2 in proptest_strategy(), r3 in proptest_strategy()) {
1443            assert_eq!(r1.intersection(&r2).intersection(&r3), r1.intersection(&r2.intersection(&r3)));
1444        }
1445
1446        #[test]
1447        fn intesection_of_complements_is_none(range in proptest_strategy()) {
1448            assert_eq!(range.complement().intersection(&range), Ranges::empty());
1449        }
1450
1451        #[test]
1452        fn intesection_contains_both(r1 in proptest_strategy(), r2 in proptest_strategy(), version in version_strat()) {
1453            assert_eq!(r1.intersection(&r2).contains(&version), r1.contains(&version) && r2.contains(&version));
1454        }
1455
1456        // Testing union -----------------------------------
1457
1458        #[test]
1459        fn union_of_complements_is_any(range in proptest_strategy()) {
1460            assert_eq!(range.complement().union(&range), Ranges::full());
1461        }
1462
1463        #[test]
1464        fn union_contains_either(r1 in proptest_strategy(), r2 in proptest_strategy(), version in version_strat()) {
1465            assert_eq!(r1.union(&r2).contains(&version), r1.contains(&version) || r2.contains(&version));
1466        }
1467
1468        #[test]
1469        fn is_disjoint_through_intersection(r1 in proptest_strategy(), r2 in proptest_strategy()) {
1470            let disjoint_def = r1.intersection(&r2) == Ranges::empty();
1471            assert_eq!(r1.is_disjoint(&r2), disjoint_def);
1472        }
1473
1474        #[test]
1475        fn subset_of_through_intersection(r1 in proptest_strategy(), r2 in proptest_strategy()) {
1476            let disjoint_def = r1.intersection(&r2) == r1;
1477            assert_eq!(r1.subset_of(&r2), disjoint_def);
1478        }
1479
1480        #[test]
1481        fn relation_through_subset_and_disjoint(r1 in proptest_strategy(), r2 in proptest_strategy()) {
1482            let relation_def = if r1.subset_of(&r2) {
1483                SetRelation::Subset
1484            } else if r1.is_disjoint(&r2) {
1485                SetRelation::Disjoint
1486            } else {
1487                SetRelation::Overlapping
1488            };
1489            assert_eq!(r1.relation(&r2), relation_def);
1490        }
1491
1492        #[test]
1493        fn union_through_intersection(r1 in proptest_strategy(), r2 in proptest_strategy()) {
1494            let union_def = r1
1495                .complement()
1496                .intersection(&r2.complement())
1497                .complement()
1498                .check_invariants();
1499            assert_eq!(r1.union(&r2), union_def);
1500        }
1501
1502        // Testing contains --------------------------------
1503
1504        #[test]
1505        fn always_contains_exact(version in version_strat()) {
1506            assert!(Ranges::<u32>::singleton(version).contains(&version));
1507        }
1508
1509        #[test]
1510        fn contains_negation(range in proptest_strategy(), version in version_strat()) {
1511            assert_ne!(range.contains(&version), range.complement().contains(&version));
1512        }
1513
1514        #[test]
1515        fn contains_intersection(range in proptest_strategy(), version in version_strat()) {
1516            assert_eq!(range.contains(&version), range.intersection(&Ranges::singleton(version)) != Ranges::empty());
1517        }
1518
1519        #[test]
1520        fn contains_bounding_range(range in proptest_strategy(), version in version_strat()) {
1521            if range.contains(&version) {
1522                assert!(range.bounding_range().map(|b| b.contains(&version)).unwrap_or(false));
1523            }
1524        }
1525
1526        #[test]
1527        fn from_range_bounds(range in any::<(Bound<u32>, Bound<u32>)>(), version in version_strat()) {
1528            let rv: Ranges<_> = Ranges::<u32>::from_range_bounds(range);
1529            assert_eq!(range.contains(&version), rv.contains(&version));
1530        }
1531
1532        #[test]
1533        fn from_range_bounds_round_trip(range in any::<(Bound<u32>, Bound<u32>)>()) {
1534            let rv: Ranges<u32> = Ranges::from_range_bounds(range);
1535            let rv2: Ranges<u32> = rv.bounding_range().map(Ranges::from_range_bounds::<_, u32>).unwrap_or_else(Ranges::empty);
1536            assert_eq!(rv, rv2);
1537        }
1538
1539        #[test]
1540        fn contains(range in proptest_strategy(), versions in proptest::collection::vec(version_strat(), ..30)) {
1541            for v in versions {
1542                assert_eq!(range.contains(&v), range.segments.iter().any(|s| RangeBounds::contains(s, &v)));
1543            }
1544        }
1545
1546        #[test]
1547        fn contains_many(range in proptest_strategy(), mut versions in proptest::collection::vec(version_strat(), ..30)) {
1548            versions.sort();
1549            assert_eq!(versions.len(), range.contains_many(versions.iter()).count());
1550            for (a, b) in versions.iter().zip(range.contains_many(versions.iter())) {
1551                assert_eq!(range.contains(a), b);
1552            }
1553        }
1554
1555        #[test]
1556        fn simplify(range in proptest_strategy(), mut versions in proptest::collection::vec(version_strat(), ..30)) {
1557            versions.sort();
1558            let simp = range.simplify(versions.iter());
1559
1560            for v in versions {
1561                assert_eq!(range.contains(&v), simp.contains(&v));
1562            }
1563            assert!(simp.segments.len() <= range.segments.len())
1564        }
1565
1566        #[test]
1567        fn widen_versions(range in proptest_strategy(), mut versions in proptest::collection::vec(version_strat(), ..30)) {
1568            versions.sort();
1569            let widened = range.widen_versions(&versions);
1570
1571            // The result is a superset of the input that agrees on all given versions.
1572            assert!(range.subset_of(&widened));
1573            for v in &versions {
1574                assert_eq!(range.contains(v), widened.contains(v));
1575            }
1576            // The operation is idempotent.
1577            assert_eq!(widened.widen_versions(&versions), widened);
1578        }
1579
1580        #[test]
1581        fn narrow_versions(range in proptest_strategy(), mut versions in proptest::collection::vec(version_strat(), ..30)) {
1582            versions.sort();
1583            let narrowed = range.narrow_versions(&versions);
1584
1585            // The result is a subset of the input that agrees on all given versions.
1586            assert!(narrowed.subset_of(&range));
1587            for v in &versions {
1588                assert_eq!(range.contains(v), narrowed.contains(v));
1589            }
1590            // The operation is idempotent.
1591            assert_eq!(narrowed.narrow_versions(&versions), narrowed);
1592            // Narrowing a widened set restores agreement on all given versions.
1593            let round_trip = range.widen_versions(&versions).narrow_versions(&versions);
1594            for v in &versions {
1595                assert_eq!(range.contains(v), round_trip.contains(v));
1596            }
1597        }
1598
1599        #[test]
1600        fn from_iter_valid(segments in proptest::collection::vec(any::<(Bound<u32>, Bound<u32>)>(), ..30)) {
1601            let mut expected = Ranges::empty();
1602            for segment in &segments {
1603                expected = expected.union(&Ranges::from_range_bounds(*segment));
1604            }
1605            let actual =  Ranges::from_iter(segments.clone());
1606            assert_eq!(expected, actual, "{segments:?}");
1607        }
1608    }
1609
1610    #[test]
1611    fn contains_many_can_take_owned() {
1612        let range: Ranges<u8> = Ranges::singleton(1);
1613        let versions = vec![1, 2, 3];
1614        // Check that iter can be a Cow
1615        assert_eq!(
1616            range.contains_many(versions.iter()).count(),
1617            range
1618                .contains_many(versions.iter().map(std::borrow::Cow::Borrowed))
1619                .count()
1620        );
1621        // Check that iter can be a V
1622        assert_eq!(
1623            range.contains_many(versions.iter()).count(),
1624            range.contains_many(versions.into_iter()).count()
1625        );
1626    }
1627
1628    #[test]
1629    fn contains_can_take_owned() {
1630        let range: Ranges<Box<u8>> = Ranges::singleton(1);
1631        let version = 1;
1632
1633        assert_eq!(range.contains(&Box::new(version)), range.contains(&version));
1634        let range: Ranges<String> = Ranges::singleton(1.to_string());
1635        let version = 1.to_string();
1636        assert_eq!(range.contains(&version), range.contains("1"));
1637    }
1638
1639    #[test]
1640    fn widen_versions_extends_to_neighboring_versions() {
1641        let versions = [1u32, 2, 3, 5, 9];
1642        // A singleton widens up to, and excluding, the neighboring versions.
1643        assert_eq!(
1644            Ranges::singleton(3u32).widen_versions(&versions),
1645            Ranges::from_range_bounds((Excluded(2u32), Excluded(5u32)))
1646        );
1647        // Without a version above, the segment becomes unbounded.
1648        assert_eq!(
1649            Ranges::singleton(9u32).widen_versions(&versions),
1650            Ranges::strictly_higher_than(5u32)
1651        );
1652        // The union of singletons of adjacent versions merges into a single segment.
1653        let range: Ranges<u32> = Ranges::singleton(2u32).union(&Ranges::singleton(3u32));
1654        assert_eq!(
1655            range.widen_versions(&versions),
1656            Ranges::from_range_bounds((Excluded(1u32), Excluded(5u32)))
1657        );
1658        // A version separating two segments is preserved.
1659        let range: Ranges<u32> = Ranges::singleton(1u32).union(&Ranges::singleton(3u32));
1660        assert_eq!(
1661            range.widen_versions(&versions),
1662            Ranges::strictly_lower_than(2u32)
1663                .union(&Ranges::from_range_bounds((Excluded(2u32), Excluded(5u32))))
1664        );
1665    }
1666
1667    #[test]
1668    fn narrow_versions_shrinks_to_contained_versions() {
1669        let versions = [1u32, 2, 3, 5, 9];
1670        // A segment shrinks to the versions it contains, with inclusive bounds.
1671        assert_eq!(
1672            Ranges::from_range_bounds((Excluded(2u32), Excluded(5u32))).narrow_versions(&versions),
1673            Ranges::singleton(3u32)
1674        );
1675        // Unbounded ends are kept, only the bounded end shrinks.
1676        assert_eq!(
1677            Ranges::strictly_higher_than(2u32).narrow_versions(&versions),
1678            Ranges::higher_than(3u32)
1679        );
1680        assert_eq!(
1681            Ranges::<u32>::full().narrow_versions(&versions),
1682            Ranges::full()
1683        );
1684        // A segment containing no version is kept unchanged.
1685        let range = Ranges::from_range_bounds((Excluded(5u32), Excluded(9u32)));
1686        assert_eq!(range.narrow_versions(&versions), range);
1687    }
1688
1689    #[test]
1690    fn simplify_can_take_owned() {
1691        let range: Ranges<u8> = Ranges::singleton(1);
1692        let versions = vec![1, 2, 3];
1693        // Check that iter can be a Cow
1694        assert_eq!(
1695            range.simplify(versions.iter()),
1696            range.simplify(versions.iter().map(std::borrow::Cow::Borrowed))
1697        );
1698        // Check that iter can be a V
1699        assert_eq!(
1700            range.simplify(versions.iter()),
1701            range.simplify(versions.into_iter())
1702        );
1703    }
1704
1705    #[test]
1706    fn version_ord() {
1707        let versions: &[Ranges<u32>] = &[
1708            Ranges::strictly_lower_than(1u32),
1709            Ranges::lower_than(1u32),
1710            Ranges::singleton(1u32),
1711            Ranges::between(1u32, 3u32),
1712            Ranges::higher_than(1u32),
1713            Ranges::strictly_higher_than(1u32),
1714            Ranges::singleton(2u32),
1715            Ranges::singleton(2u32).union(&Ranges::singleton(3u32)),
1716            Ranges::singleton(2u32)
1717                .union(&Ranges::singleton(3u32))
1718                .union(&Ranges::singleton(4u32)),
1719            Ranges::singleton(2u32).union(&Ranges::singleton(4u32)),
1720            Ranges::singleton(3u32),
1721        ];
1722
1723        let mut versions_sorted = versions.to_vec();
1724        versions_sorted.sort();
1725        assert_eq!(versions_sorted, versions);
1726
1727        // Check that the sorting isn't just stable because we're returning equal.
1728        let mut version_reverse_sorted = versions.to_vec();
1729        version_reverse_sorted.reverse();
1730        version_reverse_sorted.sort();
1731        assert_eq!(version_reverse_sorted, versions);
1732    }
1733}