use std::borrow::Cow;
use std::collections::HashMap;
use std::collections::hash_map;
use std::fmt;
use std::ops::Index;
use std::str::FromStr;
use std::sync::Arc;
use memchr::memchr;
use exec::{Exec, ExecBuilder};
use expand::expand;
use error::Error;
use params::{Params, Slot};
pub use set::RegexSetBytes as RegexSet;
pub use set::SetMatchesBytes as SetMatches;
pub use set::SetMatchesIterBytes as SetMatchesIterBytes;
pub use set::SetMatchesIntoIterBytes as SetMatchesIntoIterBytes;
#[derive(Clone)]
pub struct Regex(Exec);
impl fmt::Display for Regex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl fmt::Debug for Regex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
#[doc(hidden)]
impl From<Exec> for Regex {
fn from(exec: Exec) -> Regex {
Regex(exec)
}
}
impl FromStr for Regex {
type Err = Error;
fn from_str(s: &str) -> Result<Regex, Error> {
Regex::new(s)
}
}
impl Regex {
pub fn new(re: &str) -> Result<Regex, Error> {
Regex::with_size_limit(10 * (1 << 20), re)
}
pub fn with_size_limit(size: usize, re: &str) -> Result<Regex, Error> {
ExecBuilder::new(re)
.only_utf8(false)
.size_limit(size)
.build()
.map(Regex)
}
pub fn is_match(&self, text: &[u8]) -> bool {
self.exec(&mut [], text, 0)
}
pub fn find(&self, text: &[u8]) -> Option<(usize, usize)> {
let mut caps = [None, None];
if !self.exec(&mut caps, text, 0) {
None
} else {
Some((caps[0].unwrap(), caps[1].unwrap()))
}
}
pub fn find_iter<'r, 't>(&'r self, text: &'t [u8]) -> FindMatches<'r, 't> {
FindMatches {
re: self,
text: text,
last_end: 0,
last_match: None,
}
}
pub fn captures<'t>(&self, text: &'t [u8]) -> Option<Captures<'t>> {
let mut caps = self.alloc_captures();
if !self.exec(&mut caps, text, 0) {
None
} else {
Some(Captures {
text: text,
caps: caps,
named_groups: self.0.capture_name_idx().clone(),
})
}
}
pub fn captures_iter<'r, 't>(
&'r self,
text: &'t [u8],
) -> FindCaptures<'r, 't> {
FindCaptures {
re: self,
text: text,
last_end: 0,
last_match: None,
}
}
pub fn split<'r, 't>(&'r self, text: &'t [u8]) -> Splits<'r, 't> {
Splits {
finder: self.find_iter(text),
last: 0,
}
}
pub fn splitn<'r, 't>(
&'r self,
text: &'t [u8],
limit: usize,
) -> SplitsN<'r, 't> {
SplitsN {
splits: self.split(text),
n: limit,
}
}
pub fn replace<R: Replacer>(&self, text: &[u8], rep: R) -> Vec<u8> {
self.replacen(text, 1, rep)
}
pub fn replace_all<R: Replacer>(&self, text: &[u8], rep: R) -> Vec<u8> {
self.replacen(text, 0, rep)
}
pub fn replacen<R: Replacer>(
&self,
text: &[u8],
limit: usize,
mut rep: R,
) -> Vec<u8> {
if let Some(rep) = rep.no_expansion() {
let mut new = Vec::with_capacity(text.len());
let mut last_match = 0;
for (i, (s, e)) in self.find_iter(text).enumerate() {
if limit > 0 && i >= limit {
break
}
new.extend(&text[last_match..s]);
new.extend(&*rep);
last_match = e;
}
new.extend(&text[last_match..]);
return new;
}
let mut new = Vec::with_capacity(text.len());
let mut last_match = 0;
for (i, cap) in self.captures_iter(text).enumerate() {
if limit > 0 && i >= limit {
break
}
let (s, e) = cap.pos(0).unwrap();
new.extend(&text[last_match..s]);
rep.replace_append(&cap, &mut new);
last_match = e;
}
new.extend(&text[last_match..]);
new
}
pub fn shortest_match(&self, text: &[u8]) -> Option<usize> {
let mut caps = [None, None];
let mut _matched = [false];
let mut params =
Params::new(&mut caps, &mut _matched).set_match_short(true);
if !self.execp(&mut params, text, 0) {
None
} else {
params.captures()[1]
}
}
pub fn as_str(&self) -> &str {
&self.0.regex_strings()[0]
}
pub fn capture_names(&self) -> CaptureNames {
CaptureNames(self.0.captures().iter())
}
pub fn captures_len(&self) -> usize {
self.0.captures().len()
}
fn exec(&self, caps: &mut [Slot], text: &[u8], start: usize) -> bool {
let mut _matches = [false];
let mut params = Params::new(caps, &mut _matches);
self.0.exec(&mut params, text, start)
}
fn execp(&self, params: &mut Params, text: &[u8], start: usize) -> bool {
self.0.exec(params, text, start)
}
fn alloc_captures(&self) -> Vec<Option<usize>> {
vec![None; 2 * self.0.captures().len()]
}
}
pub struct FindMatches<'r, 't> {
re: &'r Regex,
text: &'t [u8],
last_end: usize,
last_match: Option<usize>,
}
impl<'r, 't> Iterator for FindMatches<'r, 't> {
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
if self.last_end > self.text.len() {
return None
}
let mut caps = [None, None];
if !self.re.exec(&mut caps, self.text, self.last_end) {
return None;
}
let (s, e) = (caps[0].unwrap(), caps[1].unwrap());
if e == s && Some(self.last_end) == self.last_match {
if self.last_end >= self.text.len() {
return None;
}
self.last_end += 1;
return self.next();
}
self.last_end = e;
self.last_match = Some(self.last_end);
Some((s, e))
}
}
pub struct FindCaptures<'r, 't> {
re: &'r Regex,
text: &'t [u8],
last_end: usize,
last_match: Option<usize>,
}
impl<'r, 't> Iterator for FindCaptures<'r, 't> {
type Item = Captures<'t>;
fn next(&mut self) -> Option<Captures<'t>> {
if self.last_end > self.text.len() {
return None
}
let mut caps = self.re.alloc_captures();
if !self.re.exec(&mut caps, self.text, self.last_end) {
return None;
}
let (s, e) = (caps[0].unwrap(), caps[1].unwrap());
if e == s && Some(self.last_end) == self.last_match {
if self.last_end >= self.text.len() {
return None;
}
self.last_end += 1;
return self.next();
}
self.last_end = e;
self.last_match = Some(self.last_end);
Some(Captures {
text: self.text,
caps: caps,
named_groups: self.re.0.capture_name_idx().clone(),
})
}
}
pub struct Splits<'r, 't> {
finder: FindMatches<'r, 't>,
last: usize,
}
impl<'r, 't> Iterator for Splits<'r, 't> {
type Item = &'t [u8];
fn next(&mut self) -> Option<&'t [u8]> {
let text = self.finder.text;
match self.finder.next() {
None => {
if self.last >= text.len() {
None
} else {
let s = &text[self.last..];
self.last = text.len();
Some(s)
}
}
Some((s, e)) => {
let matched = &text[self.last..s];
self.last = e;
Some(matched)
}
}
}
}
pub struct SplitsN<'r, 't> {
splits: Splits<'r, 't>,
n: usize,
}
impl<'r, 't> Iterator for SplitsN<'r, 't> {
type Item = &'t [u8];
fn next(&mut self) -> Option<&'t [u8]> {
if self.n == 0 {
return None
}
self.n -= 1;
if self.n == 0 {
let text = self.splits.finder.text;
Some(&text[self.splits.last..])
} else {
self.splits.next()
}
}
}
pub struct CaptureNames<'r>(::std::slice::Iter<'r, Option<String>>);
impl<'r> Iterator for CaptureNames<'r> {
type Item = Option<&'r str>;
fn next(&mut self) -> Option<Option<&'r str>> {
self.0.next().as_ref()
.map(|slot| slot.as_ref().map(|name| name.as_ref()))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
pub struct Captures<'t> {
text: &'t [u8],
caps: Vec<Option<usize>>,
named_groups: Arc<HashMap<String, usize>>,
}
impl<'t> Captures<'t> {
pub fn pos(&self, i: usize) -> Option<(usize, usize)> {
let (s, e) = (i * 2, i * 2 + 1);
match (self.caps.get(s), self.caps.get(e)) {
(Some(&Some(s)), Some(&Some(e))) => Some((s, e)),
_ => None,
}
}
pub fn at(&self, i: usize) -> Option<&'t [u8]> {
match self.pos(i) {
None => None,
Some((s, e)) => Some(&self.text[s..e])
}
}
pub fn name(&self, name: &str) -> Option<&'t [u8]> {
self.named_groups.get(name).and_then(|&i| self.at(i))
}
pub fn iter<'a>(&'a self) -> SubCaptures<'a, 't> {
SubCaptures { idx: 0, caps: self, }
}
pub fn iter_pos(&'t self) -> SubCapturesPos<'t> {
SubCapturesPos { idx: 0, caps: &self.caps }
}
pub fn iter_named<'a>(&'a self) -> SubCapturesNamed<'a, 't> {
SubCapturesNamed {
caps: self,
names: self.named_groups.iter()
}
}
pub fn expand(&self, replacement: &[u8], dst: &mut Vec<u8>) {
expand(self, replacement, dst)
}
#[inline]
pub fn len(&self) -> usize {
self.caps.len() / 2
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<'t> Index<usize> for Captures<'t> {
type Output = [u8];
fn index(&self, i: usize) -> &[u8] {
self.at(i).unwrap_or_else(|| panic!("no group at index '{}'", i))
}
}
impl<'t, 'i> Index<&'i str> for Captures<'t> {
type Output = [u8];
fn index<'a>(&'a self, name: &'i str) -> &'a [u8] {
self.name(name).unwrap_or_else(|| panic!("no group named '{}'", name))
}
}
pub struct SubCaptures<'c, 't: 'c> {
idx: usize,
caps: &'c Captures<'t>,
}
impl<'c, 't> Iterator for SubCaptures<'c, 't> {
type Item = Option<&'t [u8]>;
fn next(&mut self) -> Option<Option<&'t [u8]>> {
if self.idx < self.caps.len() {
self.idx += 1;
Some(self.caps.at(self.idx - 1))
} else {
None
}
}
}
pub struct SubCapturesPos<'c> {
idx: usize,
caps: &'c [Option<usize>]
}
impl<'c> Iterator for SubCapturesPos<'c> {
type Item = Option<(usize, usize)>;
fn next(&mut self) -> Option<Option<(usize, usize)>> {
if self.idx >= self.caps.len() {
return None
}
let r = match (self.caps[self.idx], self.caps[self.idx + 1]) {
(Some(s), Some(e)) => Some((s, e)),
_ => None,
};
self.idx += 2;
Some(r)
}
}
pub struct SubCapturesNamed<'c, 't: 'c> {
caps: &'c Captures<'t>,
names: hash_map::Iter<'c, String, usize>,
}
impl<'c, 't> Iterator for SubCapturesNamed<'c, 't> {
type Item = (&'c str, Option<&'t [u8]>);
fn next(&mut self) -> Option<(&'c str, Option<&'t [u8]>)> {
self.names.next().map(|(name, &pos)| (&**name, self.caps.at(pos)))
}
}
pub trait Replacer {
fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>);
fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, [u8]>> {
None
}
}
impl<'a> Replacer for &'a [u8] {
fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>) {
caps.expand(*self, dst);
}
fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, [u8]>> {
match memchr(b'$', *self) {
Some(_) => None,
None => Some(Cow::Borrowed(*self)),
}
}
}
impl<F> Replacer for F where F: FnMut(&Captures) -> Vec<u8> {
fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>) {
dst.extend((*self)(caps))
}
}
pub struct NoExpand<'r>(pub &'r [u8]);
impl<'a> Replacer for NoExpand<'a> {
fn replace_append(&mut self, _: &Captures, dst: &mut Vec<u8>) {
dst.extend(self.0)
}
fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, [u8]>> {
Some(Cow::Borrowed(self.0))
}
}