esre/re/
begin_of.rs

1use std::rc::Rc;
2
3use serde_json::{Map, Value};
4
5use crate::entities::re::{
6    ApplyError, ApplyResponse, ApplyResult, ParseJsonError, PossibleBegin, ReType, State,
7};
8use crate::js_tools::{FieldGetter, ValueFieldGetter};
9use crate::proto::builders::IJsonParser;
10use crate::proto::re::IRe;
11use crate::IntoRe;
12
13const PRIMARY_KEY: &str = "begin_of";
14
15pub struct Re {
16    re: Rc<dyn IRe>,
17}
18
19impl Re {
20    pub fn new<T: IntoRe>(re: T) -> Re {
21        Re { re: re.into_ire() }
22    }
23
24    pub fn parse_dict(
25        parser: &dyn IJsonParser,
26        dict: &Map<String, Value>,
27    ) -> Result<Option<Rc<dyn IRe>>, ParseJsonError> {
28        ValueFieldGetter::with_primary_field(dict, PRIMARY_KEY, &|val| {
29            let re = parser.parse_json(val)?;
30            Ok(Re { re }.into_ire())
31        })
32    }
33}
34
35impl IRe for Re {
36    fn get_type(&self) -> ReType {
37        ReType::BeginOf
38    }
39
40    fn apply(&self, state: &mut State, begin: usize) -> ApplyResult {
41        if self.re.apply(state, begin).is_ok() {
42            Ok(ApplyResponse::new_empty(begin))
43        } else {
44            Err(ApplyError::NotMatched)
45        }
46    }
47
48    fn show(&self) -> String {
49        format!("begin_of({})", self.re.show())
50    }
51
52    fn to_json(&self) -> Value {
53        Value::Object(
54            vec![(PRIMARY_KEY.to_string(), self.re.to_json())]
55                .into_iter()
56                .collect(),
57        )
58    }
59
60    fn possible_begin(&self) -> PossibleBegin {
61        self.re.possible_begin()
62    }
63}