forked from PowerShell/DSC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd.rs
76 lines (64 loc) · 2.08 KB
/
add.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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 Add {}
impl Function for Add {
fn min_args(&self) -> usize {
2
}
fn max_args(&self) -> usize {
2
}
fn accepted_arg_types(&self) -> Vec<AcceptedArgKind> {
vec![AcceptedArgKind::Number]
}
fn invoke(&self, args: &[Value], _context: &Context) -> Result<Value, DscError> {
debug!("add 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("[add(2, 3)]", &Context::new()).unwrap();
assert_eq!(result, 5);
}
#[test]
fn nested() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[add(2, add(3, 4))]", &Context::new()).unwrap();
assert_eq!(result, 9);
}
#[test]
fn invalid_one_parameter() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[add(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("[add(9223372036854775807, 2)]", &Context::new());
assert!(result.is_err());
}
#[test]
fn overflow_input() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[add(9223372036854775808, 2)]", &Context::new());
assert!(result.is_err());
}
}