harper_core/
span.rs

1use std::ops::Range;
2
3use serde::{Deserialize, Serialize};
4
5use crate::CharStringExt;
6
7/// A window in a [`char`] sequence.
8///
9/// Although specific to `harper.js`, [this page may clear up any questions you have](https://writewithharper.com/docs/harperjs/spans).
10#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
11pub struct Span {
12    pub start: usize,
13    pub end: usize,
14}
15
16impl Span {
17    pub fn new(start: usize, end: usize) -> Self {
18        if start > end {
19            panic!("{} > {}", start, end);
20        }
21        Self { start, end }
22    }
23
24    pub fn new_with_len(start: usize, len: usize) -> Self {
25        Self {
26            start,
27            end: start + len,
28        }
29    }
30
31    pub fn len(&self) -> usize {
32        self.end - self.start
33    }
34
35    pub fn is_empty(&self) -> bool {
36        self.len() == 0
37    }
38
39    pub fn contains(&self, idx: usize) -> bool {
40        assert!(self.start <= self.end);
41
42        self.start <= idx && idx < self.end
43    }
44
45    pub fn overlaps_with(&self, other: Self) -> bool {
46        (self.start < other.end) && (other.start < self.end)
47    }
48
49    /// Get the associated content. Will return [`None`] if any aspect is
50    /// invalid.
51    pub fn try_get_content<'a>(&self, source: &'a [char]) -> Option<&'a [char]> {
52        if (self.start > self.end) || (self.start >= source.len()) || (self.end > source.len()) {
53            if self.is_empty() {
54                return Some(&source[0..0]);
55            }
56            return None;
57        }
58
59        Some(&source[self.start..self.end])
60    }
61
62    /// Get the associated content. Will panic if any aspect is invalid.
63    pub fn get_content<'a>(&self, source: &'a [char]) -> &'a [char] {
64        match self.try_get_content(source) {
65            Some(v) => v,
66            None => panic!(
67                "Could not get position {:?} within \"{}\"",
68                self,
69                source.to_string()
70            ),
71        }
72    }
73
74    pub fn get_content_string(&self, source: &[char]) -> String {
75        String::from_iter(self.get_content(source))
76    }
77
78    pub fn set_len(&mut self, length: usize) {
79        self.end = self.start + length;
80    }
81
82    pub fn with_len(&self, length: usize) -> Self {
83        let mut cloned = *self;
84        cloned.set_len(length);
85        cloned
86    }
87
88    // Add an amount to both [`Self::start`] and [`Self::end`]
89    pub fn push_by(&mut self, by: usize) {
90        self.start += by;
91        self.end += by;
92    }
93
94    // Subtract an amount to both [`Self::start`] and [`Self::end`]
95    pub fn pull_by(&mut self, by: usize) {
96        self.start -= by;
97        self.end -= by;
98    }
99
100    // Add an amount to a copy of both [`Self::start`] and [`Self::end`]
101    pub fn pushed_by(&self, by: usize) -> Self {
102        let mut clone = *self;
103        clone.start += by;
104        clone.end += by;
105        clone
106    }
107
108    // Subtract an amount to a copy of both [`Self::start`] and [`Self::end`]
109    pub fn pulled_by(&self, by: usize) -> Option<Self> {
110        if by > self.start {
111            return None;
112        }
113
114        let mut clone = *self;
115        clone.start -= by;
116        clone.end -= by;
117        Some(clone)
118    }
119
120    // Add an amount a copy of both [`Self::start`] and [`Self::end`]
121    pub fn with_offset(&self, by: usize) -> Self {
122        let mut clone = *self;
123        clone.push_by(by);
124        clone
125    }
126}
127
128impl From<Range<usize>> for Span {
129    fn from(value: Range<usize>) -> Self {
130        Self::new(value.start, value.end)
131    }
132}
133
134impl From<Span> for Range<usize> {
135    fn from(value: Span) -> Self {
136        value.start..value.end
137    }
138}
139
140impl IntoIterator for Span {
141    type Item = usize;
142
143    type IntoIter = Range<usize>;
144
145    fn into_iter(self) -> Self::IntoIter {
146        self.start..self.end
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use crate::Span;
153
154    #[test]
155    fn overlaps() {
156        assert!(Span::new(0, 5).overlaps_with(Span::new(3, 6)));
157        assert!(Span::new(0, 5).overlaps_with(Span::new(2, 3)));
158        assert!(Span::new(0, 5).overlaps_with(Span::new(4, 5)));
159        assert!(Span::new(0, 5).overlaps_with(Span::new(4, 4)));
160
161        assert!(!Span::new(0, 3).overlaps_with(Span::new(3, 5)));
162    }
163}