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, ExecNoSync};
use expand::expand;
use error::Error;
use re_builder::bytes::RegexBuilder;
use re_trait::{self, RegularExpression, Slot};
#[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> {
RegexBuilder::new(re).size_limit(size).compile()
}
pub fn is_match(&self, text: &[u8]) -> bool {
self.is_match_at(text, 0)
}
#[doc(hidden)]
pub fn is_match_at(&self, text: &[u8], start: usize) -> bool {
self.shortest_match_at(text, start).is_some()
}
pub fn find(&self, text: &[u8]) -> Option<(usize, usize)> {
self.find_at(text, 0)
}
#[doc(hidden)]
pub fn find_at(
&self,
text: &[u8],
start: usize,
) -> Option<(usize, usize)> {
self.0.searcher().find_at(text, start)
}
pub fn find_iter<'r, 't>(&'r self, text: &'t [u8]) -> FindMatches<'r, 't> {
FindMatches(self.0.searcher().find_iter(text))
}
pub fn captures<'t>(&self, text: &'t [u8]) -> Option<Captures<'t>> {
let mut slots = vec![None; 2 * self.captures_len()];
self.read_captures_at(&mut slots, text, 0).map(|_| Captures {
text: text,
slots: slots,
named_groups: self.0.capture_name_idx().clone(),
})
}
#[doc(hidden)]
pub fn read_captures_at(
&self,
slots: &mut [Slot],
text: &[u8],
start: usize,
) -> Option<(usize, usize)> {
self.0.searcher().read_captures_at(slots, text, start)
}
pub fn captures_iter<'r, 't>(
&'r self,
text: &'t [u8],
) -> FindCaptures<'r, 't> {
FindCaptures(self.0.searcher().captures_iter(text))
}
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
}
extend_from_slice(&mut new, &text[last_match..s]);
extend_from_slice(&mut new, &*rep);
last_match = e;
}
extend_from_slice(&mut new, &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();
extend_from_slice(&mut new, &text[last_match..s]);
rep.replace_append(&cap, &mut new);
last_match = e;
}
extend_from_slice(&mut new, &text[last_match..]);
new
}
pub fn shortest_match(&self, text: &[u8]) -> Option<usize> {
self.shortest_match_at(text, 0)
}
#[doc(hidden)]
pub fn shortest_match_at(
&self,
text: &[u8],
start: usize,
) -> Option<usize> {
self.0.searcher().shortest_match_at(text, start)
}
pub fn as_str(&self) -> &str {
&self.0.regex_strings()[0]
}
pub fn capture_names(&self) -> CaptureNames {
CaptureNames(self.0.capture_names().iter())
}
pub fn captures_len(&self) -> usize {
self.0.capture_names().len()
}
}
pub struct FindMatches<'r, 't>(re_trait::FindMatches<'t, ExecNoSync<'r>>);
impl<'r, 't> Iterator for FindMatches<'r, 't> {
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
self.0.next()
}
}
pub struct FindCaptures<'r, 't>(re_trait::FindCaptures<'t, ExecNoSync<'r>>);
impl<'r, 't> Iterator for FindCaptures<'r, 't> {
type Item = Captures<'t>;
fn next(&mut self) -> Option<Captures<'t>> {
self.0.next().map(|slots| Captures {
text: self.0.text(),
slots: slots,
named_groups: self.0.regex().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.0.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.0.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],
slots: 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.slots.get(s), self.slots.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, slots: &self.slots }
}
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.slots.len() / 2
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<'t> fmt::Debug for Captures<'t> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Captures").field(&CapturesDebug(self)).finish()
}
}
struct CapturesDebug<'c, 't: 'c>(&'c Captures<'t>);
impl<'c, 't> fmt::Debug for CapturesDebug<'c, 't> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fn escape_bytes(bytes: &[u8]) -> String {
let mut s = String::new();
for &b in bytes {
s.push_str(&escape_byte(b));
}
s
}
fn escape_byte(byte: u8) -> String {
use std::ascii::escape_default;
let escaped: Vec<u8> = escape_default(byte).collect();
String::from_utf8_lossy(&escaped).into_owned()
}
let slot_to_name: HashMap<&usize, &String> =
self.0.named_groups.iter().map(|(a, b)| (b, a)).collect();
let mut map = f.debug_map();
for (slot, m) in self.0.iter_pos().enumerate() {
let m = m.map(|(s, e)| escape_bytes(&self.0.text[s..e]));
if let Some(ref name) = slot_to_name.get(&slot) {
map.entry(&name, &m);
} else {
map.entry(&slot, &m);
}
}
map.finish()
}
}
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,
slots: &'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.slots.len() {
return None
}
let r = match (self.slots[self.idx], self.slots[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>) {
extend_from_slice(dst, &(*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>) {
extend_from_slice(dst, self.0);
}
fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, [u8]>> {
Some(Cow::Borrowed(self.0))
}
}
fn extend_from_slice(dst: &mut Vec<u8>, src: &[u8]) {
dst.reserve(src.len());
let dst_len = dst.len();
unsafe { dst.set_len(dst_len + src.len()); }
let mut dst = &mut dst[dst_len..dst_len + src.len()];
for i in 0..src.len() {
dst[i] = src[i];
}
}