1use std::ops::Range;
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
7pub struct Span {
8 pub start: usize,
9 pub end: usize,
10}
11
12impl Span {
13 pub fn new(start: usize, end: usize) -> Self {
14 debug_assert!(start <= end, "span start {start} > end {end}");
15 Self { start, end }
16 }
17
18 pub fn len(&self) -> usize {
19 self.end - self.start
20 }
21
22 pub fn is_empty(&self) -> bool {
23 self.start == self.end
24 }
25
26 pub fn overlaps(&self, other: &Span) -> bool {
28 self.start < other.end && other.start < self.end
29 }
30
31 pub fn contains(&self, other: &Span) -> bool {
32 self.start <= other.start && other.end <= self.end
33 }
34
35 pub fn contains_offset(&self, offset: usize) -> bool {
37 (self.start..self.end).contains(&offset)
38 }
39
40 pub fn union(&self, other: &Span) -> Span {
42 Span::new(self.start.min(other.start), self.end.max(other.end))
43 }
44}
45
46impl From<Range<usize>> for Span {
47 fn from(range: Range<usize>) -> Self {
48 Span::new(range.start, range.end)
49 }
50}
51
52impl From<Span> for Range<usize> {
53 fn from(span: Span) -> Self {
54 span.start..span.end
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 #[test]
63 fn overlap_is_strict() {
64 let a = Span::new(0, 5);
65 assert!(a.overlaps(&Span::new(4, 8)));
66 assert!(!a.overlaps(&Span::new(5, 8)));
67 assert!(!Span::new(5, 8).overlaps(&a));
68 }
69
70 #[test]
71 fn empty_span_conflicts_inside_a_range_but_not_at_its_edges() {
72 let a = Span::new(0, 5);
73 assert!(a.overlaps(&Span::new(2, 2)));
74 assert!(!a.overlaps(&Span::new(0, 0)));
75 assert!(!a.overlaps(&Span::new(5, 5)));
76 assert!(!Span::new(3, 3).overlaps(&Span::new(3, 3)));
77 }
78}