Skip to main content

cljrs_types/
span.rs

1use serde::{Deserialize, Serialize};
2use std::sync::Arc;
3
4/// A half-open byte range `[start, end)` within a named source file.
5#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
6pub struct Span {
7    /// File path on disk, or `"<repl>"` for interactive input.
8    pub file: Arc<String>,
9    /// Inclusive start byte offset.
10    pub start: usize,
11    /// Exclusive end byte offset.
12    pub end: usize,
13    /// 1-based line number of `start`.
14    pub line: u32,
15    /// 1-based column number of `start` (in bytes).
16    pub col: u32,
17}
18
19impl Span {
20    pub fn new(file: Arc<String>, start: usize, end: usize, line: u32, col: u32) -> Self {
21        Self {
22            file,
23            start,
24            end,
25            line,
26            col,
27        }
28    }
29
30    pub fn len(&self) -> usize {
31        self.end.saturating_sub(self.start)
32    }
33
34    pub fn is_empty(&self) -> bool {
35        self.len() == 0
36    }
37}
38
39impl From<&Span> for miette::SourceSpan {
40    fn from(span: &Span) -> Self {
41        miette::SourceSpan::new(miette::SourceOffset::from(span.start), span.len())
42    }
43}
44
45impl From<Span> for miette::SourceSpan {
46    fn from(span: Span) -> Self {
47        (&span).into()
48    }
49}