pub trait Input<T> where T: Copy {
fn position(&self) -> usize;
fn current(&self) -> Option<T>;
fn advance(&mut self);
fn backward(&mut self, position: usize);
fn segment(&self, start: usize, end: usize) -> Vec<T>;
}
pub struct DataInput<'a, T: 'a> {
pub data: &'a [T],
pub position: usize,
}
impl<'a, T: Copy> DataInput<'a, T> {
pub fn new(input: &'a [T]) -> DataInput<T> {
DataInput {
data: input,
position: 0,
}
}
}
impl<'a, T: Copy> Input<T> for DataInput<'a, T> {
fn position(&self) -> usize {
self.position
}
fn current(&self) -> Option<T>
{
if self.position < self.data.len() {
Some(self.data[self.position])
} else {
None
}
}
fn advance(&mut self) {
self.position += 1;
}
fn backward(&mut self, position: usize) {
self.position = position;
}
fn segment(&self, start: usize, end: usize) -> Vec<T> {
self.data[start..end].to_vec()
}
}
pub struct TextInput<'a> {
pub text: &'a str,
pub position: usize,
}
impl<'a> TextInput<'a> {
pub fn new(input: &'a str) -> TextInput<'a> {
TextInput {
text: input,
position: 0,
}
}
}
impl<'a> Input<char> for TextInput<'a> {
fn position(&self) -> usize {
self.position
}
fn current(&self) -> Option<char>
{
self.text[self.position..].chars().next()
}
fn advance(&mut self) {
if let Some(c) = self.text[self.position..].chars().next() {
self.position += c.len_utf8();
}
}
fn backward(&mut self, position: usize) {
self.position = position;
}
fn segment(&self, start: usize, end: usize) -> Vec<char> {
self.text[start..end].chars().collect()
}
}