diff --git a/dsc_lib/src/functions/mod.rs b/dsc_lib/src/functions/mod.rs index 400b8293..70b8e6f8 100644 --- a/dsc_lib/src/functions/mod.rs +++ b/dsc_lib/src/functions/mod.rs @@ -11,6 +11,7 @@ pub mod base64; pub mod concat; pub mod create_array; pub mod envvar; +pub mod mul; pub mod parameters; pub mod resource_id; @@ -58,6 +59,7 @@ impl FunctionDispatcher { functions.insert("concat".to_string(), Box::new(concat::Concat{})); functions.insert("createArray".to_string(), Box::new(create_array::CreateArray{})); functions.insert("envvar".to_string(), Box::new(envvar::Envvar{})); + functions.insert("mul".to_string(), Box::new(mul::Mul{})); functions.insert("parameters".to_string(), Box::new(parameters::Parameters{})); functions.insert("resourceId".to_string(), Box::new(resource_id::ResourceId{})); Self { diff --git a/dsc_lib/src/functions/mul.rs b/dsc_lib/src/functions/mul.rs new file mode 100644 index 00000000..888a463d --- /dev/null +++ b/dsc_lib/src/functions/mul.rs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use crate::DscError; +use crate::configure::context::Context; +use crate::functions::{AcceptedArgKind, Function}; +use serde_json::Value; +use tracing::debug; + +#[derive(Debug, Default)] +pub struct Mul {} + +impl Function for Mul { + fn min_args(&self) -> usize { + 2 + } + + fn max_args(&self) -> usize { + 2 + } + + fn accepted_arg_types(&self) -> Vec { + vec![AcceptedArgKind::Number] + } + + fn invoke(&self, args: &[Value], _context: &Context) -> Result { + debug!("mul function"); + if let (Some(arg1), Some(arg2)) = (args[0].as_i64(), args[1].as_i64()) { + Ok(Value::Number((arg1 * arg2).into())) + } else { + Err(DscError::Parser("Invalid argument(s)".to_string())) + } + } +} + +#[cfg(test)] +mod tests { + use crate::configure::context::Context; + use crate::parser::Statement; + + #[test] + fn numbers() { + let mut parser = Statement::new().unwrap(); + let result = parser.parse_and_execute("[mul(2, 3)]", &Context::new()).unwrap(); + assert_eq!(result, 6); + } + + #[test] + fn nested() { + let mut parser = Statement::new().unwrap(); + let result = parser.parse_and_execute("[mul(2, mul(3, 4))]", &Context::new()).unwrap(); + assert_eq!(result, 24); + } + + #[test] + fn invalid_one_parameter() { + let mut parser = Statement::new().unwrap(); + let result = parser.parse_and_execute("[mul(5)]", &Context::new()); + assert!(result.is_err()); + } + + #[test] + fn overflow_result() { + let mut parser = Statement::new().unwrap(); + // max value for i64 is 2^63 -1 (or 9,223,372,036,854,775,807) + let result = parser.parse_and_execute("[mul(9223372036854775807, 2)]", &Context::new()); + assert!(result.is_err()); + } + + #[test] + fn overflow_input() { + let mut parser = Statement::new().unwrap(); + let result = parser.parse_and_execute("[mul(9223372036854775808, 2)]", &Context::new()); + assert!(result.is_err()); + } +}