Visual Studio Code, rebuilt in Rust
Rust
//! length.ts: a length in a document, or an offset from its start, as a line count and the column count (bytes)
//! of the last line.
use std::ops::Add;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Length {
pub lines: usize,
pub columns: usize,
}
impl Length {
pub const ZERO: Length = Length { lines: 0, columns: 0 };
pub fn new(lines: usize, columns: usize) -> Self {
Length { lines, columns }
}
pub fn is_zero(self) -> bool {
self == Length::ZERO
}
/// `lengthDiffNonNegative`: the length from `self` to `end`, zero when `end` is not after `self`.
pub fn until(self, end: Length) -> Length {
if end <= self {
Length::ZERO
} else if self.lines == end.lines {
Length::new(0, end.columns - self.columns)
} else {
Length::new(end.lines - self.lines, end.columns)
}
}
}
/// `lengthAdd`: a length with lines restarts the column count.
impl Add for Length {
type Output = Length;
fn add(self, other: Length) -> Length {
if other.lines == 0 { Length::new(self.lines, self.columns + other.columns) } else { Length::new(self.lines + other.lines, other.columns) }
}
}
#[cfg(test)]
mod tests {
use super::*;
/// length.test.ts "Basic".
#[test]
fn adding_a_length_with_lines_restarts_the_columns() {
let l1 = Length::new(100, 10);
assert_eq!(l1 + Length::new(100, 10), Length::new(200, 10));
assert_eq!(l1 + Length::new(0, 10), Length::new(100, 20));
}
/// length.test.ts "lengthDiffNonNeg".
#[test]
fn the_length_until_an_earlier_offset_is_zero() {
assert_eq!(Length::new(100, 10).until(Length::new(100, 20)), Length::new(0, 10));
assert_eq!(Length::new(100, 10).until(Length::new(101, 20)), Length::new(1, 20));
assert_eq!(Length::new(101, 30).until(Length::new(101, 20)), Length::ZERO);
assert_eq!(Length::new(102, 10).until(Length::new(101, 20)), Length::ZERO);
}
}