Skip to main content

zero_client/ivm/
data.rs

1//! Value comparison for rows (`packages/zql/src/ivm/data.ts`); the value
2//! orders themselves are in [`crate::compare`].
3
4use super::Row;
5use crate::ast::{Direction, OrderPart};
6use crate::compare;
7use crate::json::Value;
8use std::cell::Cell;
9use std::cmp::Ordering;
10use std::rc::Rc;
11
12/// Orders rows (`Comparator` in `data.ts`).
13pub type Comparator = Rc<dyn Fn(&Row, &Row) -> Ordering>;
14
15static NULL: Value = Value::Null;
16
17/// A row's value for `column`; a missing column reads as `null`.
18pub fn value<'a>(row: &'a Row, column: &str) -> &'a Value {
19    row.get(column).unwrap_or(&NULL)
20}
21
22/// `compareValues` on possibly missing values: `undefined` reads as `null`.
23pub fn compare_values(a: Option<&Value>, b: Option<&Value>) -> Ordering {
24    compare::compare(a.unwrap_or(&NULL), b.unwrap_or(&NULL))
25}
26
27/// `valuesEqual` on possibly missing values: `undefined` and `null` equal
28/// nothing.
29pub fn values_equal(a: Option<&Value>, b: Option<&Value>) -> bool {
30    match (a, b) {
31        (Some(a), Some(b)) => compare::equal(a, b),
32        _ => false,
33    }
34}
35
36/// JS `===` on possibly missing values. Arrays and objects are never
37/// identical, since rows are decoded fresh.
38pub fn identical(a: Option<&Value>, b: Option<&Value>) -> bool {
39    match (a, b) {
40        (None, None) => true,
41        (Some(Value::Null), Some(Value::Null)) => true,
42        (Some(Value::String(x)), Some(Value::String(y))) => x == y,
43        (Some(Value::Number(x)), Some(Value::Number(y))) => x == y,
44        (Some(Value::Bool(x)), Some(Value::Bool(y))) => x == y,
45        _ => false,
46    }
47}
48
49/// `makeComparator(order, reverse)`.
50pub fn make_comparator(order: &[OrderPart], reverse: bool) -> Comparator {
51    let parts: Vec<(String, bool, Cell<usize>)> = order
52        .iter()
53        .map(|p| (p.field.clone(), p.direction == Direction::Asc, Cell::new(0)))
54        .collect();
55    Rc::new(move |a: &Row, b: &Row| {
56        for (field, asc, hint) in &parts {
57            let c = compare_values(a.get_hinted(field, hint), b.get_hinted(field, hint));
58            if c != Ordering::Equal {
59                let c = if *asc { c } else { c.reverse() };
60                return if reverse { c.reverse() } else { c };
61            }
62        }
63        Ordering::Equal
64    })
65}