#![allow(clippy::len_without_is_empty)]
use std::cmp::Ordering;
use std::fmt::{Display, Formatter};
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Coords {
pub absolute: usize,
pub line: usize,
pub column: usize,
}
impl Coords {
#[inline]
pub fn inc(&mut self, newline: bool) {
if newline {
self.absolute += 1;
self.line += 1;
self.column = 1;
} else {
self.absolute += 1;
self.column += 1;
}
}
}
impl Display for Coords {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"[abs: {}, line: {}, column: {}]",
self.absolute, self.line, self.column
)
}
}
impl Default for Coords {
fn default() -> Self {
Coords {
absolute: 0,
line: 1,
column: 0,
}
}
}
impl Eq for Coords {}
impl PartialOrd<Self> for Coords {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match self.absolute.cmp(&other.absolute) {
Ordering::Less => Some(Ordering::Less),
Ordering::Equal => Some(Ordering::Equal),
Ordering::Greater => Some(Ordering::Greater),
}
}
}
impl Ord for Coords {
fn cmp(&self, other: &Self) -> Ordering {
self.absolute.cmp(&other.absolute)
}
}
impl std::ops::Sub for Coords {
type Output = usize;
fn sub(self, rhs: Self) -> Self::Output {
self.absolute - rhs.absolute
}
}
#[derive(Debug, Default, Copy, Clone, PartialEq, PartialOrd)]
pub struct Span {
pub start: Coords,
pub end: Coords,
}
impl Span {
pub fn len(&self) -> usize {
match self.start.cmp(&self.end) {
Ordering::Less => self.end - self.start,
Ordering::Equal => 1,
Ordering::Greater => self.start - self.end,
}
}
}
impl Display for Span {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"start: {}, end: {}, length: {}",
self.start,
self.end,
self.len()
)
}
}