use core::fmt::Debug;
use core::marker::PhantomData;
use crate::ctor::Ctor;
use crate::ctor::Handler;
use crate::ctx::Match;
use crate::err::Error;
use crate::regex::Regex;
use crate::span::Span;
pub struct Repeat2<C, P, const M: usize, const N: usize> {
pat: P,
marker: PhantomData<C>,
}
impl<C, P, const M: usize, const N: usize> core::ops::Not for Repeat2<C, P, M, N> {
type Output = crate::regex::Assert<Self>;
fn not(self) -> Self::Output {
crate::regex::not(self)
}
}
impl<C, P, const M: usize, const N: usize> Debug for Repeat2<C, P, M, N>
where
P: Debug,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Repeat2").field("pat", &self.pat).finish()
}
}
impl<C, P, const M: usize, const N: usize> Default for Repeat2<C, P, M, N>
where
P: Default,
{
fn default() -> Self {
Self {
pat: Default::default(),
marker: Default::default(),
}
}
}
impl<C, P, const M: usize, const N: usize> Clone for Repeat2<C, P, M, N>
where
P: Clone,
{
fn clone(&self) -> Self {
Self {
pat: self.pat.clone(),
marker: self.marker,
}
}
}
impl<C, P, const M: usize, const N: usize> Copy for Repeat2<C, P, M, N> where P: Copy {}
impl<C, P, const M: usize, const N: usize> Repeat2<C, P, M, N> {
pub const fn new(pat: P) -> Self {
Self {
pat,
marker: PhantomData,
}
}
pub const fn pat(&self) -> &P {
&self.pat
}
pub const fn pat_mut(&mut self) -> &mut P {
&mut self.pat
}
pub fn set_pat(&mut self, pat: P) -> &mut Self {
self.pat = pat;
self
}
pub fn with_pat(mut self, pat: P) -> Self {
self.pat = pat;
self
}
}
impl<'a, C, P, const M: usize, const N: usize, O, H> Ctor<C, [Option<O>; N], H>
for Repeat2<C, P, M, N>
where
P: Ctor<C, O, H>,
C: Match<'a>,
H: Handler<C>,
{
#[inline(always)]
fn construct(&self, ctx: &mut C, handler: &mut H) -> Result<[Option<O>; N], Error> {
let offset = ctx.offset();
let mut cnt = 0;
let mut vals = [const { None }; N];
let range = M..=N;
crate::debug_ctor_beg!("Repeat2", &range, offset);
while cnt <= N {
if let Ok(val) = self.pat.construct(ctx, handler) {
vals[cnt] = Some(val);
cnt += 1;
} else {
break;
}
}
let ret = if range.contains(&cnt) {
Ok(vals)
} else {
Err(Error::Repeat2)
}
.inspect_err(|_| {
ctx.set_offset(offset);
});
crate::debug_ctor_reval!("Repeat2", offset, ctx.offset(), ret.is_ok());
ret
}
}
impl<'a, C, P, const M: usize, const N: usize> Regex<C> for Repeat2<C, P, M, N>
where
P: Regex<C>,
C: Match<'a>,
{
#[inline(always)]
fn try_parse(&self, ctx: &mut C) -> Result<Span, Error> {
let offset = ctx.offset();
let mut cnt = 0;
let mut total = Span::new(offset, 0);
let range = M..=N;
crate::debug_regex_beg!("Repeat2", &range, offset);
while cnt <= N {
if let Ok(p_span) = ctx.try_mat(&self.pat) {
total.add_assign(p_span);
cnt += 1;
} else {
break;
}
}
let ret = if range.contains(&cnt) {
Ok(total)
} else {
Err(Error::Repeat2)
}
.inspect_err(|_| {
ctx.set_offset(offset);
});
crate::debug_regex_reval!("Repeat2", ret)
}
}