From c10ee5c0f3cf3159114177b2063f391753d22b6c Mon Sep 17 00:00:00 2001 From: projectmoon Date: Thu, 22 Oct 2020 20:47:20 +0000 Subject: [PATCH] Allow negative variables. --- src/variables.rs | 39 ++++++++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/src/variables.rs b/src/variables.rs index f7b4319..362e362 100644 --- a/src/variables.rs +++ b/src/variables.rs @@ -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::() { - Ok(num) => ParsedValue::Valid(num), - _ => ParsedValue::Invalid, + let maybe_minus = optional(char('-')).map(|value: Option| 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::() { + 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()); + } +}