handlebars/helpers/
helper_extras.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
//! Helpers for boolean operations

use std::cmp::Ordering;
use std::str::FromStr;

use num_order::NumOrd;
use serde_json::Value as Json;

use crate::json::value::JsonTruthy;

handlebars_helper!(eq: |x: Json, y: Json| x == y);
handlebars_helper!(ne: |x: Json, y: Json| x != y);
handlebars_helper!(gt: |x: Json, y: Json| compare_json(x, y) == Some(Ordering::Greater));
handlebars_helper!(gte: |x: Json, y: Json| compare_json(x, y).is_some_and(|ord| ord != Ordering::Less));
handlebars_helper!(lt: |x: Json, y: Json| compare_json(x, y) == Some(Ordering::Less));
handlebars_helper!(lte: |x: Json, y: Json| compare_json(x, y).is_some_and(|ord| ord != Ordering::Greater));
handlebars_helper!(not: |x: Json| !x.is_truthy(false));
handlebars_helper!(len: |x: Json| {
    match x {
        Json::Array(a) => a.len(),
        Json::Object(m) => m.len(),
        Json::String(s) => s.len(),
        _ => 0
    }
});

fn compare_json(x: &Json, y: &Json) -> Option<Ordering> {
    fn cmp_num_str(a_num: &serde_json::Number, b_str: &str) -> Option<Ordering> {
        let b_num = serde_json::Number::from_str(b_str).ok()?;
        cmp_nums(a_num, &b_num)
    }

    // this function relies on serde_json::Numbers coerce logic
    // for number value between [0, u64::MAX], is_u64() returns true
    // for number value between [i64::MIN, i64::MAX], is_i64() returns true
    // for others, is_f64() returns true, note that this behaviour is not
    //  guaranteed according to serde_json docs
    fn cmp_nums(a_num: &serde_json::Number, b_num: &serde_json::Number) -> Option<Ordering> {
        if a_num.is_u64() {
            let a = a_num.as_u64()?;
            if b_num.is_u64() {
                NumOrd::num_partial_cmp(&a, &b_num.as_u64()?)
            } else if b_num.is_i64() {
                NumOrd::num_partial_cmp(&a, &b_num.as_i64()?)
            } else {
                NumOrd::num_partial_cmp(&a, &b_num.as_f64()?)
            }
        } else if a_num.is_i64() {
            let a = a_num.as_i64()?;
            if b_num.is_u64() {
                NumOrd::num_partial_cmp(&a, &b_num.as_u64()?)
            } else if b_num.is_i64() {
                NumOrd::num_partial_cmp(&a, &b_num.as_i64()?)
            } else {
                NumOrd::num_partial_cmp(&a, &b_num.as_f64()?)
            }
        } else {
            let a = a_num.as_f64()?;
            if b_num.is_u64() {
                NumOrd::num_partial_cmp(&a, &b_num.as_u64()?)
            } else if b_num.is_i64() {
                NumOrd::num_partial_cmp(&a, &b_num.as_i64()?)
            } else {
                NumOrd::num_partial_cmp(&a, &b_num.as_f64()?)
            }
        }
    }

    match (x, y) {
        (Json::Number(a), Json::Number(b)) => cmp_nums(a, b),
        (Json::String(a), Json::String(b)) => Some(a.cmp(b)),
        (Json::Bool(a), Json::Bool(b)) => Some(a.cmp(b)),
        (Json::Number(a), Json::String(b)) => cmp_num_str(a, b),
        (Json::String(a), Json::Number(b)) => cmp_num_str(b, a).map(Ordering::reverse),
        _ => None,
    }
}

#[allow(non_camel_case_types)]
pub struct and;

impl crate::HelperDef for and {
    fn call_inner<'reg: 'rc, 'rc>(
        &self,
        h: &crate::Helper<'rc>,
        _r: &'reg crate::Handlebars<'reg>,
        _: &'rc crate::Context,
        _: &mut crate::RenderContext<'reg, 'rc>,
    ) -> std::result::Result<crate::ScopedJson<'rc>, crate::RenderError> {
        let all_true = h.params().iter().all(|p| p.value().is_truthy(false));
        Ok(crate::ScopedJson::Derived(crate::JsonValue::from(all_true)))
    }
}

#[allow(non_camel_case_types)]
pub struct or;

impl crate::HelperDef for or {
    fn call_inner<'reg: 'rc, 'rc>(
        &self,
        h: &crate::Helper<'rc>,
        _r: &'reg crate::Handlebars<'reg>,
        _: &'rc crate::Context,
        _: &mut crate::RenderContext<'reg, 'rc>,
    ) -> std::result::Result<crate::ScopedJson<'rc>, crate::RenderError> {
        let any_true = h.params().iter().any(|p| p.value().is_truthy(false));
        Ok(crate::ScopedJson::Derived(crate::JsonValue::from(any_true)))
    }
}

#[cfg(test)]
mod test_conditions {
    fn test_condition(condition: &str, expected: bool) {
        let handlebars = crate::Handlebars::new();

        let result = handlebars
            .render_template(
                &format!("{{{{#if {condition}}}}}lorem{{{{else}}}}ipsum{{{{/if}}}}"),
                &json!({}),
            )
            .unwrap();
        assert_eq!(&result, if expected { "lorem" } else { "ipsum" });
    }

