isis-report-lib 0.2.0

Tabular reports with hierarchical layouts: HTML, PDF, XLSX, CSV and plain text
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! Python-compatible value semantics.
//!
//! The report engine came from Python and its behavior is part of the public
//! contract: `None` sorts last, `10 == 10.0`, `True == 1`, mixed type ordering
//! falls back to text, and so on. These helpers keep that behavior isolated
//! from the rest of the engine.

use std::cmp::Ordering;

use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;
use unicode_general_category::{get_general_category, GeneralCategory};

use crate::value::Value;

/// Error kind for Python-like scalar conversions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PyOpError {
    /// Wrong value type.
    TypeError,
    /// Malformed text.
    ValueError,
    /// Numeric overflow.
    Overflow,
}

/// Result alias for Python-like scalar conversions.
pub type PyOpResult<T> = Result<T, PyOpError>;

/// Python truthiness.
pub fn py_truthy(value: &Value) -> bool {
    match value {
        Value::Null => false,
        Value::Bool(value) => *value,
        Value::Int(value) => *value != 0,
        Value::UInt(value) => *value != 0,
        Value::Float(value) => *value != 0.0,
        Value::Decimal(value) => !value.is_zero(),
        Value::String(value) => !value.is_empty(),
        Value::Date(_) | Value::DateTime(_) => true,
        Value::Array(value) => !value.is_empty(),
        Value::Object(value) => !value.is_empty(),
    }
}

/// Python `str(value)`.
pub fn py_str(value: &Value) -> String {
    match value {
        Value::Null => "None".to_string(),
        Value::Bool(value) => {
            if *value {
                "True".to_string()
            } else {
                "False".to_string()
            }
        }
        Value::Int(value) => value.to_string(),
        Value::UInt(value) => value.to_string(),
        Value::Float(value) => py_float_str(*value),
        Value::Decimal(value) => value.to_string(),
        Value::String(value) => value.clone(),
        Value::Date(value) => value.format("%Y-%m-%d").to_string(),
        Value::DateTime(value) => py_datetime_str(value),
        Value::Array(values) => {
            let parts: Vec<String> = values.iter().map(py_repr).collect();
            format!("[{}]", parts.join(", "))
        }
        Value::Object(values) => {
            let parts: Vec<String> = values
                .iter()
                .map(|(key, value)| format!("{}: {}", py_string_repr(key), py_repr(value)))
                .collect();
            format!("{{{}}}", parts.join(", "))
        }
    }
}

/// Python `repr(value)`.
pub fn py_repr(value: &Value) -> String {
    match value {
        Value::String(value) => py_string_repr(value),
        _ => py_str(value),
    }
}

/// Format a timestamp like Python `str(datetime)`.
pub fn py_datetime_str(value: &chrono::DateTime<chrono::FixedOffset>) -> String {
    let base = value.format("%Y-%m-%d %H:%M:%S").to_string();
    let micros = value.timestamp_subsec_micros();
    let fraction = if micros == 0 { String::new() } else { format!(".{micros:06}") };
    format!("{base}{fraction}{}", value.format("%:z"))
}

/// Format a string like Python `repr()`.
pub fn py_string_repr(value: &str) -> String {
    let single = value.contains('\'');
    let double = value.contains('"');
    let quote = if single && !double { '"' } else { '\'' };
    let mut out = String::with_capacity(value.len() + 2);
    out.push(quote);
    for ch in value.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c == quote => {
                out.push('\\');
                out.push(c);
            }
            c if !is_printable(c) => {
                let code = c as u32;
                if code <= 0xFF {
                    out.push_str(&format!("\\x{code:02x}"));
                } else if code <= 0xFFFF {
                    out.push_str(&format!("\\u{code:04x}"));
                } else {
                    out.push_str(&format!("\\U{code:08x}"));
                }
            }
            c => out.push(c),
        }
    }
    out.push(quote);
    out
}

fn is_printable(ch: char) -> bool {
    !matches!(
        get_general_category(ch),
        GeneralCategory::Control
            | GeneralCategory::Format
            | GeneralCategory::Surrogate
            | GeneralCategory::PrivateUse
            | GeneralCategory::LineSeparator
            | GeneralCategory::ParagraphSeparator
            | GeneralCategory::Unassigned
    )
}

