Skip to main content

mq_lang/
range.rs

1#[cfg(feature = "ast-json")]
2use serde::{Deserialize, Serialize};
3
4/// A position in source code, representing a line and column.
5#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
6#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Hash)]
7pub struct Position {
8    /// One-based line number.
9    pub line: u32,
10    /// One-based column number.
11    pub column: u32,
12}
13
14impl Default for Position {
15    fn default() -> Self {
16        Position { line: 1, column: 1 }
17    }
18}
19
20impl Position {
21    /// Creates a new position with the specified line and column.
22    pub fn new(line: u32, column: u32) -> Self {
23        Position { line, column }
24    }
25}
26
27/// A range in source code, spanning from a start position to an end position.
28#[cfg_attr(feature = "ast-json", derive(Serialize, Deserialize))]
29#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Default, Hash)]
30pub struct Range {
31    /// Start of the range.
32    pub start: Position,
33    /// End of the range.
34    pub end: Position,
35}
36
37impl Range {
38    /// Returns `true` if the specified position falls within this range (inclusive).
39    pub fn contains(&self, position: &Position) -> bool {
40        (self.start.line < position.line || (self.start.line == position.line && self.start.column <= position.column))
41            && (self.end.line > position.line || (self.end.line == position.line && self.end.column >= position.column))
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_position_and_range_size() {
51        assert_eq!(std::mem::size_of::<Position>(), 8);
52        assert_eq!(std::mem::size_of::<Range>(), 16);
53    }
54}