use std::convert::TryInto;
#[repr(C)]
#[derive(Clone, PartialEq, Eq, Copy, Default)]
pub struct Loc {
pub begin: usize,
pub end: usize,
}
impl Loc {
pub fn to_range(&self) -> std::ops::Range<usize> {
self.begin..self.end
}
pub fn size(&self) -> usize {
self.end - self.begin
}
pub fn with_begin(&self, begin: usize) -> Loc {
Self {
begin,
end: self.end,
}
}
pub fn with_end(&self, end: usize) -> Loc {
Self {
begin: self.begin,
end,
}
}
pub fn adjust_begin(&self, delta: i32) -> Loc {
let begin: i32 = self
.begin
.try_into()
.expect("failed to convert location to i32 (is it too big?)");
let begin: usize = (begin + delta)
.try_into()
.expect("failed to convert location to usize (is it negative?)");
Self {
begin,
end: self.end,
}
}
pub fn adjust_end(&self, d: i32) -> Loc {
let end: i32 = self
.end
.try_into()
.expect("failed to convert location to i32 (is it too big?)");
let end: usize = (end + d)
.try_into()
.expect("failed to convert location to usize (is it negative?)");
Self {
begin: self.begin,
end,
}
}
pub fn resize(&self, new_size: usize) -> Loc {
self.with_end(self.begin + new_size)
}
pub fn join(&self, other: &Self) -> Loc {
Self {
begin: std::cmp::min(self.begin, other.begin),
end: std::cmp::max(self.end, other.end),
}
}
pub fn maybe_join(&self, other: &Option<Loc>) -> Loc {
match other.as_ref() {
Some(other) => self.join(other),
None => *self,
}
}
pub fn is_empty(&self) -> bool {
self.begin == self.end
}
pub fn print(&self, name: &str) {
println!(
"{}{} {}",
" ".repeat(self.begin),
"~".repeat(self.size()),
name
)
}
}
impl std::fmt::Debug for Loc {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&format!("{}...{}", self.begin, self.end))
}
}
#[test]
fn test_to_range() {
assert_eq!(Loc { begin: 10, end: 20 }.to_range(), 10..20)
}
#[test]
fn test_fmt() {
assert_eq!(format!("{:?}", Loc { begin: 10, end: 20 }), "10...20")
}
#[test]
fn test_is_empty() {
assert!(Loc { begin: 1, end: 1 }.is_empty());
assert!(!Loc { begin: 1, end: 2 }.is_empty());
}