/// Python `str(float)`/`repr(float)` approximation (shortest round-trip,
/// scientific notation outside 1e-4..1e16, `.0` for integral values).
pub fn py_float_str(value: f64) -> String {
    if value.is_nan() {
        return "nan".to_string();
    }
    if value.is_infinite() {
        return if value > 0.0 { "inf" } else { "-inf" }.to_string();
    }
    if value == 0.0 {
        return if value.is_sign_negative() { "-0.0" } else { "0.0" }.to_string();
    }
    let abs = value.abs();
    if abs < 1e-4 || abs >= 1e16 {
        let raw = format!("{value:e}");
        let (mantissa, exponent) = raw.split_once('e').unwrap_or((&raw, "0"));
        let exponent: i32 = exponent.parse().unwrap_or(0);
        let sign = if exponent < 0 { '-' } else { '+' };
        format!("{mantissa}e{sign}{:02}", exponent.abs())
    } else {
        let raw = format!("{value}");
        if raw.contains('.') || raw.contains('e') || raw.contains('E') {
            raw
        } else {
            format!("{raw}.0")
        }
    }
}

/// Python `int(value)` for the scalar types the engine uses.
pub fn py_int(value: &Value) -> PyOpResult<i64> {
    match value {
        Value::Bool(value) => Ok(if *value { 1 } else { 0 }),
        Value::Int(value) => Ok(*value),
        Value::UInt(value) => i64::try_from(*value).map_err(|_| PyOpError::Overflow),
        Value::Float(value) => {
            if !value.is_finite() {
                return Err(PyOpError::ValueError);
            }
            let truncated = value.trunc();
            if truncated < i64::MIN as f64 || truncated > i64::MAX as f64 {
                return Err(PyOpError::Overflow);
            }
            Ok(truncated as i64)
        }
        Value::Decimal(value) => value.trunc().to_i64().ok_or(PyOpError::Overflow),
        Value::String(value) => parse_py_int(value),
        _ => Err(PyOpError::TypeError),
    }
}

/// Python `float(value)` for the scalar types the engine uses.
pub fn py_float(value: &Value) -> PyOpResult<f64> {
    match value {
        Value::Bool(value) => Ok(if *value { 1.0 } else { 0.0 }),
        Value::Int(value) => Ok(*value as f64),
        Value::UInt(value) => Ok(*value as f64),
        Value::Float(value) => Ok(*value),
        Value::Decimal(value) => value.to_f64().ok_or(PyOpError::Overflow),
        Value::String(value) => parse_py_float(value),
        _ => Err(PyOpError::TypeError),
    }
}

fn normalize_numeric_literal(value: &str) -> PyOpResult<String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Err(PyOpError::ValueError);
    }
    let mut out = String::with_capacity(trimmed.len());
    let chars: Vec<char> = trimmed.chars().collect();
    for (index, ch) in chars.iter().enumerate() {
        if *ch == '_' {
            let before = index.checked_sub(1).and_then(|i| chars.get(i)).copied();
            let after = chars.get(index + 1).copied();
            let before_digit = before.is_some_and(|c| c.is_ascii_alphanumeric());
            let after_digit = after.is_some_and(|c| c.is_ascii_alphanumeric());
            if !before_digit || !after_digit {
                return Err(PyOpError::ValueError);
            }
            continue;
        }
        out.push(*ch);
    }
    Ok(out)
}

/// Parse an integer with Python literal rules.
pub fn parse_py_int(value: &str) -> PyOpResult<i64> {
    let normalized = normalize_numeric_literal(value)?;
    let mut chars = normalized.chars();
    let mut body = normalized.as_str();
    if let Some(first) = chars.next() {
        if first == '+' || first == '-' {
            body = &normalized[1..];
        }
    }
    if body.is_empty() || !body.chars().all(|c| c.is_ascii_digit()) {
        return Err(PyOpError::ValueError);
    }
    normalized.parse::<i64>().map_err(|_| PyOpError::Overflow)
}

/// Parse a float with Python literal rules, including `nan`/`inf`.
pub fn parse_py_float(value: &str) -> PyOpResult<f64> {
    let normalized = normalize_numeric_literal(value)?;
    let lower = normalized.to_ascii_lowercase();
    if matches!(lower.as_str(), "nan" | "+nan" | "-nan") {
        return Ok(f64::NAN);
    }
    if matches!(lower.as_str(), "inf" | "+inf" | "infinity" | "+infinity") {
        return Ok(f64::INFINITY);
    }
    if matches!(lower.as_str(), "-inf" | "-infinity") {
        return Ok(f64::NEG_INFINITY);
    }
    normalized.parse::<f64>().map_err(|_| PyOpError::ValueError)
}

