arch_pkg_text/parse/
partial.rs

1/// Result of a parsing process that may or may not be complete.
2#[derive(Debug, Clone, Copy)]
3pub struct PartialParseResult<Parsed, Error> {
4    /// The result of the parsing process, either partial or complete.
5    parsed: Parsed,
6    /// Possible error encountered during parsing.
7    error: Option<Error>,
8}
9
10impl<Parsed, Error> PartialParseResult<Parsed, Error> {
11    /// Create a complete parse result.
12    pub fn new_complete(parsed: Parsed) -> Self {
13        PartialParseResult {
14            parsed,
15            error: None,
16        }
17    }
18
19    /// Create partial parse result.
20    pub fn new_partial(parsed: Parsed, error: Error) -> Self {
21        PartialParseResult {
22            parsed,
23            error: Some(error),
24        }
25    }
26
27    /// Return an `Ok` if there was no error.
28    ///
29    /// Otherwise, return an `Err`.
30    pub fn try_into_complete(self) -> Result<Parsed, Error> {
31        match self.error {
32            Some(error) => Err(error),
33            None => Ok(self.parsed),
34        }
35    }
36
37    /// Return both the parsed object and the error regardless of whether there was an error.
38    pub fn into_partial(self) -> (Parsed, Option<Error>) {
39        (self.parsed, self.error)
40    }
41
42    /// Return a reference to the partially parsed object.
43    pub fn parsed(&self) -> &'_ Parsed {
44        &self.parsed
45    }
46
47    /// Return a reference to the stored error if there was one.
48    pub fn error(&self) -> Option<&'_ Error> {
49        self.error.as_ref()
50    }
51
52    /// Whether there was an error.
53    pub fn has_error(&self) -> bool {
54        self.error.is_some()
55    }
56}
57
58impl<Parsed, Error> From<PartialParseResult<Parsed, Error>> for Result<Parsed, Error> {
59    fn from(value: PartialParseResult<Parsed, Error>) -> Self {
60        value.try_into_complete()
61    }
62}
63
64impl<Parsed, Error> From<PartialParseResult<Parsed, Error>> for (Parsed, Option<Error>) {
65    fn from(value: PartialParseResult<Parsed, Error>) -> Self {
66        value.into_partial()
67    }
68}
69
70impl<Parsed, Error> From<(Parsed, Option<Error>)> for PartialParseResult<Parsed, Error> {
71    fn from((parsed, error): (Parsed, Option<Error>)) -> Self {
72        PartialParseResult { parsed, error }
73    }
74}