oneline_template/functions/string/
substr.rs

1use crate::function_executor::*;
2
3/// Function: `string:substr`
4/// 
5/// Input: `String`
6///
7/// * first argument: uint offset
8/// * second argument: uint length
9///
10/// Returns `Option<String>`
11pub struct SubStr;
12
13impl FunctionExecutor for SubStr {
14    fn schema(&self) -> FunctionSchema {
15        FunctionSchema::new("string:substr")
16            .with_argument(FunctionArgument::uint())
17            .with_argument(FunctionArgument::uint())
18    }
19
20    fn call(&self, value: Value, arguments: &[Value]) -> Result<Value, FunctionError> {
21        let value = value.as_string()?;
22        let begin = arguments[0].as_uint()?;
23        let begin = *begin as usize;
24        let length = arguments[1].as_uint()?;
25        let length = *length as usize;
26        let end = begin + length;
27        let value = value
28            .get(begin..end)
29            .map(|value| {
30                return Value::String(value.to_string());
31            })
32            .map(Box::new);
33        let value = Value::Option(value);
34        return Ok(value);
35    }
36}