/// Python `==`.
pub fn py_eq(left: &Value, right: &Value) -> bool {
    match (left, right) {
        (Value::Null, Value::Null) => true,
        (Value::Bool(a), Value::Bool(b)) => a == b,
        (Value::String(a), Value::String(b)) => a == b,
        (Value::Date(a), Value::Date(b)) => a == b,
        (Value::DateTime(a), Value::DateTime(b)) => a == b,
        (Value::Decimal(a), Value::Decimal(b)) => a == b,
        (Value::Array(a), Value::Array(b)) => a.len() == b.len() && a.iter().zip(b).all(|(a, b)| py_eq(a, b)),
        (Value::Object(a), Value::Object(b)) => {
            a.len() == b.len() && a.iter().all(|(key, value)| b.get(key).is_some_and(|other| py_eq(value, other)))
        }
        _ if left.is_number() && right.is_number() => numeric_eq(left, right),
        _ => false,
    }
}

fn numeric_eq(left: &Value, right: &Value) -> bool {
    match (left, right) {
        (Value::Bool(a), Value::Bool(b)) => a == b,
        (Value::Int(a), Value::Int(b)) => a == b,
        (Value::UInt(a), Value::UInt(b)) => a == b,
        (Value::Int(a), Value::UInt(b)) => *a >= 0 && (*a as u64) == *b,
        (Value::UInt(a), Value::Int(b)) => *b >= 0 && *a == (*b as u64),
        (Value::Decimal(a), Value::Decimal(b)) => a == b,
        (Value::Decimal(a), Value::Int(b)) => *a == Decimal::from(*b),
        (Value::Int(a), Value::Decimal(b)) => Decimal::from(*a) == *b,
        (Value::Decimal(a), Value::UInt(b)) => *a == Decimal::from(*b),
        (Value::UInt(a), Value::Decimal(b)) => Decimal::from(*a) == *b,
        _ => match (py_float(left), py_float(right)) {
            (Ok(a), Ok(b)) => a == b,
            _ => false,
        },
    }
}

/// Python ordering for values that are comparable (`None` when Python would
/// raise a `TypeError`).
pub fn py_cmp(left: &Value, right: &Value) -> Option<Ordering> {
    match (left, right) {
        (Value::String(a), Value::String(b)) => Some(a.cmp(b)),
        (Value::Date(a), Value::Date(b)) => Some(a.cmp(b)),
        (Value::DateTime(a), Value::DateTime(b)) => Some(a.cmp(b)),
        (Value::Array(a), Value::Array(b)) => {
            for (a, b) in a.iter().zip(b) {
                match py_cmp(a, b) {
                    Some(Ordering::Equal) => continue,
                    other => return other,
                }
            }
            Some(a.len().cmp(&b.len()))
        }
        _ if left.is_number() && right.is_number() => numeric_cmp(left, right),
        _ => None,
    }
}

