1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use std::{cmp,fmt};
use std::ops::Range;
pub const MAX_INTERVAL : Interval = Interval{start:0,end:std::usize::MAX};
#[derive(Clone,Copy,Debug,Eq,PartialEq)]
pub struct Interval {
pub start: usize,
pub end: usize
}
impl Interval {
pub fn new(start: usize, end: usize) -> Self {
assert!(start <= end);
Self{start,end}
}
pub const fn new_const(start: usize, end: usize) -> Self {
assert!(start <= end);
Self{start,end}
}
pub fn is_constant(&self) -> bool {
self.start == self.end
}
pub fn unwrap(&self) -> usize {
if self.start != self.end { panic!("unwrapping non-constant interval"); }
self.start
}
pub fn add(&self, val: usize) -> Self {
let start = self.start + val;
let end = self.end + val;
Self{start,end}
}
pub fn sub(&self, val: usize) -> Self {
let start = self.start - val;
let end = self.end - val;
Self{start,end}
}
pub fn union(&self, other: &Interval) -> Self {
let start = cmp::min(self.start,other.start);
let end = cmp::max(self.end,other.end);
Self{start,end}
}
}
impl fmt::Display for Interval {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,"{}..{}",self.start,self.end)
}
}
impl From<Range<usize>> for Interval {
fn from(r:Range<usize>) -> Interval {
Interval::new(r.start,r.end)
}
}