Skip to main content

rl_lang/utils/
span.rs

1use std::ops::Range;
2
3/// A byte-offset range into the source string.
4///
5/// Used for pointing error reports at exact source locations.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
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        Self { start, end }
15    }
16
17    /// A sentinel span used when no real location is known.
18    pub fn dummy() -> Self {
19        Self { start: 0, end: 0 }
20    }
21
22    /// Span covering both `self` and `other` (and everything between).
23    pub fn join(self, other: Self) -> Self {
24        Self {
25            start: self.start.min(other.start),
26            end: self.end.max(other.end),
27        }
28    }
29}
30
31impl From<Span> for Range<usize> {
32    fn from(s: Span) -> Self {
33        s.start..s.end
34    }
35}
36
37impl From<Range<usize>> for Span {
38    fn from(r: Range<usize>) -> Self {
39        Self {
40            start: r.start,
41            end: r.end,
42        }
43    }
44}