|
| 1 | +use std::cmp::{max, min}; |
| 2 | + |
| 3 | +#[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 4 | +/// A position represents a rectangle in the source code. |
| 5 | +pub struct Position { |
| 6 | + pub start: CaretPos, |
| 7 | + pub end: CaretPos |
| 8 | +} |
| 9 | + |
| 10 | +#[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 11 | +/// An endpoint represents either the top left or bottom right points of a |
| 12 | +/// [Position] rectangle. |
| 13 | +/// |
| 14 | +/// Line's and position's are 1-indexed. |
| 15 | +pub struct CaretPos { |
| 16 | + pub line: i32, |
| 17 | + pub pos: i32 |
| 18 | +} |
| 19 | + |
| 20 | +impl Position { |
| 21 | + pub fn new(start: &CaretPos, end: &CaretPos) -> Position { |
| 22 | + Position { start: start.clone(), end: end.clone() } |
| 23 | + } |
| 24 | + |
| 25 | + /// Get the absolute width of a position, which represents a rectangle in |
| 26 | + /// the source code. |
| 27 | + /// |
| 28 | + /// Width is always 1 or greater. |
| 29 | + pub fn get_width(&self) -> i32 { |
| 30 | + max(1, max(self.end.pos - self.start.pos, self.start.pos - self.end.pos)) |
| 31 | + } |
| 32 | + |
| 33 | + pub fn union(&self, other: &Position) -> Position { |
| 34 | + Position { |
| 35 | + start: CaretPos { |
| 36 | + line: min(self.start.line, other.start.line), |
| 37 | + pos: min(self.start.pos, other.start.pos) |
| 38 | + }, |
| 39 | + end: CaretPos { |
| 40 | + line: max(self.end.line, other.end.line), |
| 41 | + pos: max(self.end.pos, other.end.pos) |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +impl CaretPos { |
| 48 | + /// Create new endpoint with given line and position. |
| 49 | + pub fn new(line: i32, pos: i32) -> CaretPos { CaretPos { line, pos } } |
| 50 | + |
| 51 | + /// Create new [EndPoint] which is offset in the vertical direction by the |
| 52 | + /// given amount. |
| 53 | + pub fn offset_line(self, offset: i32) -> CaretPos { |
| 54 | + CaretPos { line: self.line + offset, pos: self.pos } |
| 55 | + } |
| 56 | + |
| 57 | + /// Create new [EndPoint] which is offset in the horizontal direction by the |
| 58 | + /// given amount. |
| 59 | + pub fn offset_pos(self, offset: i32) -> CaretPos { |
| 60 | + CaretPos { line: self.line, pos: self.pos + offset } |
| 61 | + } |
| 62 | + |
| 63 | + pub fn newline(self) -> CaretPos { CaretPos { line: self.line + 1, pos: 1 } } |
| 64 | +} |
| 65 | + |
| 66 | +impl Default for Position { |
| 67 | + fn default() -> Self { Position { start: CaretPos::default(), end: CaretPos::default() } } |
| 68 | +} |
| 69 | + |
| 70 | +impl Default for CaretPos { |
| 71 | + fn default() -> Self { CaretPos { line: 1, pos: 1 } } |
| 72 | +} |
0 commit comments