use std::cmp::Ordering;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct Position {
pub line: usize,
pub column: usize,
}
impl Position {
pub const fn new(line: usize, column: usize) -> Self {
Self { line, column }
}
pub const ORIGIN: Position = Position { line: 0, column: 0 };
pub const fn line_start(line: usize) -> Self {
Self { line, column: 0 }
}
}
impl PartialOrd for Position {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Position {
fn cmp(&self, other: &Self) -> Ordering {
self.line
.cmp(&other.line)
.then_with(|| self.column.cmp(&other.column))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Range {
pub start: Position,
pub end: Position,
}
impl Range {
pub fn new(a: Position, b: Position) -> Self {
if a <= b {
Self { start: a, end: b }
} else {
Self { start: b, end: a }
}
}
pub const fn empty(position: Position) -> Self {
Self {
start: position,
end: position,
}
}
pub fn is_empty(&self) -> bool {
self.start == self.end
}
pub fn is_multiline(&self) -> bool {
self.start.line != self.end.line
}
pub fn contains(&self, position: Position) -> bool {
position >= self.start && position < self.end
}
pub fn line_span(&self) -> std::ops::RangeInclusive<usize> {
self.start.line..=self.end.line
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn positions_order_by_line_then_column() {
assert!(Position::new(0, 9) < Position::new(1, 0));
assert!(Position::new(2, 3) < Position::new(2, 4));
assert_eq!(Position::new(1, 1), Position::new(1, 1));
}
#[test]
fn range_normalises_reversed_endpoints() {
let a = Position::new(4, 2);
let b = Position::new(1, 7);
let range = Range::new(a, b);
assert_eq!(range.start, b);
assert_eq!(range.end, a);
}
#[test]
fn empty_range_contains_nothing() {
let range = Range::empty(Position::new(3, 3));
assert!(range.is_empty());
assert!(!range.contains(Position::new(3, 3)));
}
#[test]
fn contains_is_end_exclusive() {
let range = Range::new(Position::new(0, 2), Position::new(0, 5));
assert!(!range.contains(Position::new(0, 1)));
assert!(range.contains(Position::new(0, 2)));
assert!(range.contains(Position::new(0, 4)));
assert!(!range.contains(Position::new(0, 5)));
}
#[test]
fn line_span_covers_both_endpoints() {
let range = Range::new(Position::new(2, 0), Position::new(5, 1));
let lines: Vec<usize> = range.line_span().collect();
assert_eq!(lines, vec![2, 3, 4, 5]);
assert!(range.is_multiline());
}
}