Allow negative variables.
This commit is contained in:
parent
0c394d0f79
commit
c10ee5c0f3
|
@ -1,6 +1,6 @@
|
|||
use crate::error::BotError;
|
||||
use combine::parser::char::{digit, letter, spaces};
|
||||
use combine::{many1, Parser};
|
||||
use combine::parser::char::{char, digit, letter, spaces};
|
||||
use combine::{many1, optional, Parser};
|
||||
use thiserror::Error;
|
||||
|
||||
enum ParsedValue {
|
||||
|
@ -20,11 +20,21 @@ pub enum VariableParsingError {
|
|||
pub fn parse_set_variable(input: &str) -> Result<(String, i32), BotError> {
|
||||
let name = many1(letter()).map(|value: String| value);
|
||||
|
||||
let value = many1(digit()).map(|value: String| match value.parse::<i32>() {
|
||||
Ok(num) => ParsedValue::Valid(num),
|
||||
_ => ParsedValue::Invalid,
|
||||
let maybe_minus = optional(char('-')).map(|value: Option<char>| match value {
|
||||
Some(minus_sign) => String::from(minus_sign),
|
||||
_ => "".to_owned(),
|
||||
});
|
||||
|
||||
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)?;
|
||||
|
||||
|
@ -41,3 +51,22 @@ pub fn parse_set_variable(input: &str) -> Result<(String, i32), BotError> {
|
|||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue