starnix_uapi/
range_ext.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::cmp::{max, min};
6use std::ops::Range;
7
8/// Provides convenience methods for [`Range`].
9pub trait RangeExt {
10    /// Returns the intersection of self and rhs. If there is no intersection, the result will
11    /// return true for .is_empty().
12    fn intersect(&self, rhs: &Self) -> Self;
13}
14
15impl<K: Ord + Copy> RangeExt for Range<K> {
16    fn intersect(&self, rhs: &Self) -> Self {
17        max(self.start, rhs.start)..min(self.end, rhs.end)
18    }
19}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24
25    #[::fuchsia::test]
26    fn no_intersection() {
27        let a = 1..3;
28        let b = 3..5;
29        assert!(a.intersect(&b).is_empty());
30        assert!(b.intersect(&a).is_empty());
31    }
32
33    #[::fuchsia::test]
34    fn partial_intersection() {
35        let a = 1..3;
36        let b = 2..5;
37        assert_eq!(a.intersect(&b), (2..3));
38        assert_eq!(b.intersect(&a), (2..3));
39    }
40
41    #[::fuchsia::test]
42    fn full_intersection() {
43        let a = 1..4;
44        let b = 2..3;
45        assert_eq!(a.intersect(&b), (2..3));
46        assert_eq!(b.intersect(&a), (2..3));
47
48        let c = 2..4;
49        assert_eq!(a.intersect(&c), (2..4));
50        assert_eq!(c.intersect(&a), (2..4));
51
52        let d = 1..2;
53        assert_eq!(a.intersect(&d), (1..2));
54        assert_eq!(d.intersect(&a), (1..2));
55
56        assert_eq!(a.intersect(&a), (1..4));
57    }
58}