pub type Slot = Option<usize>;
pub trait RegularExpression: Sized {
type Text: ?Sized;
fn slots_len(&self) -> usize;
fn next_after_empty(&self, text: &Self::Text, i: usize) -> usize;
fn shortest_match_at(
&self,
text: &Self::Text,
start: usize,
) -> Option<usize>;
fn is_match_at(
&self,
text: &Self::Text,
start: usize,
) -> bool;
fn find_at(
&self,
text: &Self::Text,
start: usize,
) -> Option<(usize, usize)>;
fn read_captures_at(
&self,
slots: &mut [Slot],
text: &Self::Text,
start: usize,
) -> Option<(usize, usize)>;
fn find_iter<'t>(
self,
text: &'t Self::Text,
) -> FindMatches<'t, Self> {
FindMatches {
re: self,
text: text,
last_end: 0,
last_match: None,
}
}
fn captures_iter<'t>(
self,
text: &'t Self::Text,
) -> FindCaptures<'t, Self> {
FindCaptures(self.find_iter(text))
}
}
pub struct FindMatches<'t, R> where R: RegularExpression, R::Text: 't {
re: R,
text: &'t R::Text,
last_end: usize,
last_match: Option<usize>,
}
impl<'t, R> FindMatches<'t, R> where R: RegularExpression, R::Text: 't {
pub fn text(&self) -> &'t R::Text {
self.text
}
pub fn regex(&self) -> &R {
&self.re
}
}
impl<'t, R> Iterator for FindMatches<'t, R>
where R: RegularExpression, R::Text: 't + AsRef<[u8]> {
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
if self.last_end > self.text.as_ref().len() {
return None;
}
let (s, e) = match self.re.find_at(self.text, self.last_end) {
None => return None,
Some((s, e)) => (s, e),
};
if s == e {
self.last_end = self.re.next_after_empty(&self.text, e);
if Some(e) == self.last_match {
return self.next();
}
} else {
self.last_end = e;
}
self.last_match = Some(e);
Some((s, e))
}
}
pub struct FindCaptures<'t, R>(FindMatches<'t, R>)
where R: RegularExpression, R::Text: 't;
impl<'t, R> FindCaptures<'t, R> where R: RegularExpression, R::Text: 't {
pub fn text(&self) -> &'t R::Text {
self.0.text()
}
pub fn regex(&self) -> &R {
self.0.regex()
}
}
impl<'t, R> Iterator for FindCaptures<'t, R>
where R: RegularExpression, R::Text: 't + AsRef<[u8]> {
type Item = Vec<Slot>;
fn next(&mut self) -> Option<Vec<Slot>> {
if self.0.last_end > self.0.text.as_ref().len() {
return None
}
let mut slots = vec![None; self.0.re.slots_len()];
let (s, e) = match self.0.re.read_captures_at(
&mut slots,
self.0.text,
self.0.last_end,
) {
None => return None,
Some((s, e)) => (s, e),
};
if s == e {
self.0.last_end = self.0.re.next_after_empty(&self.0.text, e);
if Some(e) == self.0.last_match {
return self.next();
}
} else {
self.0.last_end = e;
}
self.0.last_match = Some(e);
Some(slots)
}
}