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;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PyOpError {
TypeError,
ValueError,
Overflow,
}
pub type PyOpResult<T> = Result<T, PyOpError>;
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(),
}
}
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(", "))
}
}
}
pub fn py_repr(value: &Value) -> String {
match value {
Value::String(value) => py_string_repr(value),
_ => py_str(value),
}
}
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"))
}
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
)
}
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")
}
}
}
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),
}
}
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)
}
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)
}
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)
}
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,
},
}
}
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)),
}
}
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),
}
}
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),
}
}
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))),
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum SortKey {
Number(f64),
Text(String),
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),
}
}
}
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());
}
}