lexer_rs/posn_and_span/
stream_char_span.rs

1//a Imports
2use std::ops::Range;
3
4use crate::PosnInCharStream;
5
6//a StreamCharSpan
7//tp StreamCharSpan
8/// This provides a span between two byte offsets within a stream; the start and end have
9/// an associated position that might also ccurately provide line and
10/// column numbers
11///
12/// This can be used as within tokens for a lexer; if
13/// [crate::LineColumn] is used for the generic argument then the
14/// lexer will correctly track the line and column of the span of
15/// tokens, and parsers can correctly track real spans of the tokens,
16/// which allows for suitable formatting of errors etc within their
17/// context (see [crate::FmtContext] also).
18#[derive(Debug, Clone, Copy)]
19pub struct StreamCharSpan<P>
20where
21    P: PosnInCharStream,
22{
23    start: P,
24    end: P,
25}
26
27//ip StreamCharSpan
28impl<P> StreamCharSpan<P>
29where
30    P: PosnInCharStream,
31{
32    //fp new
33    /// Create a new [StreamCharSpan]
34    pub fn new(start: P, end: P) -> Self {
35        Self { start, end }
36    }
37
38    //fp new_at
39    /// Create a new [StreamCharSpan]
40    pub fn new_at(posn: &P) -> Self {
41        Self {
42            start: *posn,
43            end: *posn,
44        }
45    }
46
47    //cp end_at
48    /// Create a new [StreamCharSpan]
49    pub fn end_at(mut self, posn: &P) -> Self {
50        self.end = *posn;
51        self
52    }
53
54    //ap start
55    /// Get the start of the span
56    pub fn start(&self) -> &P {
57        &self.start
58    }
59
60    //ap end
61    /// Get the end of the span
62    pub fn end(&self) -> &P {
63        &self.end
64    }
65
66    //mp byte_range
67    /// Get the range between the two positions of this [StreamCharSpan]
68    pub fn byte_range(&self) -> Range<usize> {
69        let start = self.start.byte_ofs();
70        let end = self.end.byte_ofs();
71        Range { start, end }
72    }
73}