Skip to main content

zero_client/
compare.rs

1//! Comparing row values (`packages/zql/src/ivm/data.ts`).
2
3use crate::json::{Value, stringify};
4use crate::strings;
5use std::cmp::Ordering;
6use std::fmt;
7
8/// Two values JS's `compareValues` throws on.
9#[derive(Clone, Debug, PartialEq, Eq)]
10pub struct IncomparableError(pub String);
11
12impl fmt::Display for IncomparableError {
13    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14        f.write_str(&self.0)
15    }
16}
17
18impl std::error::Error for IncomparableError {}
19
20/// JS's `typeof`, which calls an array an object.
21fn type_of(v: &Value) -> &'static str {
22    match v {
23        Value::Array(_) => "object",
24        v => v.type_name(),
25    }
26}
27
28/// `compareValues(a, b)`: strings by UTF-8 bytes, numbers numerically,
29/// `false < true`, and `null` before everything. Values of different
30/// non-null types, and arrays or objects, can't be compared: JS throws.
31pub fn compare_checked(a: &Value, b: &Value) -> Result<Ordering, IncomparableError> {
32    match scalar_compare(a, b) {
33        Some(o) => Ok(o),
34        None if type_of(a) != type_of(b) => Err(IncomparableError(format!(
35            "Cannot compare values of different types: {} and {}",
36            type_of(a),
37            type_of(b)
38        ))),
39        None => Err(IncomparableError(format!(
40            "Unsupported type: {}",
41            type_of(a)
42        ))),
43    }
44}
45
46/// [`compare_checked`], with a total order for the inputs JS throws on: by
47/// type, then by JSON encoding. Pipelines use this so a bad `orderBy` (on a
48/// json column) degrades instead of failing.
49pub fn compare(a: &Value, b: &Value) -> Ordering {
50    scalar_compare(a, b).unwrap_or_else(|| {
51        let rank = |v: &Value| match v {
52            Value::Null => 0,
53            Value::Bool(_) => 1,
54            Value::Number(_) => 2,
55            Value::String(_) => 3,
56            Value::Array(_) => 4,
57            Value::Object(_) => 5,
58        };
59        rank(a)
60            .cmp(&rank(b))
61            .then_with(|| strings::utf8(&stringify(a), &stringify(b)))
62    })
63}
64
65fn scalar_compare(a: &Value, b: &Value) -> Option<Ordering> {
66    Some(match (a, b) {
67        (Value::String(x), Value::String(y)) => strings::utf8(x, y),
68        // NaN can't come from JSON; JS's `<`/`>` would call it equal.
69        (Value::Number(x), Value::Number(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
70        (Value::Bool(x), Value::Bool(y)) => x.cmp(y),
71        (Value::Null, Value::Null) => Ordering::Equal,
72        (Value::Null, _) => Ordering::Less,
73        (_, Value::Null) => Ordering::Greater,
74        _ => return None,
75    })
76}
77
78/// `valuesEqual(a, b)`: like `===`, except `null` equals nothing (as in SQL
79/// joins). Arrays and objects are never equal: JS compares them by
80/// reference.
81pub fn equal(a: &Value, b: &Value) -> bool {
82    match (a, b) {
83        (Value::String(x), Value::String(y)) => x == y,
84        (Value::Number(x), Value::Number(y)) => x == y,
85        (Value::Bool(x), Value::Bool(y)) => x == y,
86        _ => false,
87    }
88}