tenebrous-dicebot/src/variables.rs

73 lines
1.9 KiB
Rust
Raw Normal View History

use crate::error::BotError;
2020-10-22 20:47:20 +00:00
use combine::parser::char::{char, digit, letter, spaces};
use combine::{many1, optional, Parser};
use thiserror::Error;
enum ParsedValue {
Valid(i32),
Invalid,
}
#[derive(Error, Debug)]
pub enum VariableParsingError {
#[error("invalid variable value, must be a number")]
InvalidValue,
#[error("unconsumed input")]
UnconsumedInput,
}
pub fn parse_set_variable(input: &str) -> Result<(String, i32), BotError> {
let name = many1(letter()).map(|value: String| value);
2020-10-22 20:47:20 +00:00
let maybe_minus = optional(char('-')).map(|value: Option<char>| match value {
Some(minus_sign) => String::from(minus_sign),
_ => "".to_owned(),
});
2020-10-22 20:47:20 +00:00
let value = maybe_minus
.and(many1(digit()))
.map(|value: (String, String)| {
let number = format!("{}{}", value.0, value.1);
match number.parse::<i32>() {
Ok(num) => ParsedValue::Valid(num),
_ => ParsedValue::Invalid,
}
});
let mut parser = name.skip(spaces().silent()).and(value);
let (result, rest) = parser.parse(input)?;
if rest.len() == 0 {
match result {
(variable_name, ParsedValue::Valid(value)) => Ok((variable_name, value)),
_ => Err(BotError::VariableParsingError(
VariableParsingError::InvalidValue,
)),
}
} else {
Err(BotError::VariableParsingError(
VariableParsingError::UnconsumedInput,
))
}
}
2020-10-22 20:47:20 +00:00
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_postive_number() {
let result = parse_set_variable("myvar 5");
assert!(result.is_ok());
assert_eq!(("myvar".to_string(), 5), result.unwrap());
}
#[test]
fn parse_negative_number() {
let result = parse_set_variable("myvar -5");
assert!(result.is_ok());
assert_eq!(("myvar".to_string(), -5), result.unwrap());
}
}