oxblade 0.2.0

Laravel Blade templates for Rust: Blade's markup and directives with Rust expressions, rendering the same HTML as Laravel. Community package, not affiliated with Laravel.
Documentation
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use super::{mutate, select, support::*};
use crate::{
    error::Result,
    library::{CallLimits, data_depth_error},
    value::{Value, expansion_error},
};
use std::cmp::Ordering;

pub(super) fn stable_sort<T>(
    items: &mut [T],
    mut compare: impl FnMut(&T, &T) -> Result<Ordering>,
) -> Result<()> {
    fn merge_sort(
        order: &mut [usize],
        scratch: &mut [usize],
        compare: &mut impl FnMut(usize, usize) -> Result<Ordering>,
    ) -> Result<()> {
        if order.len() < 2 {
            return Ok(());
        }
        let mid = order.len() / 2;
        let (left, right) = order.split_at_mut(mid);
        merge_sort(left, scratch, compare)?;
        merge_sort(right, scratch, compare)?;
        let mut i = 0;
        let mut j = mid;
        for slot in &mut scratch[..order.len()] {
            if j == order.len() || i < mid && compare(order[i], order[j])?.is_le() {
                *slot = order[i];
                i += 1;
            } else {
                *slot = order[j];
                j += 1;
            }
        }
        order.copy_from_slice(&scratch[..order.len()]);
        Ok(())
    }

    let mut order: Vec<_> = (0..items.len()).collect();
    let mut scratch = vec![0; items.len()];
    let len = items.len();
    merge_sort(&mut order, &mut scratch, &mut |a, b| {
        compare(&items[a], &items[b])
    })?;
    for (new, old) in order.into_iter().enumerate() {
        scratch[old] = new;
    }
    for i in 0..len {
        while scratch[i] != i {
            let j = scratch[i];
            items.swap(i, j);
            scratch.swap(i, j);
        }
    }
    Ok(())
}

pub(super) fn slice_range(len: usize, offset: i64, length: Option<i64>) -> std::ops::Range<usize> {
    let start = signed_offset(len, offset);
    let end = match length {
        Some(n) if n < 0 => len.saturating_sub(magnitude(n)).max(start),
        Some(n) => start.saturating_add(magnitude(n)).min(len),
        None => len,
    };
    start..end
}

fn positive(value: i64, label: &str) -> Result<usize> {
    if value > 0 {
        Ok(magnitude(value))
    } else {
        Err(error(format!("{label} must be positive")))
    }
}

