1use std::fmt;
13
14use chrono::{DateTime, FixedOffset, NaiveDate};
15use indexmap::IndexMap;
16use rust_decimal::Decimal;
17use serde::{Deserialize, Deserializer, Serialize, Serializer};
18
19use crate::pyops;
20
21#[derive(Clone, Debug, Default, PartialEq)]
23pub enum Value {
24 #[default]
26 Null,
27 Bool(bool),
29 Int(i64),
31 UInt(u64),
33 Float(f64),
35 Decimal(Decimal),
37 String(String),
39 Date(NaiveDate),
41 DateTime(DateTime<FixedOffset>),
43 Array(Vec<Value>),
45 Object(IndexMap<String, Value>),
47}
48
49impl Value {
50 pub fn object() -> IndexMap<String, Value> {
52 IndexMap::new()
53 }
54
55 pub fn from_object(object: IndexMap<String, Value>) -> Self {
57 Self::Object(object)
58 }
59
60 pub fn from_array(array: Vec<Value>) -> Self {
62 Self::Array(array)
63 }
64
65 pub fn is_null(&self) -> bool {
67 matches!(self, Self::Null)
68 }
69
70 pub fn is_number(&self) -> bool {
72 matches!(
73 self,
74 Self::Bool(_) | Self::Int(_) | Self::UInt(_) | Self::Float(_) | Self::Decimal(_)
75 )
76 }
77
78 pub fn is_string(&self) -> bool {
80 matches!(self, Self::String(_))
81 }
82
83 pub fn is_array(&self) -> bool {
85 matches!(self, Self::Array(_))
86 }
87
88 pub fn is_object(&self) -> bool {
90 matches!(self, Self::Object(_))
91 }
92
93 pub fn as_bool(&self) -> Option<bool> {
95 match self {
96 Self::Bool(value) => Some(*value),
97 _ => None,
98 }
99 }
100
101 pub fn as_str(&self) -> Option<&str> {
103 match self {
104 Self::String(value) => Some(value),
105 _ => None,
106 }
107 }
108
109 pub fn as_array(&self) -> Option<&Vec<Value>> {
111 match self {
112 Self::Array(value) => Some(value),
113 _ => None,
114 }
115 }
116
117 pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
119 match self {
120 Self::Array(value) => Some(value),
121 _ => None,
122 }
123 }
124
125 pub fn as_object(&self) -> Option<&IndexMap<String, Value>> {
127 match self {
128 Self::Object(value) => Some(value),
129 _ => None,
130 }
131 }
132
133 pub fn as_object_mut(&mut self) -> Option<&mut IndexMap<String, Value>> {
135 match self {
136 Self::Object(value) => Some(value),
137 _ => None,
138 }
139 }
140
141 pub fn get(&self, key: &str) -> Option<&Value> {
143 self.as_object().and_then(|object| object.get(key))
144 }
145
146 pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
148 self.as_object_mut().and_then(|object| object.get_mut(key))
149 }
150
151 pub fn contains_key(&self, key: &str) -> bool {
153 self.as_object().is_some_and(|object| object.contains_key(key))
154 }
155
156 pub fn insert(&mut self, key: impl Into<String>, value: impl Into<Value>) -> Option<Value> {
158 self.as_object_mut().and_then(|object| object.insert(key.into(), value.into()))
159 }
160
161 pub fn push(&mut self, value: impl Into<Value>) {
163 if let Some(array) = self.as_array_mut() {
164 array.push(value.into());
165 }
166 }
167
168 pub fn as_f64(&self) -> Option<f64> {
170 pyops::py_float(self).ok()
171 }
172
173 pub fn as_i64(&self) -> Option<i64> {
175 pyops::py_int(self).ok()
176 }
177
178 pub fn py_str(&self) -> String {
180 pyops::py_str(self)
181 }
182
183 pub fn py_repr(&self) -> String {
185 pyops::py_repr(self)
186 }
187
188 pub fn truthy(&self) -> bool {
190 pyops::py_truthy(self)
191 }
192
193 pub fn to_json(&self) -> serde_json::Value {
196 match self {
197 Self::Null => serde_json::Value::Null,
198 Self::Bool(value) => serde_json::Value::Bool(*value),
199 Self::Int(value) => serde_json::Value::Number((*value).into()),
200 Self::UInt(value) => serde_json::Value::Number((*value).into()),
201 Self::Float(value) => {
202 if value.is_finite() {
203 serde_json::Number::from_f64(*value)
204 .map(serde_json::Value::Number)
205 .unwrap_or(serde_json::Value::Null)
206 } else {
207 serde_json::Value::Null
208 }
209 }
210 Self::Decimal(value) => serde_json::Value::String(value.to_string()),
211 Self::String(value) => serde_json::Value::String(value.clone()),
212 Self::Date(value) => serde_json::Value::String(value.format("%Y-%m-%d").to_string()),
213 Self::DateTime(value) => serde_json::Value::String(value.to_rfc3339()),
214 Self::Array(values) => serde_json::Value::Array(values.iter().map(Value::to_json).collect()),
215 Self::Object(values) => {
216 let mut object = serde_json::Map::with_capacity(values.len());
217 for (key, value) in values {
218 object.insert(key.clone(), value.to_json());
219 }
220 serde_json::Value::Object(object)
221 }
222 }
223 }
224
225 pub fn from_json(value: serde_json::Value) -> Self {
227 match value {
228 serde_json::Value::Null => Self::Null,
229 serde_json::Value::Bool(value) => Self::Bool(value),
230 serde_json::Value::Number(number) => {
231 if let Some(value) = number.as_i64() {
232 Self::Int(value)
233 } else if let Some(value) = number.as_u64() {
234 Self::UInt(value)
235 } else {
236 Self::Float(number.as_f64().unwrap_or(f64::NAN))
237 }
238 }
239 serde_json::Value::String(value) => Self::String(value),
240 serde_json::Value::Array(values) => Self::Array(values.into_iter().map(Self::from_json).collect()),
241 serde_json::Value::Object(values) => {
242 let mut object = IndexMap::with_capacity(values.len());
243 for (key, value) in values {
244 object.insert(key, Self::from_json(value));
245 }
246 Self::Object(object)
247 }
248 }
249 }
250
251 pub fn to_json_string(&self) -> String {
253 serde_json::to_string(&self.to_json()).unwrap_or_else(|_| "null".to_string())
254 }
255}
256
257impl fmt::Display for Value {
258 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
259 formatter.write_str(&self.py_str())
260 }
261}
262
263impl Serialize for Value {
264 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
265 where
266 S: Serializer,
267 {
268 self.to_json().serialize(serializer)
269 }
270}
271
272impl<'de> Deserialize<'de> for Value {
273 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
274 where
275 D: Deserializer<'de>,
276 {
277 let value = serde_json::Value::deserialize(deserializer)?;
278 Ok(Self::from_json(value))
279 }
280}
281
282impl From<serde_json::Value> for Value {
283 fn from(value: serde_json::Value) -> Self {
284 Self::from_json(value)
285 }
286}
287
288impl From<Value> for serde_json::Value {
289 fn from(value: Value) -> Self {
290 value.to_json()
291 }
292}
293
294impl From<bool> for Value {
295 fn from(value: bool) -> Self {
296 Self::Bool(value)
297 }
298}
299
300impl From<i64> for Value {
301 fn from(value: i64) -> Self {
302 Self::Int(value)
303 }
304}
305
306impl From<i32> for Value {
307 fn from(value: i32) -> Self {
308 Self::Int(value as i64)
309 }
310}
311
312impl From<u64> for Value {
313 fn from(value: u64) -> Self {
314 Self::UInt(value)
315 }
316}
317
318impl From<f64> for Value {
319 fn from(value: f64) -> Self {
320 Self::Float(value)
321 }
322}
323
324impl From<Decimal> for Value {
325 fn from(value: Decimal) -> Self {
326 Self::Decimal(value)
327 }
328}
329
330impl From<String> for Value {
331 fn from(value: String) -> Self {
332 Self::String(value)
333 }
334}
335
336impl From<&str> for Value {
337 fn from(value: &str) -> Self {
338 Self::String(value.to_string())
339 }
340}
341
342impl From<NaiveDate> for Value {
343 fn from(value: NaiveDate) -> Self {
344 Self::Date(value)
345 }
346}
347
348impl From<DateTime<FixedOffset>> for Value {
349 fn from(value: DateTime<FixedOffset>) -> Self {
350 Self::DateTime(value)
351 }
352}
353
354impl From<IndexMap<String, Value>> for Value {
355 fn from(value: IndexMap<String, Value>) -> Self {
356 Self::Object(value)
357 }
358}
359
360impl<T> From<Vec<T>> for Value
361where
362 T: Into<Value>,
363{
364 fn from(value: Vec<T>) -> Self {
365 Self::Array(value.into_iter().map(Into::into).collect())
366 }
367}
368
369impl<T> From<Option<T>> for Value
370where
371 T: Into<Value>,
372{
373 fn from(value: Option<T>) -> Self {
374 match value {
375 Some(value) => value.into(),
376 None => Self::Null,
377 }
378 }
379}
380
381#[cfg(test)]
382mod tests {
383 use super::*;
384 use chrono::DateTime;
385 use rust_decimal::Decimal;
386 use serde_json::json;
387
388 fn object() -> Value {
389 let mut map = Value::object();
390 map.insert("a".to_string(), Value::Int(1));
391 Value::from_object(map)
392 }
393
394 #[test]
395 fn predicates_accessors_and_mutators() {
396 let mut value = object();
397 assert!(value.is_object());
398 assert!(value.contains_key("a"));
399 assert_eq!(value.get("a"), Some(&Value::Int(1)));
400 *value.get_mut("a").unwrap() = Value::Int(2);
401 assert_eq!(value.get("a"), Some(&Value::Int(2)));
402 assert_eq!(value.insert("b", true), None);
403 assert_eq!(value.insert("b", 3), Some(Value::Bool(true)));
404 assert!(!value.is_array());
405 assert!(value.as_array().is_none());
406 assert!(value.as_array_mut().is_none());
407 assert!(value.as_bool().is_none());
408 assert!(value.as_str().is_none());
409
410 let mut array = Value::from_array(vec![Value::Int(1)]);
411 assert!(array.is_array());
412 array.push(2);
413 assert_eq!(array.as_array().unwrap().len(), 2);
414 array.as_array_mut().unwrap().push(Value::Int(3));
415 assert_eq!(array.as_array().unwrap().len(), 3);
416 array.push(Value::Null); assert_eq!(array.as_array().unwrap().len(), 4);
418
419 assert!(Value::Null.is_null());
420 assert!(Value::Bool(true).is_number());
421 assert!(Value::Decimal(Decimal::new(15, 1)).is_number());
422 assert!(Value::String("x".into()).is_string());
423 }
424
425 #[test]
426 fn numeric_and_python_accessors() {
427 assert_eq!(Value::Int(10).as_f64(), Some(10.0));
428 assert_eq!(Value::Float(10.5).as_i64(), Some(10));
429 assert_eq!(Value::String("3".into()).as_i64(), Some(3));
430 assert_eq!(Value::Null.as_f64(), None);
431 assert_eq!(Value::String("hello".into()).py_str(), "hello");
432 assert_eq!(Value::String("hello".into()).py_repr(), "'hello'");
433 assert!(Value::Int(1).truthy());
434 assert!(!Value::Int(0).truthy());
435 assert!(!Value::Null.truthy());
436 assert_eq!(Value::Int(1).to_string(), "1");
437 }
438
439 #[test]
440 fn from_index_map_and_option() {
441 let mut map = IndexMap::new();
442 map.insert("a".to_string(), Value::Int(1));
443 let value = Value::from(map);
444 assert_eq!(value.get("a"), Some(&Value::Int(1)));
445 assert_eq!(Value::from(Some(2)), Value::Int(2));
446 assert_eq!(Value::from(Option::<i64>::None), Value::Null);
447 assert_eq!(Value::from(vec![1, 2]), Value::Array(vec![Value::Int(1), Value::Int(2)]));
448 }
449
450 #[test]
451 fn json_roundtrip_for_every_variant() {
452 let date = NaiveDate::from_ymd_opt(2024, 1, 2).unwrap();
453 let datetime = DateTime::parse_from_rfc3339("2024-01-02T03:04:05+00:00").unwrap();
454 let decimal = Decimal::new(12345, 2);
455 let values = vec![
456 Value::Null,
457 Value::Bool(true),
458 Value::Int(-1),
459 Value::UInt(1),
460 Value::Float(1.5),
461 Value::Float(f64::NAN),
462 Value::Float(f64::INFINITY),
463 Value::Decimal(decimal),
464 Value::String("x".into()),
465 Value::Date(date),
466 Value::DateTime(datetime),
467 Value::Array(vec![Value::Int(1), Value::Null]),
468 object(),
469 ];
470 for value in values {
471 let json = value.to_json();
472 let parsed = Value::from_json(json);
473 if matches!(value, Value::Float(f) if !f.is_finite()) {
474 assert!(parsed.is_null());
475 } else if let Value::Decimal(decimal) = value {
476 assert_eq!(parsed, Value::String(decimal.to_string()));
477 } else if let Value::UInt(value) = value {
478 assert_eq!(parsed, Value::Int(value as i64));
479 } else if let Value::Date(date) = value {
480 assert_eq!(parsed, Value::String(date.format("%Y-%m-%d").to_string()));
481 } else if let Value::DateTime(datetime) = value {
482 assert_eq!(parsed, Value::String(datetime.to_rfc3339()));
483 } else {
484 assert_eq!(parsed, value);
485 }
486 assert!(!value.to_json_string().is_empty());
487 }
488 assert_eq!(
489 Value::from_json(json!({"a": [1, 2]})).get("a").unwrap().as_array().unwrap().len(),
490 2
491 );
492 assert_eq!(Value::from_json(json!(1.25)), Value::Float(1.25));
493 assert_eq!(Value::from_json(json!(u64::MAX)), Value::UInt(u64::MAX));
494 }
495
496 #[test]
497 fn conversions_and_serde() {
498 assert_eq!(Value::from(true), Value::Bool(true));
499 assert_eq!(Value::from(1_i64), Value::Int(1));
500 assert_eq!(Value::from(1_i32), Value::Int(1));
501 assert_eq!(Value::from(1_u64), Value::UInt(1));
502 assert_eq!(Value::from(1.5_f64), Value::Float(1.5));
503 assert_eq!(Value::from("x"), Value::String("x".into()));
504 assert_eq!(Value::from(String::from("x")), Value::String("x".into()));
505 assert_eq!(Value::from(Some(1_i64)), Value::Int(1));
506 assert_eq!(Value::from(None::<i64>), Value::Null);
507 assert_eq!(Value::from(vec![1_i64, 2]), Value::Array(vec![Value::Int(1), Value::Int(2)]));
508
509 let decimal = Decimal::new(15, 1);
510 assert_eq!(Value::from(decimal), Value::Decimal(decimal));
511 let date = NaiveDate::from_ymd_opt(2024, 1, 2).unwrap();
512 assert_eq!(Value::from(date), Value::Date(date));
513 let datetime = DateTime::parse_from_rfc3339("2024-01-02T03:04:05+00:00").unwrap();
514 assert_eq!(Value::from(datetime), Value::DateTime(datetime));
515
516 let value = object();
517 let encoded = serde_json::to_string(&value).unwrap();
518 let decoded: Value = serde_json::from_str(&encoded).unwrap();
519 assert_eq!(decoded, value);
520 assert_eq!(serde_json::Value::from(value.clone()), value.to_json());
521 }
522}