use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Position {
pub line: u32,
pub column: u32,
pub offset: u32,
}
impl Position {
pub const ZERO: Self = Self { line: 0, column: 0, offset: 0 };
#[inline]
pub const fn new(line: u32, column: u32, offset: u32) -> Self {
Self { line, column, offset }
}
}
impl Default for Position {
#[inline]
fn default() -> Self {
Self::ZERO
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Span {
pub start: Position,
pub end: Position,
}
impl Span {
#[inline]
pub const fn new(start: Position, end: Position) -> Self {
Self { start, end }
}
#[inline]
pub const fn point(pos: Position) -> Self {
Self { start: pos, end: pos }
}
#[inline]
#[must_use]
pub fn contains(&self, pos: Position) -> bool {
(self.start.offset..self.end.offset).contains(&pos.offset)
}
#[inline]
#[must_use]
pub fn merge(self, other: Span) -> Span {
let start = if self.start.offset <= other.start.offset { self.start } else { other.start };
let end = if self.end.offset >= other.end.offset { self.end } else { other.end };
Span::new(start, end)
}
#[inline]
#[must_use]
pub fn len(&self) -> u32 {
self.end.offset.saturating_sub(self.start.offset)
}
#[inline]
pub fn is_empty(&self) -> bool {
self.start.offset >= self.end.offset
}
}
impl Default for Span {
#[inline]
fn default() -> Self {
Self::point(Position::ZERO)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_position_new() {
let pos = Position::new(1, 5, 10);
assert_eq!(pos.line, 1);
assert_eq!(pos.column, 5);
assert_eq!(pos.offset, 10);
}
#[test]
fn test_span_contains() {
let span = Span::new(Position::new(0, 0, 0), Position::new(0, 10, 10));
assert!(span.contains(Position::new(0, 5, 5)));
assert!(!span.contains(Position::new(0, 15, 15)));
}
#[test]
fn test_span_merge() {
let span1 = Span::new(Position::new(0, 0, 0), Position::new(0, 5, 5));
let span2 = Span::new(Position::new(0, 3, 3), Position::new(0, 10, 10));
let merged = span1.merge(span2);
assert_eq!(merged.start.offset, 0);
assert_eq!(merged.end.offset, 10);
}
}