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
use crate::{ParseResult, ParseResult::Stop, Parsed};

use super::*;

/// Helper for choice pattern
#[derive(Debug, Clone)]
pub struct ChoiceHelper<'a, T> {
    state: ParseState<'a>,
    result: Option<Parsed<'a, T>>,
}

impl<'i> ParseState<'i> {
    /// Begin a choice progress
    #[inline]
    pub fn begin_choice<T>(self) -> ChoiceHelper<'i, T> {
        ChoiceHelper { state: self, result: None }
    }
}

impl<'a, T> ChoiceHelper<'a, T> {
    /// Create a new choice helper
    #[inline]
    pub fn new(state: ParseState<'a>) -> Self {
        Self { state, result: None }
    }
    /// Try to parse a value
    #[inline]
    pub fn or_else<F>(mut self, mut parse_fn: F) -> Self
    where
        F: FnMut(ParseState<'a>) -> ParseResult<'a, T>,
    {
        if self.result.is_none() {
            match parse_fn(self.state.clone()) {
                Pending(s, v) => self.result = Some((s, v)),
                Stop(err) => self.state.set_error(err),
            }
        }
        self
    }
    /// End choice
    #[inline]
    pub fn end_choice(self) -> ParseResult<'a, T> {
        match self.result {
            Some(ok) => Pending(ok.0, ok.1),
            None => Stop(self.state.get_error()),
        }
    }
}