Skip to main content

beyond_any/
beyond_any.rs

1use common_range_tools::{CpCmp, IncDecCpCmp, Intersector, RiFactory};
2#[derive(Clone, Copy, Debug)]
3struct Point {
4    p: i32,
5}
6
7const MIN: Point = Point { p: 0 };
8const MAX: Point = Point { p: 8 };
9struct CustomIncDecCpCmp {}
10
11impl CpCmp<Point> for CustomIncDecCpCmp {
12    // a way to copy or clone the current struct is required!
13    fn cp(&self, v: &Point) -> Point {
14        return v.clone();
15    }
16    // All compare operations can be derived from either lt or gt.
17    // The only compare method that is required to be implemented
18    // for this trait is the lt operator.
19    fn lt(&self, a: &Point, b: &Point) -> bool {
20        a.p < b.p
21    }
22    fn min(&self) -> Point {
23        return MIN;
24    }
25    fn max(&self) -> Point {
26        return MAX;
27    }
28    fn min_ref(&self) -> &Point {
29        &MIN
30    }
31    fn max_ref(&self) -> &Point {
32        &MAX
33    }
34}
35
36impl IncDecCpCmp<Point, Point> for CustomIncDecCpCmp {
37    fn inc(&self, a: &Point, b: &Point) -> Option<Point> {
38        match a.p.checked_add(b.p) {
39            Some(x) => Some(Point { p: x }),
40            None => None,
41        }
42    }
43
44    fn dec(&self, a: &Point, b: &Point) -> Option<Point> {
45        match a.p.checked_sub(b.p) {
46            Some(x) => Some(Point { p: x }),
47            None => None,
48        }
49    }
50    fn cp_v(&self, v: &Point) -> Point {
51        return *v;
52    }
53}
54
55fn main() {
56    let t = CustomIncDecCpCmp {};
57
58    let mut isec = Intersector::new(
59        Vec::new(),       // Container for our internal ranges
60        Point { p: 1 },   // step
61        Point { p: 1 },   // Rebound value
62        t,                // our compare instance
63        RiFactory::new(), // Factory used to construct new ranges
64    );
65
66    // Note: an internal RangeInclusive instance is
67    // generated for every range that is successfully added.
68    // This means it is safe to drop the orginal range values
69    // after they are loaded into the Intersector instance.
70    isec.add_range(&(..Point { p: 2 }));
71    isec.add_range(&(Point { p: 1 }..Point { p: 3 }));
72    isec.add_range(&(Point { p: 3 }..=Point { p: 4 }));
73    isec.add_range(&(Point { p: 3 }..));
74    for r in isec.into_iter() {
75        println!("X: {:?}, Y: {:?}", r.start(), r.end());
76    }
77    // Output will be:
78    //  X: Point { p: 0 }, Y: Point { p: 0 }
79    //  X: Point { p: 1 }, Y: Point { p: 1 }
80    //  X: Point { p: 2 }, Y: Point { p: 2 }
81    //  X: Point { p: 3 }, Y: Point { p: 4 }
82    //  X: Point { p: 5 }, Y: Point { p: 8 }
83}