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
use std::convert::From;
use std::default::Default;

use super::{Parsable, Argument};

/// An argument which represents an option which may occur 0 - x times.
/// # Example
/// ```
/// use yaccas::arguments::{Argument, Flag};
/// use yaccas::parser::{Parser, Result};
/// use yaccas::scanner::Unix;
///
/// // This option will be modified by the flag
/// let mut will_be_true = false;
///
/// {
///     let mut parser = Parser::default();
///     let flag = Flag::default();
///
///     parser.register(&["option", "o"], Argument::with_callback(flag, | flag | {
///         // This will only be executed if the parsing was successful.
///         will_be_true = flag.is_activated();
///     }));
///
///     assert_eq!(parser.parse(Unix::new(&["-option"])), Result::Success(Vec::new()));
/// }
///
/// assert_eq!(will_be_true, true);
/// ```
pub struct Flag(u32);

impl Flag {
    /// Activates the flag and increments the counter of matches by 1.
    pub fn activate(&mut self) {
        self.0 += 1;
    }

    /// Checks if the flag is set.
    pub fn is_activated(&self) -> bool {
        self.0 > 0
    }

    /// Returns how many times the flag was set.
    /// # Example
    /// ```
    /// use yaccas::arguments::{Argument, Flag};
    /// use yaccas::parser::{Parser, Result};
    /// use yaccas::scanner::Unix;
    ///
    /// let mut parser = Parser::default();
    /// let flag = Flag::default();
    ///
    /// parser.register(&["option", "o"], Argument::with_callback(flag, | flag | {
    ///     assert_eq!(flag.get_matches(), 2u32);
    /// }));
    ///
    /// assert_eq!(parser.parse(Unix::new(&["-option", "-o"])), Result::Success(Vec::new()));
    /// ```
    pub fn get_matches(&self) -> u32 {
        self.0
    }
}

impl Default for Flag {
    fn default() -> Flag {
        Flag(0)
    }
}

impl Parsable for Flag {}

impl From<Flag> for Argument<'static> {
    fn from(value: Flag) -> Argument<'static> {
        Argument::Flag(value, None)
    }
}