    #[test]
    fn test_and_or() {
        test_condition("(or (gt 3 5) (gt 5 3))", true);
        test_condition("(and null 4)", false);
        test_condition("(or null 4)", true);
        test_condition("(and null 4 5 6)", false);
        test_condition("(or null 4 5 6)", true);
        test_condition("(and 1 2 3 4)", true);
        test_condition("(or 1 2 3 4)", true);
        test_condition("(and 1 2 3 4 0)", false);
        test_condition("(or 1 2 3 4 0)", true);
        test_condition("(or null 2 3 4 0)", true);
        test_condition("(or [] [])", false);
        test_condition("(or [1] [])", true);
        test_condition("(or [1] [2])", true);
        test_condition("(or [1] [2] [3])", true);
        test_condition("(or [1] [2] [3] [4])", true);
        test_condition("(or [1] [2] [3] [4] [])", true);
    }

    #[test]
    fn test_cmp() {
        test_condition("(gt 5 3)", true);
        test_condition("(gt 3 5)", false);
        test_condition("(not [])", true);
    }

    #[test]
    fn test_eq() {
        test_condition("(eq 5 5)", true);
        test_condition("(eq 5 6)", false);
        test_condition(r#"(eq "foo" "foo")"#, true);
        test_condition(r#"(eq "foo" "Foo")"#, false);
        test_condition(r"(eq [5] [5])", true);
        test_condition(r"(eq [5] [4])", false);
        test_condition(r#"(eq 5 "5")"#, false);
        test_condition(r"(eq 5 [5])", false);
    }

    #[test]
    fn test_ne() {
        test_condition("(ne 5 6)", true);
        test_condition("(ne 5 5)", false);
        test_condition(r#"(ne "foo" "foo")"#, false);
        test_condition(r#"(ne "foo" "Foo")"#, true);
    }

    #[test]
    fn nested_conditions() {
        let handlebars = crate::Handlebars::new();

        let result = handlebars
            .render_template("{{#if (gt 5 3)}}lorem{{else}}ipsum{{/if}}", &json!({}))
            .unwrap();
        assert_eq!(&result, "lorem");

        let result = handlebars
            .render_template(
                "{{#if (not (gt 5 3))}}lorem{{else}}ipsum{{/if}}",
                &json!({}),
            )
            .unwrap();
        assert_eq!(&result, "ipsum");
    }

    #[test]
    fn test_len() {
        let handlebars = crate::Handlebars::new();

        let result = handlebars
            .render_template("{{len value}}", &json!({"value": [1,2,3]}))
            .unwrap();
        assert_eq!(&result, "3");

        let result = handlebars
            .render_template("{{len value}}", &json!({"value": {"a" :1, "b": 2}}))
            .unwrap();
        assert_eq!(&result, "2");

        let result = handlebars
            .render_template("{{len value}}", &json!({"value": "tomcat"}))
            .unwrap();
        assert_eq!(&result, "6");

        let result = handlebars
            .render_template("{{len value}}", &json!({"value": 3}))
            .unwrap();
        assert_eq!(&result, "0");
    }

    #[test]
    fn test_comparisons() {
        // Integer comparisons
        test_condition("(gt 5 3)", true);
        test_condition("(gt 3 5)", false);
        test_condition("(gte 5 5)", true);
        test_condition("(lt 3 5)", true);
        test_condition("(lte 5 5)", true);
        test_condition("(lt 9007199254740992 9007199254740993)", true);

        // Float comparisons
        test_condition("(gt 5.5 3.3)", true);
        test_condition("(gt 3.3 5.5)", false);
        test_condition("(gte 5.5 5.5)", true);
        test_condition("(lt 3.3 5.5)", true);
        test_condition("(lte 5.5 5.5)", true);

        // String comparisons
        test_condition(r#"(gt "b" "a")"#, true);
        test_condition(r#"(lt "a" "b")"#, true);
        test_condition(r#"(gte "a" "a")"#, true);

        // Mixed type comparisons
        test_condition(r#"(gt 53 "35")"#, true);
        test_condition(r#"(lt 53 "35")"#, false);
        test_condition(r#"(lt "35" 53)"#, true);
        test_condition(r#"(gte "53" 53)"#, true);
        test_condition(r#"(lt -1 0)"#, true);
        test_condition(r#"(lt "-1" 0)"#, true);
        test_condition(r#"(lt "-1.00" 0)"#, true);
        test_condition(r#"(gt "1.00" 0)"#, true);
        test_condition(r#"(gt 0 -1)"#, true);
        test_condition(r#"(gt 0 "-1")"#, true);
        test_condition(r#"(gt 0 "-1.00")"#, true);
        test_condition(r#"(lt 0 "1.00")"#, true);
        // u64::MAX
        test_condition(r#"(gt 18446744073709551615 -1)"#, true);

        // Boolean comparisons
        test_condition("(gt true false)", true);
        test_condition("(lt false true)", true);
    }
}