pub(super) fn run<'a>(
    name: &str,
    receiver: &Value<'a>,
    args: &mut Args<'a, '_>,
) -> Result<Value<'a>> {
    let mut input = rows(receiver)?;
    let keyed = is_map(receiver);
    let len = input.len();
    let limits = args.1;

    Ok(match name {
        "rev" => collection(keyed, input.into_iter().rev()),
        n if n.starts_with("sort") => sort(name, receiver, input, args)?,
        "unique" | "unique_strict" | "duplicates" | "duplicates_strict" => {
            args.bool(1, true)?;
            let duplicates = name.starts_with("duplicates");
            let mut seen: Vec<Value<'a>> = Vec::new();
            let mut out = Vec::new();
            for row in input {
                let item = args.selector(0, &row)?;
                let exists = any_match(&seen, |v| equal(v, &item, limits.data_depth()))?;
                if !exists {
                    seen.push(item.clone());
                }
                if exists == duplicates {
                    out.push(if duplicates { (row.0, item) } else { row });
                }
            }
            collection(keyed, out)
        }
        "take" | "skip" | "slice" | "for_page" => {
            let n = args.int(0, 0)?;
            let range = match name {
                "take" if n < 0 => signed_offset(len, n)..len,
                "take" => 0..magnitude(n).min(len),
                "for_page" => {
                    let count = positive(args.int(1, 0)?, "page size")?;
                    let offset = magnitude(n.saturating_sub(1).max(0))
                        .saturating_mul(count)
                        .min(len);
                    offset..offset.saturating_add(count).min(len)
                }
                _ => slice_range(
                    len,
                    n,
                    if is_null(&args.value(1)?) {
                        None
                    } else {
                        Some(args.int(1, 0)?)
                    },
                ),
            };
            collection(keyed, input.drain(range))
        }
        "take_until" | "take_while" | "skip_until" | "skip_while" => {
            let until = name.ends_with("until");
            let mut boundary = len;
            for (i, row) in input.iter().enumerate() {
                if select::matches(name, args, row)? == until {
                    boundary = i;
                    break;
                }
            }
            if name.starts_with("take") {
                collection(keyed, input.drain(..boundary))
            } else {
                collection(keyed, input.drain(boundary..))
            }
        }
        "nth" => {
            let step = positive(args.int(0, 0)?, "step")?;
            let offset = args.int(1, 0)?.max(0);
            collection(
                false,
                input.into_iter().skip(magnitude(offset)).step_by(step),
            )
        }
        "chunk" | "split_in" | "sliding" => {
            let amount = args.int(0, 2)?;
            let mut result = Vec::new();
            if name == "chunk" && amount <= 0 {
                return Ok(Value::List(result));
            }
            let size = positive(amount, "group size")?;
            if name == "sliding" {
                let step = positive(args.int(1, 1)?, "step")?;
                if size <= len {
                    expansion((len - size) / step + 1, size)?;
                    result.extend(
                        input
                            .windows(size)
                            .step_by(step)
                            .map(|w| collection(keyed, w.iter().cloned())),
                    );
                }
            } else {
                let size = if name == "split_in" {
                    len.div_ceil(size).max(1)
                } else {
                    size
                };
                let preserve = name != "chunk" || args.bool(1, true)?;
                result.extend(
                    input
                        .chunks(size)
                        .map(|c| collection(keyed && preserve, c.iter().cloned())),
                );
            }
            Value::List(result)
        }
        "split" => {
            let groups = positive(args.int(0, 0)?, "group count")?;
            let (size, larger) = (len / groups, len % groups);
            let mut input = input.into_iter();
            Value::List(
                (0..groups.min(len))
                    .map(|i| collection(keyed, input.by_ref().take(size + usize::from(i < larger))))
                    .collect(),
            )
        }
        "chunk_by" | "chunk_while" => {
            if name == "chunk_while" {
                args.closure(0)?;
            }
            let mut result = Vec::new();
            let mut chunk = Vec::new();
            let mut previous = Value::Null;
            for row in input {
                let selected = if name == "chunk_by" {
                    args.selector(0, &row)?
                } else {
                    Value::Null
                };
                if !chunk.is_empty() {
                    let same = if name == "chunk_by" {
                        equal(&selected, &previous, limits.data_depth())?
                    } else {
                        let group = collection(keyed, chunk.iter().cloned());
                        boolean(&args.call(0, &[row.1.clone(), row.0.clone(), group])?)?
                    };
                    if !same {
                        result.push(collection(keyed, std::mem::take(&mut chunk)));
                    }
                }
                previous = selected;
                chunk.push(row);
            }
            if !chunk.is_empty() {
                result.push(collection(keyed, chunk));
            }
            Value::List(result)
        }
        "flatten" => {
            let mut result = Vec::new();
            let depth = args.int(0, i64::MAX)?.max(1);
            for (_, v) in input {
                flatten(v, depth, limits.data_depth(), limits.expansion, &mut result)?;
            }
            Value::List(result)
        }
        "collapse" | "collapse_with_keys" => {
            let nested = input.into_iter().map(|(_, v)| v).filter(is_collection);
            if name == "collapse" {
                mutate::merge_many(nested.map(Ok), false, limits)?
            } else {
                mutate::replace_many(nested, false, limits)?
            }
        }
        "dot" => Value::Map(dot(receiver, "", args.int(0, i64::MAX)?, limits)?),
        "undot" => {
            let mut out = Value::Map(map());
            for (k, v) in input {
                mutate::set_path(&mut out, &key(&k)?, v)?;
            }
            out
        }
        "zip" | "cross_join" => {
            let inputs = std::iter::once(Ok(input.into_iter().map(|(_, v)| v).collect()))
                .chain((0..args.0.len()).map(|i| values(&args.value(i)?)))
                .collect::<Result<Vec<_>>>()?;
            if name == "zip" {
                let height = inputs.iter().map(Vec::len).max().unwrap_or_default();
                expansion(height, inputs.len())?;
                Value::List(
                    (0..height)
                        .map(|i| {
                            Value::List(
                                inputs
                                    .iter()
                                    .map(|column| column.get(i).cloned().unwrap_or(Value::Null))
                                    .collect(),
                            )
                        })
                        .collect(),
                )
            } else {
                if inputs.iter().any(Vec::is_empty) {
                    return Ok(Value::List(vec![]));
                }
                let height = inputs
                    .iter()
                    .try_fold(1, |height, column| expansion(height, column.len()))?;
                expansion(height, inputs.len())?;
                let mut out = vec![Vec::new()];
                for column in inputs {
                    out = out
                        .into_iter()
                        .flat_map(|row| {
                            column.iter().map(move |item| {
                                let mut row = row.clone();
                                row.push(item.clone());
                                row
                            })
                        })
                        .collect();
                }
                Value::List(out.into_iter().map(Value::List).collect())
            }
        }
        _ => return Err(error("unknown collection ordering operation")),
    })
}

