use std::fmt;
use std::hash::{Hash, Hasher};
use std::ptr;
use std::str;
use position;
pub struct Span<'i> {
input: &'i [u8],
start: usize,
end: usize
}
#[inline]
pub unsafe fn new(input: &[u8], start: usize, end: usize) -> Span {
Span { input, start, end }
}
impl<'i> Span<'i> {
#[inline]
pub fn start(&self) -> usize {
self.start
}
#[inline]
pub fn end(&self) -> usize {
self.end
}
#[inline]
pub fn start_pos(&self) -> position::Position<'i> {
unsafe { position::new(self.input, self.start) }
}
#[inline]
pub fn end_pos(&self) -> position::Position<'i> {
unsafe { position::new(self.input, self.end) }
}
#[inline]
pub fn split(self) -> (position::Position<'i>, position::Position<'i>) {
let pos1 = unsafe { position::new(self.input, self.start) };
let pos2 = unsafe { position::new(self.input, self.end) };
(pos1, pos2)
}
#[inline]
pub fn as_str(&self) -> &'i str {
unsafe { str::from_utf8_unchecked(&self.input[self.start..self.end]) }
}
}
impl<'i> fmt::Debug for Span<'i> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Span")
.field("str", &self.as_str())
.field("start", &self.start)
.field("end", &self.end)
.finish()
}
}
impl<'i> Clone for Span<'i> {
fn clone(&self) -> Span<'i> {
unsafe { new(self.input, self.start, self.end) }
}
}
impl<'i> PartialEq for Span<'i> {
fn eq(&self, other: &Span<'i>) -> bool {
ptr::eq(self.input, other.input) && self.start == other.start && self.end == other.end
}
}
impl<'i> Eq for Span<'i> {}
impl<'i> Hash for Span<'i> {
fn hash<H: Hasher>(&self, state: &mut H) {
(self.input as *const [u8]).hash(state);
self.start.hash(state);
self.end.hash(state);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn split() {
let input = "a";
let start = position::Position::from_start(input);
let mut end = start.clone();
assert!(end.skip(1));
let span = start.clone().span(&end.clone());
assert_eq!(span.split(), (start, end));
}
}