snarkvm_console_types_boolean/
parse.rs

1// Copyright 2024 Aleo Network Foundation
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18impl<E: Environment> Parser for Boolean<E> {
19    /// Parses a string into a boolean.
20    #[inline]
21    fn parse(string: &str) -> ParserResult<Self> {
22        // Parse the boolean from the string.
23        let (string, value) = alt((map(tag("true"), |_| true), map(tag("false"), |_| false)))(string)?;
24
25        Ok((string, Boolean::new(value)))
26    }
27}
28
29impl<E: Environment> FromStr for Boolean<E> {
30    type Err = Error;
31
32    /// Parses a string into a boolean.
33    #[inline]
34    fn from_str(string: &str) -> Result<Self> {
35        match Self::parse(string) {
36            Ok((remainder, object)) => {
37                // Ensure the remainder is empty.
38                ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
39                // Return the object.
40                Ok(object)
41            }
42            Err(error) => bail!("Failed to parse string. {error}"),
43        }
44    }
45}
46
47impl<E: Environment> Debug for Boolean<E> {
48    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
49        Display::fmt(self, f)
50    }
51}
52
53impl<E: Environment> Display for Boolean<E> {
54    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
55        write!(f, "{}", self.boolean)
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62    use snarkvm_console_network_environment::Console;
63
64    type CurrentEnvironment = Console;
65
66    #[test]
67    fn test_parse() -> Result<()> {
68        // Ensure type and empty value fails.
69        assert!(Boolean::<CurrentEnvironment>::parse(Boolean::<CurrentEnvironment>::type_name()).is_err());
70        assert!(Boolean::<CurrentEnvironment>::parse("").is_err());
71
72        for boolean in &[true, false] {
73            let expected = format!("{boolean}");
74            let (remainder, candidate) = Boolean::<CurrentEnvironment>::parse(&expected).unwrap();
75            assert_eq!(format!("{expected}"), candidate.to_string());
76            assert_eq!("", remainder);
77        }
78        Ok(())
79    }
80
81    #[test]
82    fn test_display() {
83        /// Attempts to construct a boolean from the given element,
84        /// format it in display mode, and recover a boolean from it.
85        fn check_display<E: Environment>(element: bool) {
86            let candidate = Boolean::<E>::new(element);
87            assert_eq!(format!("{element}"), format!("{candidate}"));
88
89            let candidate_recovered = Boolean::<E>::from_str(&format!("{candidate}")).unwrap();
90            assert_eq!(candidate, candidate_recovered);
91        }
92
93        check_display::<CurrentEnvironment>(false);
94        check_display::<CurrentEnvironment>(true);
95    }
96
97    #[test]
98    fn test_display_false() {
99        // Constant
100        let candidate = Boolean::<CurrentEnvironment>::new(false);
101        assert_eq!("false", &format!("{candidate}"));
102    }
103
104    #[test]
105    fn test_display_true() {
106        // Constant
107        let candidate = Boolean::<CurrentEnvironment>::new(true);
108        assert_eq!("true", &format!("{candidate}"));
109    }
110}