fn numeric_cmp(left: &Value, right: &Value) -> Option<Ordering> {
    match (left, right) {
        (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
        (Value::UInt(a), Value::UInt(b)) => Some(a.cmp(b)),
        (Value::Int(a), Value::UInt(b)) => {
            if *a < 0 {
                Some(Ordering::Less)
            } else {
                Some((*a as u64).cmp(b))
            }
        }
        (Value::UInt(a), Value::Int(b)) => {
            if *b < 0 {
                Some(Ordering::Greater)
            } else {
                Some(a.cmp(&(*b as u64)))
            }
        }
        (Value::Decimal(a), Value::Decimal(b)) => Some(a.cmp(b)),
        (Value::Decimal(a), Value::Int(b)) => Some(a.cmp(&Decimal::from(*b))),
        (Value::Int(a), Value::Decimal(b)) => Some(Decimal::from(*a).cmp(b)),
        (Value::Decimal(a), Value::UInt(b)) => Some(a.cmp(&Decimal::from(*b))),
        (Value::UInt(a), Value::Decimal(b)) => Some(Decimal::from(*a).cmp(b)),
        _ => py_float(left).ok().zip(py_float(right).ok()).and_then(|(a, b)| a.partial_cmp(&b)),
    }
}

/// Python `value in container` for the containers report rules use.
pub fn py_contains(container: &Value, needle: &Value) -> PyOpResult<bool> {
    match container {
        Value::String(text) => match needle {
            Value::String(needle) => Ok(text.contains(needle)),
            _ => Err(PyOpError::TypeError),
        },
        Value::Array(values) => Ok(values.iter().any(|value| py_eq(value, needle))),
        Value::Object(values) => match needle {
            Value::String(key) => Ok(values.contains_key(key)),
            Value::Array(_) | Value::Object(_) => Err(PyOpError::TypeError),
            _ => Ok(false),
        },
        _ => Err(PyOpError::TypeError),
    }
}

/// Python membership against the right-hand side of an `in`/`not_in` rule.
pub fn py_membership(value: &Value, expected: &Value) -> PyOpResult<bool> {
    match expected {
        Value::Array(values) => Ok(values.iter().any(|item| py_eq(value, item))),
        Value::String(text) => match value {
            Value::String(value) => Ok(text.contains(value)),
            _ => Err(PyOpError::TypeError),
        },
        Value::Object(values) => match value {
            Value::String(key) => Ok(values.contains_key(key)),
            Value::Array(_) | Value::Object(_) => Err(PyOpError::TypeError),
            _ => Ok(false),
        },
        _ => Err(PyOpError::TypeError),
    }
}

/// Canonical key used by `distinct` aggregation. Mirrors Python hash/equality
/// for the common cases (1, 1.0 and True are the same value; unhashable values
/// fall back to `str()`).
pub fn distinct_key(value: &Value) -> Option<String> {
    match value {
        Value::Null => None,
        Value::Bool(value) => Some(format!("n:{}", if *value { 1 } else { 0 })),
        Value::Int(value) => Some(format!("n:{value}")),
        Value::UInt(value) => Some(format!("n:{value}")),
        Value::Float(value) => {
            if *value == 0.0 {
                Some("n:0".to_string())
            } else if value.is_finite() && value.fract() == 0.0 {
                if *value >= i64::MIN as f64 && *value <= i64::MAX as f64 {
                    Some(format!("n:{}", *value as i64))
                } else {
                    Some(format!("n:f:{value:?}"))
                }
            } else {
                Some(format!("n:f:{value:?}"))
            }
        }
        Value::Decimal(value) => {
            if value.fract().is_zero() {
                if let Some(value) = value.trunc().to_i64() {
                    Some(format!("n:{value}"))
                } else {
                    Some(format!("n:d:{value}"))
                }
            } else {
                Some(format!("n:d:{value}"))
            }
        }
        Value::String(value) => Some(format!("s:{value}")),
        Value::Date(value) => Some(format!("d:{}", value.format("%Y-%m-%d"))),
        Value::DateTime(value) => Some(format!("dt:{}", value.to_rfc3339())),
        Value::Array(_) | Value::Object(_) => Some(format!("r:{}", py_str(value))),
    }
}

/// Sort key mirroring the Python `_sort_key`: numbers first, strings/text next,
/// `None` last.
#[derive(Debug, Clone, PartialEq)]
pub enum SortKey {
    /// Numeric value (bools included).
    Number(f64),
    /// Text value.
    Text(String),
    /// Nulls sort last.
    Null,
}

impl Eq for SortKey {}

impl PartialOrd for SortKey {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for SortKey {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            (SortKey::Null, SortKey::Null) => Ordering::Equal,
            (SortKey::Null, _) => Ordering::Greater,
            (_, SortKey::Null) => Ordering::Less,
            (SortKey::Number(a), SortKey::Number(b)) => a.partial_cmp(b).unwrap_or(Ordering::Equal),
            (SortKey::Number(_), SortKey::Text(_)) => Ordering::Less,
            (SortKey::Text(_), SortKey::Number(_)) => Ordering::Greater,
            (SortKey::Text(a), SortKey::Text(b)) => a.cmp(b),
        }
    }
}

