I've been working on a Tokeniser/Lexer in Rust. I would like to have the tokeniser take input from different sources, such as files or in-memory strings. To abstract over this concern i've created a trait Source
. This has left me with a wonky situation where I appear to need a PhantomData
member in the token iterator. I've created a cut-down example here:
/// Source of Characters
///
/// In this example all that a source can do is be sliced to retrieve
/// a subsection of the overall character buffer.
trait Source<'a> {
/// Character at Offset
///
/// Gets the character at the given offset in the buffer and
/// returns it. If no character is available at that offset `None`
/// is returned.
fn at(&self, offset: usize) -> Option<(char, usize)>;
/// Slice the Source Buffer
fn slice(&self, start: usize, end: usize) -> &'a str;
}
/// Source of Characters from a `str` Slice
struct StringSource<'a> {
pub buff: &'a str
}
/// Implementation of the Source trait.
impl<'a> Source<'a> for StringSource<'a> {
fn at(&self, offset: usize) -> Option<(char, usize)> {
self.buff[offset..].chars().nth(0).map(|ch| { (ch, offset + ch.len_utf8()) })
}
fn slice(&self, start: usize, end: usize) -> &'a str {
&self.buff[start..end]
}
}
/// Token Iterator Implementation
///
/// This token iterator takes a given source and steps through it returning string slices for each token
struct TokenIter<'a, S>
where S: Source<'a>,
S: 'a
{
source: S,
idx: usize,
phantom: ::std::marker::PhantomData<&'a ()>,
}
impl<'a, S> TokenIter<'a, S>
where S: Source<'a>
{
/// Create a Token Iterator from a Source
fn new(source: S) -> Self {
TokenIter {
source: source,
idx: 0,
phantom: ::std::marker::PhantomData,
}
}
}
/// Token Iterators implement `Iterator`
impl<'a, S> Iterator for TokenIter<'a, S>
where S: Source<'a>
{
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
let ts = self.idx;
self.source.at(ts).map(|(_ch, next)| {
self.idx = next;
// Imagine a regex state machine is run here to produce a token
// rather than just returning single-character tokens.
self.source.slice(ts, next)
})
}
}
fn main() {
let source = StringSource{ buff: "hello world" };
let iter = TokenIter::new(source);
println!("{:?}", iter.collect::<Vec<_>>());
}
Run it here: https://is.gd/OCL91u
Is there a nicer way to express the source buffer lifetime 'a
so that I don't need a PhantomData
member or this bit of funky lifetime constraints:
where S: Source<'a>,
S: 'a