1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use std::{cell::Cell, marker::PhantomData};

use super::Neu;

use crate::{trace_log, MayDebug};

#[derive(Debug, Default)]
pub struct MayUnit<U, I, T>
where
    U: Neu<T>,
    I: Neu<T>,
{
    r#if: I,
    unit: U,
    count: Cell<usize>,
    value: Cell<bool>,
    marker: PhantomData<T>,
}

impl<U, I, T> Clone for MayUnit<U, I, T>
where
    U: Neu<T> + Clone,
    I: Neu<T> + Clone,
{
    fn clone(&self) -> Self {
        Self {
            r#if: self.r#if.clone(),
            unit: self.unit.clone(),
            value: self.value.clone(),
            count: self.count.clone(),
            marker: self.marker,
        }
    }
}

impl<U, I, T> MayUnit<U, I, T>
where
    U: Neu<T>,
    I: Neu<T>,
{
    pub fn new(r#if: I, count: usize, unit: U) -> Self {
        Self {
            r#if,
            unit,
            count: Cell::new(count),
            value: Cell::new(true),
            marker: PhantomData,
        }
    }

    pub fn unit(&self) -> &U {
        &self.unit
    }

    pub fn r#if(&self) -> &I {
        &self.r#if
    }

    pub fn unit_mut(&mut self) -> &mut U {
        &mut self.unit
    }

    pub fn r#if_mut(&mut self) -> &mut I {
        &mut self.r#if
    }

    pub fn set_unit(&mut self, unit: U) -> &mut Self {
        self.unit = unit;
        self
    }

    pub fn and(&mut self, r#if: I) -> &mut Self {
        self.r#if = r#if;
        self
    }
}

impl<U, I, T> Neu<T> for MayUnit<U, I, T>
where
    U: Neu<T>,
    I: Neu<T>,
    T: MayDebug,
{
    #[inline(always)]
    fn is_match(&self, other: &T) -> bool {
        let count = self.count.get();
        let value = self.value.get();

        if count == 0 {
            let ret = self.unit.is_match(other);

            trace_log!("{:?} -> u`may({})` -> {:?}", other, count, ret);
            value && ret
        } else {
            let ret = self.r#if.is_match(other);

            trace_log!("{:?} -> u`may if({})`:  -> {:?}", other, count, ret);
            self.value.set(value && ret);
            self.count.set(count - 1);
            ret
        }
    }
}