From 9ce4db545efba697f20ab5cecbefc0589c7146ca Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sun, 31 Dec 2017 17:54:33 +0300 Subject: Parser: groundwork --- src/text.rs | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) (limited to 'src/text.rs') diff --git a/src/text.rs b/src/text.rs index c3ef1ac8e..ee0dc8398 100644 --- a/src/text.rs +++ b/src/text.rs @@ -56,4 +56,63 @@ impl ops::SubAssign for TextUnit { fn sub_assign(&mut self, rhs: TextUnit) { self.0 -= rhs.0 } +} + + +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct TextRange { + start: TextUnit, + end: TextUnit, +} + +impl fmt::Debug for TextRange { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ::fmt(self, f) + } +} + +impl fmt::Display for TextRange { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "[{}; {})", self.start(), self.end()) + } +} + + +impl TextRange { + pub fn empty() -> TextRange { + TextRange::from_to(TextUnit::new(0), TextUnit::new(0)) + } + + pub fn from_to(from: TextUnit, to: TextUnit) -> TextRange { + assert!(from <= to, "Invalid text range [{}; {})", from, to); + TextRange { start: from, end: to } + } + + pub fn from_len(from: TextUnit, len: TextUnit) -> TextRange { + TextRange::from_to(from, from + len) + } + + pub fn start(&self) -> TextUnit { + self.start + } + + pub fn end(&self) -> TextUnit { + self.end + } + + pub fn len(&self) -> TextUnit { + self.end - self.start + } + + pub fn is_empty(&self) -> bool { + self.start() == self.end() + } +} + +impl ops::Index for str { + type Output = str; + + fn index(&self, index: TextRange) -> &str { + &self[index.start().0 as usize..index.end().0 as usize] + } } \ No newline at end of file -- cgit v1.2.3