|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +use core::option::Option::Some; |
| 5 | + |
| 6 | +use crate::DscError; |
| 7 | +use crate::configure::context::Context; |
| 8 | +use crate::functions::{AcceptedArgKind, Function, FunctionCategory}; |
| 9 | +use rust_i18n::t; |
| 10 | +use serde_json::Value; |
| 11 | +use tracing::debug; |
| 12 | + |
| 13 | +#[derive(Debug, Default)] |
| 14 | +pub struct Length {} |
| 15 | + |
| 16 | +impl Function for Length { |
| 17 | + fn description(&self) -> String { |
| 18 | + t!("functions.length.description").to_string() |
| 19 | + } |
| 20 | + |
| 21 | + fn category(&self) -> FunctionCategory { |
| 22 | + FunctionCategory::Array |
| 23 | + } |
| 24 | + |
| 25 | + fn min_args(&self) -> usize { |
| 26 | + 1 |
| 27 | + } |
| 28 | + |
| 29 | + fn max_args(&self) -> usize { |
| 30 | + 1 |
| 31 | + } |
| 32 | + |
| 33 | + fn accepted_arg_types(&self) -> Vec<AcceptedArgKind> { |
| 34 | + vec![AcceptedArgKind::Array, AcceptedArgKind::Object, AcceptedArgKind::String] |
| 35 | + } |
| 36 | + |
| 37 | + fn invoke(&self, args: &[Value], _context: &Context) -> Result<Value, DscError> { |
| 38 | + debug!("{}", t!("functions.length.invoked")); |
| 39 | + if let Some(array) = args[0].as_array() { |
| 40 | + return Ok(Value::Number(array.len().into())); |
| 41 | + } |
| 42 | + |
| 43 | + if let Some(object) = args[0].as_object() { |
| 44 | + return Ok(Value::Number(object.keys().len().into())); |
| 45 | + } |
| 46 | + |
| 47 | + if let Some(string) = args[0].as_str() { |
| 48 | + return Ok(Value::Number(string.len().into())); |
| 49 | + } |
| 50 | + |
| 51 | + Err(DscError::Parser(t!("functions.length.invalidArgType").to_string())) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | + |
| 56 | +#[cfg(test)] |
| 57 | +mod tests { |
| 58 | + use crate::configure::context::Context; |
| 59 | + use crate::parser::Statement; |
| 60 | + use serde_json::Value; |
| 61 | + |
| 62 | + #[test] |
| 63 | + fn empty_string() { |
| 64 | + let mut parser = Statement::new().unwrap(); |
| 65 | + let result = parser.parse_and_execute("[length('')]", &Context::new()).unwrap(); |
| 66 | + assert_eq!(result, Value::Number(0.into())); |
| 67 | + } |
| 68 | + |
| 69 | + #[test] |
| 70 | + fn not_empty_string() { |
| 71 | + let mut parser = Statement::new().unwrap(); |
| 72 | + let result = parser.parse_and_execute("[length('foo')]", &Context::new()).unwrap(); |
| 73 | + assert_eq!(result, Value::Number(3.into())); |
| 74 | + } |
| 75 | +} |
0 commit comments