/// Build a Python-compatible sort key.
pub fn sort_key(value: &Value) -> SortKey {
    match value {
        Value::Null => SortKey::Null,
        Value::Bool(value) => SortKey::Number(if *value { 1.0 } else { 0.0 }),
        Value::Int(value) => SortKey::Number(*value as f64),
        Value::UInt(value) => SortKey::Number(*value as f64),
        Value::Float(value) => SortKey::Number(*value),
        Value::Decimal(value) => SortKey::Number(value.to_f64().unwrap_or(f64::NAN)),
        _ => SortKey::Text(py_str(value)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn truthiness_matches_python() {
        assert!(!py_truthy(&Value::Null));
        assert!(!py_truthy(&Value::Int(0)));
        assert!(!py_truthy(&Value::String(String::new())));
        assert!(py_truthy(&Value::Float(f64::NAN)));
        assert!(py_truthy(&Value::Int(-1)));
    }

    #[test]
    fn str_and_repr_are_python_like() {
        assert_eq!(py_str(&Value::Null), "None");
        assert_eq!(py_str(&Value::Bool(true)), "True");
        assert_eq!(py_str(&Value::Float(1.0)), "1.0");
        assert_eq!(py_str(&Value::Float(1e16)), "1e+16");
        assert_eq!(py_str(&Value::Float(1e-5)), "1e-05");
        assert_eq!(py_str(&Value::String("a".into())), "a");
        assert_eq!(py_repr(&Value::String("a".into())), "'a'");
        assert_eq!(py_repr(&Value::String("a'b".into())), "\"a'b\"");
    }

    #[test]
    fn equality_crosses_numeric_types() {
        assert!(py_eq(&Value::Int(1), &Value::Float(1.0)));
        assert!(py_eq(&Value::Bool(true), &Value::Int(1)));
        assert!(!py_eq(&Value::Int(1), &Value::String("1".into())));
    }

    #[test]
    fn sort_keys_put_null_last_and_numbers_first() {
        assert!(sort_key(&Value::Int(10)) < sort_key(&Value::String("a".into())));
        assert!(sort_key(&Value::String("z".into())) < sort_key(&Value::Null));
    }

    #[test]
    fn int_and_float_parsing_follow_python() {
        assert_eq!(parse_py_int(" 1_0 ").unwrap(), 10);
        assert_eq!(parse_py_int("+7").unwrap(), 7);
        assert!(parse_py_int("1.5").is_err());
        assert_eq!(parse_py_float("1_0.5").unwrap(), 10.5);
        assert!(parse_py_float("nan").unwrap().is_nan());
        assert_eq!(parse_py_float("-inf").unwrap(), f64::NEG_INFINITY);
    }

    #[test]
    fn contains_and_membership() {
        let list = Value::Array(vec![Value::Int(1), Value::Int(2)]);
        assert!(py_contains(&list, &Value::Int(2)).unwrap());
        assert!(py_membership(&Value::String("a".into()), &Value::String("cat".into())).unwrap());
        assert!(!py_membership(&Value::Int(1), &Value::Int(2)).unwrap_or(false));
    }

    #[test]
    fn distinct_keys_merge_equal_numbers() {
        assert_eq!(distinct_key(&Value::Int(1)), distinct_key(&Value::Float(1.0)));
        assert_eq!(distinct_key(&Value::Bool(true)), distinct_key(&Value::Int(1)));
        assert_ne!(distinct_key(&Value::Int(1)), distinct_key(&Value::String("1".into())));
    }
}

#[cfg(test)]
mod extra_tests {
    use super::*;
    use chrono::{DateTime, NaiveDate};
    use rust_decimal::Decimal;
    use std::cmp::Ordering;

    #[test]
    fn comparisons_cover_numeric_and_container_edges() {
        assert_eq!(py_cmp(&Value::Int(-1), &Value::UInt(1)), Some(Ordering::Less));
        assert_eq!(py_cmp(&Value::UInt(1), &Value::Int(-1)), Some(Ordering::Greater));
        assert_eq!(py_cmp(&Value::Int(1), &Value::UInt(1)), Some(Ordering::Equal));
        assert_eq!(py_cmp(&Value::UInt(1), &Value::Int(1)), Some(Ordering::Equal));
        assert_eq!(
            py_cmp(&Value::Decimal(Decimal::new(15, 1)), &Value::Int(1)),
            Some(Ordering::Greater)
        );
        assert_eq!(py_cmp(&Value::Int(1), &Value::Decimal(Decimal::new(15, 1))), Some(Ordering::Less));
        assert_eq!(py_cmp(&Value::UInt(1), &Value::Decimal(Decimal::new(15, 1))), Some(Ordering::Less));
        assert_eq!(
            py_cmp(&Value::Decimal(Decimal::new(15, 1)), &Value::UInt(1)),
            Some(Ordering::Greater)
        );
        assert_eq!(
            py_cmp(
                &Value::Array(vec![Value::Int(1)]),
                &Value::Array(vec![Value::Int(1), Value::Int(2)])
            ),
            Some(Ordering::Less)
        );
        assert_eq!(py_cmp(&Value::Bool(true), &Value::Int(1)), Some(Ordering::Equal));
        assert_eq!(py_cmp(&Value::String("a".into()), &Value::String("b".into())), Some(Ordering::Less));
        assert_eq!(py_cmp(&Value::Null, &Value::Int(1)), None);
    }

    #[test]
    fn equality_handles_containers_dates_and_decimals() {
        assert!(py_eq(&Value::Array(vec![Value::Int(1)]), &Value::Array(vec![Value::Float(1.0)])));
        assert!(!py_eq(&Value::Array(vec![Value::Int(1)]), &Value::Array(vec![Value::Int(2)])));
        assert!(py_eq(
            &Value::Date(NaiveDate::from_ymd_opt(2024, 1, 1).unwrap()),
            &Value::Date(NaiveDate::from_ymd_opt(2024, 1, 1).unwrap())
        ));
        assert!(!py_eq(
            &Value::Date(NaiveDate::from_ymd_opt(2024, 1, 1).unwrap()),
            &Value::String("2024-01-01".into())
        ));
        let datetime = DateTime::parse_from_rfc3339("2024-01-01T00:00:00+00:00").unwrap();
        assert!(py_eq(&Value::DateTime(datetime), &Value::DateTime(datetime)));
        assert!(py_eq(&Value::Decimal(Decimal::new(1, 0)), &Value::Int(1)));
        assert!(!py_eq(&Value::Bool(true), &Value::String("True".into())));
    }

    #[test]
    fn containers_fail_closed_on_type_errors() {
        assert!(py_contains(&Value::String("abc".into()), &Value::Int(1)).is_err());
        assert!(py_contains(&Value::Int(1), &Value::Int(1)).is_err());
        assert!(py_contains(&Value::Object(Value::object()), &Value::Array(vec![])).is_err());
        assert!(!py_contains(&Value::Object(Value::object()), &Value::Int(1)).unwrap());
        assert!(py_membership(&Value::String("a".into()), &Value::Int(1)).is_err());
        assert!(py_membership(&Value::Array(vec![]), &Value::Object(Value::object())).is_err());
    }

    #[test]
    fn distinct_and_sort_keys_cover_every_variant() {
        assert_eq!(distinct_key(&Value::Null), None);
        assert_eq!(distinct_key(&Value::Float(-0.0)), Some("n:0".into()));
        assert_eq!(distinct_key(&Value::Float(2.0)), distinct_key(&Value::Int(2)));
        assert_eq!(distinct_key(&Value::Float(1.5)), Some("n:f:1.5".into()));
        assert_eq!(distinct_key(&Value::Decimal(Decimal::new(2, 0))), Some("n:2".into()));
        assert_eq!(distinct_key(&Value::Decimal(Decimal::new(15, 1))), Some("n:d:1.5".into()));
        assert_eq!(
            distinct_key(&Value::Date(NaiveDate::from_ymd_opt(2024, 1, 1).unwrap())),
            Some("d:2024-01-01".into())
        );
        assert!(distinct_key(&Value::Array(vec![])).unwrap().starts_with("r:"));
        assert!(distinct_key(&Value::Object(Value::object())).unwrap().starts_with("r:"));

        assert!(sort_key(&Value::Bool(true)) < sort_key(&Value::String("a".into())));
        assert!(sort_key(&Value::UInt(1)) < sort_key(&Value::String("a".into())));
        assert!(sort_key(&Value::Decimal(Decimal::new(15, 1))) < sort_key(&Value::String("a".into())));
        assert_eq!(sort_key(&Value::Null), SortKey::Null);
    }

    #[test]
    fn numeric_parsing_rejects_garbage_and_overflow() {
        assert_eq!(py_int(&Value::Bool(true)).unwrap(), 1);
        assert_eq!(py_int(&Value::Float(2.9)).unwrap(), 2);
        assert_eq!(py_int(&Value::String(" 4 ".into())).unwrap(), 4);
        assert!(py_int(&Value::Date(NaiveDate::from_ymd_opt(2024, 1, 1).unwrap())).is_err());
        assert_eq!(py_float(&Value::Int(2)).unwrap(), 2.0);
        assert_eq!(py_float(&Value::UInt(2)).unwrap(), 2.0);
        assert_eq!(py_float(&Value::Decimal(Decimal::new(15, 1))).unwrap(), 1.5);
        assert!(py_float(&Value::String("x".into())).is_err());
        assert!(parse_py_int("").is_err());
        assert!(parse_py_int("9223372036854775808").is_err());
        assert!(parse_py_float("").is_err());
        assert!(parse_py_float("1,2").is_err());
    }
}