rubble_templates/std_fun/strings.rs
1//! Provides standard string manipulation and utility functions.
2//!
3//! See [`std_fun`](rubble-templates::std_fun) or [`string_functions`] for more info.
4//!
5use std::collections::HashMap;
6use rubble_templates_core::evaluator::Function;
7use rubble_templates_core::functions::SimpleFunction;
8
9pub const EMPTY_STRING: &str = "";
10
11/// Provides a set of string related functions.
12///
13/// Available functions:
14/// * [`concat`](concat_function) - Concatenates parameters.
15/// * [`trim`](trim_function) - Trims parameters.
16/// * [`$}`](right_brackets_function) - Inserts "}}".
17/// * [`$quote`](right_brackets_function) - Inserts double qoutes (").
18pub fn string_functions() -> HashMap<String, Box<dyn Function>> {
19 let mut functions: HashMap<String, Box<dyn Function>> = HashMap::new();
20 functions.insert("concat".to_string(), SimpleFunction::new(concat_function));
21 functions.insert("trim".to_string(), SimpleFunction::new(trim_function));
22 functions.insert("$}".to_string(), SimpleFunction::new(right_brackets_function));
23 functions.insert("$quote".to_string(), SimpleFunction::new(quotes_function));
24 functions
25}
26
27/// Concatenates the parameters.
28///
29/// Eg.
30/// ```text
31/// concat 1 "hello" " " 3.14 "world!"
32/// ```
33/// Expected output:
34/// ```text
35/// 1hello 3.14world!
36/// ```
37pub fn concat_function(parameters: &[String]) -> String {
38 let mut result = EMPTY_STRING.to_string();
39 parameters.iter().for_each(|param| {
40 result.push_str(param);
41 });
42 result
43}
44
45/// Trims the parameters.
46/// If there is more than one parameter, then concatenates them.
47///
48/// Eg.
49/// ```text
50/// trim " hello"
51/// trim " hello " " world" "text "
52/// ```
53/// Expected output:
54/// ```text
55/// hello
56/// helloworldtext
57/// ```
58pub fn trim_function(parameters: &[String]) -> String {
59 let mut result = EMPTY_STRING.to_string();
60 parameters.iter().for_each(|param| {
61 result.push_str(param.trim());
62 });
63 result
64}
65
66/// Inserts "}}". Ignores the parameters.
67///
68/// Eg.
69/// ```text
70/// $}}
71/// $}} " hello " " world" "text "
72/// ```
73/// Expected output:
74/// ```text
75/// }}
76/// }}
77/// ```
78pub fn right_brackets_function(_: &[String]) -> String {
79 "}}".to_string()
80}
81
82/// Inserts ". Ignores the parameters.
83///
84/// Eg.
85/// ```text
86/// $quote
87/// $quote " hello " " world" "text "
88/// ```
89/// Expected output:
90/// ```text
91/// "
92/// "
93/// ```
94pub fn quotes_function(_: &[String]) -> String {
95 "\"".to_string()
96}