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
104
105
106
107
108
109
110
111
112
use std::ops::{Deref, DerefMut};

use crate::Error;
use crate::{ctx::Ctx, RawVal};

/// Return value for [`Policy`](crate::parser::Policy).
#[derive(Debug, Clone, Default)]
pub struct ReturnVal {
    failure: Error,

    ctx: Ctx,
}

impl ReturnVal {
    pub fn new(ctx: Ctx) -> Self {
        Self {
            ctx,
            failure: Error::default(),
        }
    }

    pub fn with_failure(mut self, failure: Error) -> Self {
        self.failure = failure;
        self
    }

    pub fn set_failure(&mut self, failure: Error) -> &mut Self {
        self.failure = failure;
        self
    }

    pub fn failure(&self) -> &Error {
        &self.failure
    }

    pub fn ctx(&self) -> &Ctx {
        &self.ctx
    }

    pub fn args(&self) -> &[RawVal] {
        self.ctx.args().as_slice()
    }

    /// The [`status`](ReturnVal::status) is true if parsing successes
    /// otherwise it will be false if any [`failure`](Error::is_failure) raised.
    pub fn status(&self) -> bool {
        self.failure.is_null()
    }

    /// Unwrap the [`Ctx`] from [`ReturnVal`].
    pub fn unwrap(self) -> Ctx {
        Result::unwrap(if self.failure.is_null() {
            Ok(self.ctx)
        } else {
            Err(self.failure)
        })
    }

    pub fn ok(self) -> Result<Ctx, Error> {
        if self.failure.is_null() {
            Ok(self.ctx)
        } else {
            Err(self.failure)
        }
    }

    pub fn take_ctx(&mut self) -> Ctx {
        std::mem::take(&mut self.ctx)
    }

    pub fn take_failure(&mut self) -> Error {
        std::mem::take(&mut self.failure)
    }

    pub fn clone_args(&self) -> Vec<RawVal> {
        let args = self.ctx.args().as_ref();

        args.clone().into_inner()
    }
}

impl Deref for ReturnVal {
    type Target = Ctx;

    fn deref(&self) -> &Self::Target {
        &self.ctx
    }
}

impl DerefMut for ReturnVal {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.ctx
    }
}

impl From<ReturnVal> for bool {
    fn from(value: ReturnVal) -> Self {
        value.status()
    }
}

impl<'a> From<&'a ReturnVal> for bool {
    fn from(value: &'a ReturnVal) -> Self {
        value.status()
    }
}

impl<'a> From<&'a mut ReturnVal> for bool {
    fn from(value: &'a mut ReturnVal) -> Self {
        value.status()
    }
}