Skip to main content

session_file/
js.rs

1//! JavaScript semantics only the session format uses: `Array.prototype.join`'s `String`, `?? `/`== null`,
2//! `new Date(value)` of a JSON value, and V8's comparator sort. The shared primitives are in [`jsrt`].
3
4use serde_json::Value;
5
6/// `undefined` or `null`, the values `??` and `== null` treat as missing.
7pub fn nullish(value: Option<&Value>) -> bool {
8    matches!(value, None | Some(Value::Null))
9}
10
11/// `String(value)` as `Array.prototype.join` applies it: `null` and `undefined` become "".
12pub fn join_string(value: Option<&Value>) -> String {
13    match value {
14        None | Some(Value::Null) => String::new(),
15        Some(Value::Bool(b)) => b.to_string(),
16        Some(Value::Number(n)) => jsrt::number::json_to_string(n),
17        Some(Value::String(s)) => s.clone(),
18        Some(Value::Array(items)) => items.iter().map(|v| join_string(Some(v))).collect::<Vec<_>>().join(","),
19        Some(Value::Object(_)) => "[object Object]".to_string(),
20    }
21}
22
23/// `new Date(value).getTime()` for a JSON value; `None` is `NaN` (an invalid date).
24pub fn date_value(value: Option<&Value>) -> Option<i64> {
25    match value? {
26        Value::String(s) => jsrt::date::parse_date(s),
27        Value::Array(_) | Value::Object(_) => None,
28        other => jsrt::date::time_clip(jsrt::value::number(other)),
29    }
30}
31
32/// A timestamp as a JSON number, or `null` for an invalid date (as `JSON.stringify(NaN)` writes it).
33pub fn date_json(value: Option<&Value>) -> Value {
34    date_value(value).map_or(Value::Null, Value::from)
35}
36
37/// `Array.prototype.sort` with a comparator, as V8 runs it on arrays under 64 elements (one natural
38/// run, then binary insertion). A `NaN` comparison counts as equal. Stable; never panics on an
39/// inconsistent comparator.
40// ponytail: V8 merges runs for 64+ elements; for consistent comparators any stable sort agrees.
41pub fn sort_by<T>(items: &mut [T], compare: impl Fn(&T, &T) -> f64) {
42    let less = |a: &T, b: &T| compare(a, b) < 0.0;
43    let n = items.len();
44    if n < 2 {
45        return;
46    }
47    let mut run = 2;
48    let descending = less(&items[1], &items[0]);
49    while run < n {
50        let order_less = less(&items[run], &items[run - 1]);
51        let equal_or_greater = !order_less;
52        if (descending && equal_or_greater) || (!descending && order_less) {
53            break;
54        }
55        run += 1;
56    }
57    if descending {
58        items[..run].reverse();
59    }
60    for start in run..n {
61        let (mut left, mut right) = (0, start);
62        while left < right {
63            let mid = left + (right - left) / 2;
64            if less(&items[start], &items[mid]) {
65                right = mid;
66            } else {
67                left = mid + 1;
68            }
69        }
70        items[left..=start].rotate_right(1);
71    }
72}