use std::fmt;
use chrono::{DateTime, FixedOffset, NaiveDate};
use indexmap::IndexMap;
use rust_decimal::Decimal;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::pyops;
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Value {
#[default]
Null,
Bool(bool),
Int(i64),
UInt(u64),
Float(f64),
Decimal(Decimal),
String(String),
Date(NaiveDate),
DateTime(DateTime<FixedOffset>),
Array(Vec<Value>),
Object(IndexMap<String, Value>),
}
impl Value {
pub fn object() -> IndexMap<String, Value> {
IndexMap::new()
}
pub fn from_object(object: IndexMap<String, Value>) -> Self {
Self::Object(object)
}
pub fn from_array(array: Vec<Value>) -> Self {
Self::Array(array)
}
pub fn is_null(&self) -> bool {
matches!(self, Self::Null)
}
pub fn is_number(&self) -> bool {
matches!(
self,
Self::Bool(_) | Self::Int(_) | Self::UInt(_) | Self::Float(_) | Self::Decimal(_)
)
}
pub fn is_string(&self) -> bool {
matches!(self, Self::String(_))
}
pub fn is_array(&self) -> bool {
matches!(self, Self::Array(_))
}
pub fn is_object(&self) -> bool {
matches!(self, Self::Object(_))
}
pub fn as_bool(&self) -> Option<bool> {
match self {
Self::Bool(value) => Some(*value),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
Self::String(value) => Some(value),
_ => None,
}
}
pub fn as_array(&self) -> Option<&Vec<Value>> {
match self {
Self::Array(value) => Some(value),
_ => None,
}
}
pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
match self {
Self::Array(value) => Some(value),
_ => None,
}
}
pub fn as_object(&self) -> Option<&IndexMap<String, Value>> {
match self {
Self::Object(value) => Some(value),
_ => None,
}
}
pub fn as_object_mut(&mut self) -> Option<&mut IndexMap<String, Value>> {
match self {
Self::Object(value) => Some(value),
_ => None,
}
}
pub fn get(&self, key: &str) -> Option<&Value> {
self.as_object().and_then(|object| object.get(key))
}
pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
self.as_object_mut().and_then(|object| object.get_mut(key))
}
pub fn contains_key(&self, key: &str) -> bool {
self.as_object().is_some_and(|object| object.contains_key(key))
}
pub fn insert(&mut self, key: impl Into<String>, value: impl Into<Value>) -> Option<Value> {
self.as_object_mut().and_then(|object| object.insert(key.into(), value.into()))
}
pub fn push(&mut self, value: impl Into<Value>) {
if let Some(array) = self.as_array_mut() {
array.push(value.into());
}
}
pub fn as_f64(&self) -> Option<f64> {
pyops::py_float(self).ok()
}
pub fn as_i64(&self) -> Option<i64> {
pyops::py_int(self).ok()
}
pub fn py_str(&self) -> String {
pyops::py_str(self)
}
pub fn py_repr(&self) -> String {
pyops::py_repr(self)
}
pub fn truthy(&self) -> bool {
pyops::py_truthy(self)
}
pub fn to_json(&self) -> serde_json::Value {
match self {
Self::Null => serde_json::Value::Null,
Self::Bool(value) => serde_json::Value::Bool(*value),
Self::Int(value) => serde_json::Value::Number((*value).into()),
Self::UInt(value) => serde_json::Value::Number((*value).into()),
Self::Float(value) => {
if value.is_finite() {
serde_json::Number::from_f64(*value)
.map(serde_json::Value::Number)
.unwrap_or(serde_json::Value::Null)
} else {
serde_json::Value::Null
}
}
Self::Decimal(value) => serde_json::Value::String(value.to_string()),
Self::String(value) => serde_json::Value::String(value.clone()),
Self::Date(value) => serde_json::Value::String(value.format("%Y-%m-%d").to_string()),
Self::DateTime(value) => serde_json::Value::String(value.to_rfc3339()),
Self::Array(values) => serde_json::Value::Array(values.iter().map(Value::to_json).collect()),
Self::Object(values) => {
let mut object = serde_json::Map::with_capacity(values.len());
for (key, value) in values {
object.insert(key.clone(), value.to_json());
}
serde_json::Value::Object(object)
}
}
}
pub fn from_json(value: serde_json::Value) -> Self {
match value {
serde_json::Value::Null => Self::Null,
serde_json::Value::Bool(value) => Self::Bool(value),
serde_json::Value::Number(number) => {
if let Some(value) = number.as_i64() {
Self::Int(value)
} else if let Some(value) = number.as_u64() {
Self::UInt(value)
} else {
Self::Float(number.as_f64().unwrap_or(f64::NAN))
}
}
serde_json::Value::String(value) => Self::String(value),
serde_json::Value::Array(values) => Self::Array(values.into_iter().map(Self::from_json).collect()),
serde_json::Value::Object(values) => {
let mut object = IndexMap::with_capacity(values.len());
for (key, value) in values {
object.insert(key, Self::from_json(value));
}
Self::Object(object)
}
}
}
pub fn to_json_string(&self) -> String {
serde_json::to_string(&self.to_json()).unwrap_or_else(|_| "null".to_string())
}
}
impl fmt::Display for Value {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.py_str())
}
}
impl Serialize for Value {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.to_json().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Value {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = serde_json::Value::deserialize(deserializer)?;
Ok(Self::from_json(value))
}
}
impl From<serde_json::Value> for Value {
fn from(value: serde_json::Value) -> Self {
Self::from_json(value)
}
}
impl From<Value> for serde_json::Value {
fn from(value: Value) -> Self {
value.to_json()
}
}
impl From<bool> for Value {
fn from(value: bool) -> Self {
Self::Bool(value)
}
}
impl From<i64> for Value {
fn from(value: i64) -> Self {
Self::Int(value)
}
}
impl From<i32> for Value {
fn from(value: i32) -> Self {
Self::Int(value as i64)
}
}
impl From<u64> for Value {
fn from(value: u64) -> Self {
Self::UInt(value)
}
}
impl From<f64> for Value {
fn from(value: f64) -> Self {
Self::Float(value)
}
}
impl From<Decimal> for Value {
fn from(value: Decimal) -> Self {
Self::Decimal(value)
}
}
impl From<String> for Value {
fn from(value: String) -> Self {
Self::String(value)
}
}
impl From<&str> for Value {
fn from(value: &str) -> Self {
Self::String(value.to_string())
}
}
impl From<NaiveDate> for Value {
fn from(value: NaiveDate) -> Self {
Self::Date(value)
}
}
impl From<DateTime<FixedOffset>> for Value {
fn from(value: DateTime<FixedOffset>) -> Self {
Self::DateTime(value)
}
}
impl From<IndexMap<String, Value>> for Value {
fn from(value: IndexMap<String, Value>) -> Self {
Self::Object(value)
}
}
impl<T> From<Vec<T>> for Value
where
T: Into<Value>,
{
fn from(value: Vec<T>) -> Self {
Self::Array(value.into_iter().map(Into::into).collect())
}
}
impl<T> From<Option<T>> for Value
where
T: Into<Value>,
{
fn from(value: Option<T>) -> Self {
match value {
Some(value) => value.into(),
None => Self::Null,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::DateTime;
use rust_decimal::Decimal;
use serde_json::json;
fn object() -> Value {
let mut map = Value::object();
map.insert("a".to_string(), Value::Int(1));
Value::from_object(map)
}
#[test]
fn predicates_accessors_and_mutators() {
let mut value = object();
assert!(value.is_object());
assert!(value.contains_key("a"));
assert_eq!(value.get("a"), Some(&Value::Int(1)));
*value.get_mut("a").unwrap() = Value::Int(2);
assert_eq!(value.get("a"), Some(&Value::Int(2)));
assert_eq!(value.insert("b", true), None);
assert_eq!(value.insert("b", 3), Some(Value::Bool(true)));
assert!(!value.is_array());
assert!(value.as_array().is_none());
assert!(value.as_array_mut().is_none());
assert!(value.as_bool().is_none());
assert!(value.as_str().is_none());
let mut array = Value::from_array(vec![Value::Int(1)]);
assert!(array.is_array());
array.push(2);
assert_eq!(array.as_array().unwrap().len(), 2);
array.as_array_mut().unwrap().push(Value::Int(3));
assert_eq!(array.as_array().unwrap().len(), 3);
array.push(Value::Null); assert_eq!(array.as_array().unwrap().len(), 4);
assert!(Value::Null.is_null());
assert!(Value::Bool(true).is_number());
assert!(Value::Decimal(Decimal::new(15, 1)).is_number());
assert!(Value::String("x".into()).is_string());
}
#[test]
fn numeric_and_python_accessors() {
assert_eq!(Value::Int(10).as_f64(), Some(10.0));
assert_eq!(Value::Float(10.5).as_i64(), Some(10));
assert_eq!(Value::String("3".into()).as_i64(), Some(3));
assert_eq!(Value::Null.as_f64(), None);
assert_eq!(Value::String("hello".into()).py_str(), "hello");
assert_eq!(Value::String("hello".into()).py_repr(), "'hello'");
assert!(Value::Int(1).truthy());
assert!(!Value::Int(0).truthy());
assert!(!Value::Null.truthy());
assert_eq!(Value::Int(1).to_string(), "1");
}
#[test]
fn from_index_map_and_option() {
let mut map = IndexMap::new();
map.insert("a".to_string(), Value::Int(1));
let value = Value::from(map);
assert_eq!(value.get("a"), Some(&Value::Int(1)));
assert_eq!(Value::from(Some(2)), Value::Int(2));
assert_eq!(Value::from(Option::<i64>::None), Value::Null);
assert_eq!(Value::from(vec![1, 2]), Value::Array(vec![Value::Int(1), Value::Int(2)]));
}
#[test]
fn json_roundtrip_for_every_variant() {
let date = NaiveDate::from_ymd_opt(2024, 1, 2).unwrap();
let datetime = DateTime::parse_from_rfc3339("2024-01-02T03:04:05+00:00").unwrap();
let decimal = Decimal::new(12345, 2);
let values = vec![
Value::Null,
Value::Bool(true),
Value::Int(-1),
Value::UInt(1),
Value::Float(1.5),
Value::Float(f64::NAN),
Value::Float(f64::INFINITY),
Value::Decimal(decimal),
Value::String("x".into()),
Value::Date(date),
Value::DateTime(datetime),
Value::Array(vec![Value::Int(1), Value::Null]),
object(),
];
for value in values {
let json = value.to_json();
let parsed = Value::from_json(json);
if matches!(value, Value::Float(f) if !f.is_finite()) {
assert!(parsed.is_null());
} else if let Value::Decimal(decimal) = value {
assert_eq!(parsed, Value::String(decimal.to_string()));
} else if let Value::UInt(value) = value {
assert_eq!(parsed, Value::Int(value as i64));
} else if let Value::Date(date) = value {
assert_eq!(parsed, Value::String(date.format("%Y-%m-%d").to_string()));
} else if let Value::DateTime(datetime) = value {
assert_eq!(parsed, Value::String(datetime.to_rfc3339()));
} else {
assert_eq!(parsed, value);
}
assert!(!value.to_json_string().is_empty());
}
assert_eq!(
Value::from_json(json!({"a": [1, 2]})).get("a").unwrap().as_array().unwrap().len(),
2
);
assert_eq!(Value::from_json(json!(1.25)), Value::Float(1.25));
assert_eq!(Value::from_json(json!(u64::MAX)), Value::UInt(u64::MAX));
}
#[test]
fn conversions_and_serde() {
assert_eq!(Value::from(true), Value::Bool(true));
assert_eq!(Value::from(1_i64), Value::Int(1));
assert_eq!(Value::from(1_i32), Value::Int(1));
assert_eq!(Value::from(1_u64), Value::UInt(1));
assert_eq!(Value::from(1.5_f64), Value::Float(1.5));
assert_eq!(Value::from("x"), Value::String("x".into()));
assert_eq!(Value::from(String::from("x")), Value::String("x".into()));
assert_eq!(Value::from(Some(1_i64)), Value::Int(1));
assert_eq!(Value::from(None::<i64>), Value::Null);
assert_eq!(Value::from(vec![1_i64, 2]), Value::Array(vec![Value::Int(1), Value::Int(2)]));
let decimal = Decimal::new(15, 1);
assert_eq!(Value::from(decimal), Value::Decimal(decimal));
let date = NaiveDate::from_ymd_opt(2024, 1, 2).unwrap();
assert_eq!(Value::from(date), Value::Date(date));
let datetime = DateTime::parse_from_rfc3339("2024-01-02T03:04:05+00:00").unwrap();
assert_eq!(Value::from(datetime), Value::DateTime(datetime));
let value = object();
let encoded = serde_json::to_string(&value).unwrap();
let decoded: Value = serde_json::from_str(&encoded).unwrap();
assert_eq!(decoded, value);
assert_eq!(serde_json::Value::from(value.clone()), value.to_json());
}
}