Skip to main content

sage_runtime/stdlib/
parsing.rs

1//! Parsing helper functions for the Sage standard library.
2
3/// Parse a boolean from a string.
4/// Accepts "true", "false", "1", "0" (case-insensitive for true/false).
5pub fn parse_bool(s: &str) -> Result<bool, String> {
6    match s.trim().to_lowercase().as_str() {
7        "true" | "1" => Ok(true),
8        "false" | "0" => Ok(false),
9        _ => Err(format!("invalid boolean: '{s}'")),
10    }
11}
12
13#[cfg(test)]
14mod tests {
15    use super::*;
16
17    #[test]
18    fn test_parse_bool() {
19        assert_eq!(parse_bool("true"), Ok(true));
20        assert_eq!(parse_bool("false"), Ok(false));
21        assert_eq!(parse_bool("TRUE"), Ok(true));
22        assert_eq!(parse_bool("FALSE"), Ok(false));
23        assert_eq!(parse_bool("True"), Ok(true));
24        assert_eq!(parse_bool("1"), Ok(true));
25        assert_eq!(parse_bool("0"), Ok(false));
26        assert_eq!(parse_bool("  true  "), Ok(true));
27        assert!(parse_bool("yes").is_err());
28        assert!(parse_bool("no").is_err());
29        assert!(parse_bool("").is_err());
30    }
31}