diff options
Diffstat (limited to 'src/position.rs')
| -rw-r--r-- | src/position.rs | 96 |
1 files changed, 96 insertions, 0 deletions
diff --git a/src/position.rs b/src/position.rs new file mode 100644 index 0000000..24f5309 --- /dev/null +++ b/src/position.rs | |||
| @@ -0,0 +1,96 @@ | |||
| 1 | use std::fmt; | ||
| 2 | use std::cmp::Ordering; | ||
| 3 | |||
| 4 | #[derive(Copy,Clone)] | ||
| 5 | pub struct Position { | ||
| 6 | pub line: u32, | ||
| 7 | pub column: u32, | ||
| 8 | } | ||
| 9 | |||
| 10 | impl Position { | ||
| 11 | pub fn new( line: u32, column: u32 ) -> Self { | ||
| 12 | Self { | ||
| 13 | line, column, | ||
| 14 | } | ||
| 15 | } | ||
| 16 | |||
| 17 | pub fn none() -> Self { | ||
| 18 | Self { | ||
| 19 | line: 0, | ||
| 20 | column: 0, | ||
| 21 | } | ||
| 22 | } | ||
| 23 | |||
| 24 | pub fn is_none(&self) -> bool { | ||
| 25 | self.line == 0 || self.column == 0 | ||
| 26 | } | ||
| 27 | } | ||
| 28 | |||
| 29 | impl fmt::Debug for Position { | ||
| 30 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 31 | if self.is_none() { | ||
| 32 | write!(f, "none") | ||
| 33 | } else { | ||
| 34 | write!(f, "{}:{}", self.line, self.column ) | ||
| 35 | } | ||
| 36 | } | ||
| 37 | } | ||
| 38 | |||
| 39 | impl PartialOrd for Position { | ||
| 40 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | ||
| 41 | let ord = self.line.partial_cmp( &other.line ); | ||
| 42 | if Some(Ordering::Equal) == ord { | ||
| 43 | self.column.partial_cmp( &other.column ) | ||
| 44 | } else { | ||
| 45 | ord | ||
| 46 | } | ||
| 47 | } | ||
| 48 | } | ||
| 49 | |||
| 50 | impl Ord for Position { | ||
| 51 | fn cmp(&self, other: &Self) -> Ordering { | ||
| 52 | let ord = self.line.cmp( &other.line ); | ||
| 53 | if Ordering::Equal == ord { | ||
| 54 | self.column.cmp( &other.column ) | ||
| 55 | } else { | ||
| 56 | ord | ||
| 57 | } | ||
| 58 | } | ||
| 59 | } | ||
| 60 | |||
| 61 | impl PartialEq for Position { | ||
| 62 | fn eq(&self, other: &Self) -> bool { | ||
| 63 | self.line == other.line && self.column == other.column | ||
| 64 | } | ||
| 65 | } | ||
| 66 | |||
| 67 | impl Eq for Position {} | ||
| 68 | |||
| 69 | #[derive(Copy,Clone)] | ||
| 70 | pub struct Range { | ||
| 71 | start: Position, | ||
| 72 | end: Position, | ||
| 73 | } | ||
| 74 | |||
| 75 | impl Range { | ||
| 76 | pub fn new( start: Position, end: Position ) -> Self { | ||
| 77 | Self { | ||
| 78 | start, end, | ||
| 79 | } | ||
| 80 | } | ||
| 81 | |||
| 82 | pub fn include(&mut self, pos: &Position ) { | ||
| 83 | if *pos < self.start { | ||
| 84 | self.start = pos.clone(); | ||
| 85 | } | ||
| 86 | if *pos > self.end { | ||
| 87 | self.end = pos.clone(); | ||
| 88 | } | ||
| 89 | } | ||
| 90 | } | ||
| 91 | |||
| 92 | impl fmt::Debug for Range { | ||
| 93 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 94 | write!(f, "{:?}-{:?}", self.start, self.end ) | ||
| 95 | } | ||
| 96 | } | ||