pub(super) fn expansion(length: usize, width: usize) -> Result<usize> {
    const MAX_EXPANSION: usize = 100_000;
    length
        .checked_mul(width)
        .filter(|n| *n <= MAX_EXPANSION)
        .ok_or_else(crate::value::expansion_error)
}

fn flatten<'a>(
    item: Value<'a>,
    depth: i64,
    remaining_depth: usize,
    expansion: usize,
    output: &mut Vec<Value<'a>>,
) -> Result<()> {
    if depth > 0 && is_collection(&item) {
        let remaining_depth = remaining_depth
            .checked_sub(1)
            .ok_or_else(data_depth_error)?;
        for (_, child) in item.entries(expansion)? {
            flatten(
                child.scalar(),
                depth - 1,
                remaining_depth,
                expansion,
                output,
            )?;
        }
    } else {
        if output.len() >= expansion {
            return Err(expansion_error());
        }
        output.push(item);
    }
    Ok(())
}

pub(super) fn dot<'a>(
    receiver: &Value<'a>,
    prefix: &str,
    depth: i64,
    limits: CallLimits,
) -> Result<crate::value::ValueMap<'a>> {
    fn add<'a>(
        receiver: &Value<'a>,
        prefix: &str,
        depth: i64,
        limits: CallLimits,
        out: &mut crate::value::ValueMap<'a>,
    ) -> Result<()> {
        for (k, v) in receiver.entries(limits.expansion)? {
            let v = if matches!(v, Value::Json(_)) {
                v.scalar()
            } else {
                v
            };
            let k = key(&k)?;
            limits.check_bytes(prefix.len().checked_add(k.len()))?;
            let path = format!("{prefix}{k}");
            if depth > 0 && is_collection(&v) && size(&v) != 0 {
                let depth_left = limits.depth.checked_sub(1).ok_or_else(data_depth_error)?;
                add(
                    &v,
                    &format!("{path}."),
                    depth - 1,
                    CallLimits {
                        depth: depth_left,
                        ..limits
                    },
                    out,
                )?;
            } else {
                if out.len() >= limits.expansion && !out.contains_key(&path) {
                    return Err(expansion_error());
                }
                out.insert(path, v);
            }
        }
        Ok(())
    }
    if !is_collection(receiver) {
        return Err(error("expected a list or map"));
    }
    let mut out = map();
    add(
        receiver,
        prefix,
        depth,
        CallLimits {
            depth: limits.data_depth(),
            ..limits
        },
        &mut out,
    )?;
    Ok(out)
}

fn compare_direction(a: &Value<'_>, b: &Value<'_>, desc: bool, depth: usize) -> Result<Ordering> {
    if desc {
        compare(b, a, depth)
    } else {
        compare(a, b, depth)
    }
}

