luau_lexer/
position.rs

1//! The [`PositionExt`]
2
3use lsp_types::Position;
4
5/// Extands the [`Position`] type by adding helper functions.
6pub trait Ext {
7    /// The largest value that can be represented by a [`Position`].
8    const MAX: Self;
9    /// The smallest value that can be represented by a [`Position`].
10    const MIN: Self;
11
12    /// Offsets the current position by lines and characters. If you're adding both
13    /// lines and characters, making sure to set characters to `0` before calling
14    /// this function to ensure correct results.
15    fn offset(&mut self, lines: i32, characters: i32);
16
17    /// Sets line to a specific value.
18    fn set_line(&mut self, line: u32);
19
20    /// Sets character to a specific value.
21    fn set_character(&mut self, character: u32);
22
23    /// Checks whether or not this position is between the 2 passed positions.
24    fn is_in_bounds(&self, start: Self, end: Self) -> bool;
25
26    /// Checks whether or not this position is after the passed position.
27    fn is_after(&self, position: Self) -> bool;
28
29    /// Checks whether or not this position is before the passed position.
30    fn is_before(&self, position: Self) -> bool;
31}
32
33impl Ext for Position {
34    const MAX: Self = Self {
35        line: u32::MAX,
36        character: u32::MAX,
37    };
38
39    const MIN: Self = Self {
40        line: u32::MIN,
41        character: u32::MIN,
42    };
43
44    #[inline]
45    fn offset(&mut self, lines: i32, characters: i32) {
46        self.line = self.line.saturating_add_signed(lines);
47        self.character = self.character.saturating_add_signed(characters);
48    }
49
50    #[inline]
51    fn set_line(&mut self, line: u32) {
52        self.line = line;
53    }
54
55    #[inline]
56    fn set_character(&mut self, character: u32) {
57        self.character = character;
58    }
59
60    #[inline]
61    fn is_in_bounds(&self, start: Self, end: Self) -> bool {
62        self.is_after(start) & self.is_before(end)
63    }
64
65    #[inline]
66    fn is_after(&self, position: Self) -> bool {
67        self.line > position.line
68            || position.line == self.line && self.character >= position.character
69    }
70
71    #[inline]
72    fn is_before(&self, position: Self) -> bool {
73        self.line < position.line
74            || position.line == self.line && self.character <= position.character
75    }
76}