fn sort<'a>(
    name: &str,
    receiver: &Value<'a>,
    mut input: Vec<Row<'a>>,
    args: &mut Args<'a, '_>,
) -> Result<Value<'a>> {
    let keyed = is_map(receiver);
    let descending = name.ends_with("_desc");
    let depth = args.1.data_depth();
    match name {
        "sort_by" | "sort_by_desc" => {
            regular(args, 1)?;
            let descending = descending || args.bool(2, false)?;
            let selectors = if !args.has_closure(0) && is_list(&args.value(0)?) {
                Some(sort_selectors(&args.value(0)?, descending)?)
            } else {
                None
            };
            input = match selectors.as_deref() {
                None => sort_selected(
                    input,
                    |row| args.selector(0, row),
                    |a, b| compare_direction(a, b, descending, depth),
                )?,
                Some([(path, descending)]) => sort_selected(
                    input,
                    |row| data_get(&row.1, path, depth).map(|value| value.unwrap_or(Value::Null)),
                    |a, b| compare_direction(a, b, *descending, depth),
                )?,
                Some(selectors) => sort_selected(
                    input,
                    |row| {
                        selectors
                            .iter()
                            .map(|(path, _)| {
                                data_get(&row.1, path, depth)
                                    .map(|value| value.unwrap_or(Value::Null))
                            })
                            .collect::<Result<Vec<_>>>()
                    },
                    |a, b| {
                        for ((a, b), (_, descending)) in a.iter().zip(b).zip(selectors) {
                            let order = compare_direction(a, b, *descending, depth)?;
                            if !order.is_eq() {
                                return Ok(order);
                            }
                        }
                        Ok(Ordering::Equal)
                    },
                )?,
            };
        }
        "sort_keys_using" => stable_sort(&mut input, |(a, _), (b, _)| {
            Ok(integer(&args.call(0, &[a.clone(), b.clone()])?)?.cmp(&0))
        })?,
        "sort_keys" | "sort_keys_desc" => {
            regular(args, 0)?;
            let desc = descending || args.bool(1, false)?;
            stable_sort(&mut input, |(a, _), (b, _)| {
                compare_direction(a, b, desc, depth)
            })?;
        }
        "sort_recursive" | "sort_recursive_desc" => {
            regular(args, 0)?;
            let descending = descending || args.bool(1, false)?;
            return recursive_sort(receiver, descending, depth);
        }
        "sort" if args.has_closure(0) => {
            stable_sort(&mut input, |(_, a), (_, b)| {
                Ok(integer(&args.call(0, &[a.clone(), b.clone()])?)?.cmp(&0))
            })?;
        }
        _ => {
            regular(args, 0)?;
            stable_sort(&mut input, |(_, a), (_, b)| {
                compare_direction(a, b, descending, depth)
            })?;
        }
    }
    Ok(collection(keyed, input))
}

fn sort_selected<'a, K>(
    rows: Vec<Row<'a>>,
    mut select: impl FnMut(&Row<'a>) -> Result<K>,
    mut compare: impl FnMut(&K, &K) -> Result<Ordering>,
) -> Result<Vec<Row<'a>>> {
    let mut decorated = rows
        .into_iter()
        .map(|row| Ok((select(&row)?, row)))
        .collect::<Result<Vec<_>>>()?;
    stable_sort(&mut decorated, |(a, _), (b, _)| compare(a, b))?;
    Ok(decorated.into_iter().map(|(_, row)| row).collect())
}

fn regular(args: &Args<'_, '_>, index: usize) -> Result<()> {
    if args.int(index, 0)? == 0 {
        Ok(())
    } else {
        Err(error("PHP sort flags require an explicit Rust closure"))
    }
}

fn recursive_sort<'a>(receiver: &Value<'a>, descending: bool, depth: usize) -> Result<Value<'a>> {
    let mut input = rows(receiver)?;
    let keyed = is_map(receiver);
    for (_, value) in &mut input {
        if is_collection(value) {
            *value = recursive_sort(
                value,
                descending,
                depth.checked_sub(1).ok_or_else(data_depth_error)?,
            )?;
        }
    }
    stable_sort(&mut input, |(ak, av), (bk, bv)| {
        let (a, b) = if keyed { (ak, bk) } else { (av, bv) };
        compare_direction(a, b, descending, depth)
    })?;
    Ok(collection(keyed, input))
}

fn sort_selectors(value: &Value<'_>, descending: bool) -> Result<Vec<(String, bool)>> {
    values(value)?
        .into_iter()
        .map(|v| {
            if !is_list(&v) {
                return Ok((key(&v)?, descending));
            }
            let fields = values(&v)?;
            match fields.as_slice() {
                [path] => Ok((key(path)?, descending)),
                [path, direction] => {
                    let desc = match string(direction)?.as_ref() {
                        "asc" => false,
                        "desc" => true,
                        _ => return Err(error("sort direction must be asc or desc")),
                    };
                    Ok((key(path)?, desc))
                }
                _ => Err(error(
                    "sort selector must contain a path and optional direction",
                )),
            }
        })
        .collect()
}