teo_parser/value/
value.rs

1use std::cmp::Ordering;
2use std::fmt::{Display, Formatter};
3use std::mem;
4use std::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Not, Rem, Shl, Shr, Sub};
5use std::str::FromStr;
6use bigdecimal::{BigDecimal, Zero};
7use bson::oid::ObjectId;
8use chrono::{DateTime, NaiveDate, SecondsFormat, Utc};
9use indexmap::IndexMap;
10use itertools::Itertools;
11use regex::Regex;
12use teo_result::Error;
13use crate::r#type::Type;
14use crate::value::index::Index;
15
16use super::{interface_enum_variant::InterfaceEnumVariant, option_variant::OptionVariant, range::Range};
17
18/// Unlike the Value that runtime defines, this value is for parser use only.
19#[derive(Debug, Clone)]
20pub enum Value {
21    Null,
22    Bool(bool),
23    Int(i32),
24    Int64(i64),
25    Float32(f32),
26    Float(f64),
27    Decimal(BigDecimal),
28    ObjectId(ObjectId),
29    String(String),
30    Date(NaiveDate),
31    DateTime(DateTime<Utc>),
32    Array(Vec<Value>),
33    Dictionary(IndexMap<String, Value>),
34    Range(Range),
35    Tuple(Vec<Value>),
36    OptionVariant(OptionVariant),
37    InterfaceEnumVariant(InterfaceEnumVariant),
38    Regex(Regex),
39    Type(Type),
40}
41
42impl Value {
43
44    // Access
45
46    pub fn get<I: Index>(&self, index: I) -> Option<&Value> {
47        index.index_into(self)
48    }
49
50    pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> {
51        index.index_into_mut(self)
52    }
53
54    // Value
55
56    pub fn is_null(&self) -> bool {
57        match self {
58            Value::Null => true,
59            _ => false,
60        }
61    }
62
63    pub fn is_bool(&self) -> bool {
64        self.as_bool().is_some()
65    }
66
67    pub fn as_bool(&self) -> Option<bool> {
68        match *self {
69            Value::Bool(b) => Some(b),
70            _ => None,
71        }
72    }
73
74    pub fn is_int(&self) -> bool {
75        self.as_int().is_some()
76    }
77
78    pub fn as_int(&self) -> Option<i32> {
79        match *self {
80            Value::Int(v) => Some(v),
81            _ => None
82        }
83    }
84
85    pub fn to_int(&self) -> Option<i32> {
86        match *self {
87            Value::Int(i) => Some(i),
88            Value::Int64(i) => if i >= (i32::MAX as i64) {
89                None
90            } else {
91                Some(i as i32)
92            }
93            _ => None
94        }
95    }
96
97    pub fn is_int64(&self) -> bool {
98        self.as_int64().is_some()
99    }
100
101    pub fn as_int64(&self) -> Option<i64> {
102        match *self {
103            Value::Int64(v) => Some(v),
104            _ => None
105        }
106    }
107
108    pub fn to_int64(&self) -> Option<i64> {
109        match *self {
110            Value::Int64(v) => Some(v),
111            Value::Int(v) => Some(v as i64),
112            _ => None,
113        }
114    }
115
116    pub fn is_float32(&self) -> bool {
117        self.as_float32().is_some()
118    }
119
120    pub fn as_float32(&self) -> Option<f32> {
121        match *self {
122            Value::Float32(v) => Some(v),
123            _ => None
124        }
125    }
126
127    pub fn to_float32(&self) -> Option<f32> {
128        match *self {
129            Value::Float32(v) => Some(v),
130            Value::Float(v) => Some(v as f32),
131            Value::Int(i) => Some(i as f32),
132            Value::Int64(i) => Some(i as f32),
133            _ => None,
134        }
135    }
136
137    pub fn is_float(&self) -> bool {
138        self.as_float().is_some()
139    }
140
141    pub fn as_float(&self) -> Option<f64> {
142        match *self {
143            Value::Float(v) => Some(v),
144            _ => None
145        }
146    }
147
148    pub fn to_float(&self) -> Option<f64> {
149        match *self {
150            Value::Int(v) => Some(v as f64),
151            Value::Int64(v) => Some(v as f64),
152            Value::Float32(v) => Some(v as f64),
153            Value::Float(v) => Some(v),
154            _ => None
155        }
156    }
157
158    pub fn is_decimal(&self) -> bool {
159        match *self {
160            Value::Decimal(_) => true,
161            _ => false,
162        }
163    }
164
165    pub fn as_decimal(&self) -> Option<&BigDecimal> {
166        match self {
167            Value::Decimal(v) => Some(v),
168            _ => None
169        }
170    }
171
172    pub fn is_object_id(&self) -> bool {
173        self.as_object_id().is_some()
174    }
175
176    pub fn as_object_id(&self) -> Option<&ObjectId> {
177        match self {
178            Value::ObjectId(o) => Some(o),
179            _ => None,
180        }
181    }
182
183    pub fn is_string(&self) -> bool {
184        self.as_str().is_some()
185    }
186
187    pub fn as_str(&self) -> Option<&str> {
188        match self {
189            Value::String(s) => Some(s),
190            _ => None,
191        }
192    }
193
194    pub fn is_date(&self) -> bool {
195        self.as_date().is_some()
196    }
197
198    pub fn as_date(&self) -> Option<&NaiveDate> {
199        match self {
200            Value::Date(d) => Some(d),
201            _ => None,
202        }
203    }
204
205    pub fn is_datetime(&self) -> bool {
206        self.as_datetime().is_some()
207    }
208
209    pub fn as_datetime(&self) -> Option<&DateTime<Utc>> {
210        match self {
211            Value::DateTime(d) => Some(d),
212            _ => None,
213        }
214    }
215
216    pub fn is_array(&self) -> bool {
217        self.as_array().is_some()
218    }
219
220    pub fn as_array(&self) -> Option<&Vec<Value>> {
221        match self {
222            Value::Array(vec) => Some(vec),
223            _ => None,
224        }
225    }
226
227    pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
228        match self {
229            Value::Array(vec) => Some(vec),
230            _ => None,
231        }
232    }
233
234    pub fn into_array(self) -> Option<Vec<Value>> {
235        match self {
236            Value::Array(vec) => Some(vec),
237            _ => None,
238        }
239    }
240
241    pub fn is_dictionary(&self) -> bool {
242        self.as_dictionary().is_some()
243    }
244
245    pub fn as_dictionary(&self) -> Option<&IndexMap<String, Value>> {
246        match self {
247            Value::Dictionary(map) => Some(map),
248            _ => None,
249        }
250    }
251
252    pub fn as_dictionary_mut(&mut self) -> Option<&mut IndexMap<String, Value>> {
253        match self {
254            Value::Dictionary(map) => Some(map),
255            _ => None,
256        }
257    }
258
259    pub fn is_range(&self) -> bool {
260        self.as_range().is_some()
261    }
262
263    pub fn as_range(&self) -> Option<&Range> {
264        match self {
265            Value::Range(r) => Some(r),
266            _ => None,
267        }
268    }
269
270    pub fn is_tuple(&self) -> bool {
271        self.as_range().is_some()
272    }
273
274    pub fn as_tuple(&self) -> Option<&Vec<Value>> {
275        match self {
276            Value::Tuple(t) => Some(t),
277            _ => None,
278        }
279    }
280
281    pub fn is_option_variant(&self) -> bool {
282        self.as_option_variant().is_some()
283    }
284
285    pub fn as_option_variant(&self) -> Option<&OptionVariant> {
286        match self {
287            Value::OptionVariant(e) => Some(e),
288            _ => None,
289        }
290    }
291
292    pub fn is_interface_enum_variant(&self) -> bool {
293        self.as_interface_enum_variant().is_some()
294    }
295
296    pub fn as_interface_enum_variant(&self) -> Option<&InterfaceEnumVariant> {
297        match self {
298            Value::InterfaceEnumVariant(e) => Some(e),
299            _ => None,
300        }
301    }
302
303    pub fn is_regex(&self) -> bool {
304        self.as_regex().is_some()
305    }
306
307    pub fn as_regex(&self) -> Option<&Regex> {
308        match self {
309            Value::Regex(r) => Some(r),
310            _ => None,
311        }
312    }
313
314    pub fn is_type(&self) -> bool {
315        self.as_type().is_some()
316    }
317
318    pub fn as_type(&self) -> Option<&Type> {
319        match self {
320            Value::Type(t) => Some(t),
321            _ => None,
322        }
323    }
324
325    // Compound queries
326
327    pub fn is_any_int(&self) -> bool {
328        match *self {
329            Value::Int(_) | Value::Int64(_) => true,
330            _ => false,
331        }
332    }
333
334    pub fn is_any_float(&self) -> bool {
335        match *self {
336            Value::Float32(_) | Value::Float(_) => true,
337            _ => false,
338        }
339    }
340
341    pub fn is_any_int_or_float(&self) -> bool {
342        self.is_any_int() || self.is_any_float()
343    }
344
345    pub fn is_any_number(&self) -> bool {
346        self.is_any_int() || self.is_any_float() || self.is_decimal()
347    }
348
349    pub fn to_usize(&self) -> Option<usize> {
350        match *self {
351            Value::Int(n) => Some(n as usize),
352            Value::Int64(n) => Some(n as usize),
353            _ => None
354        }
355    }
356
357    pub fn into_vec<T>(self) -> teo_result::Result<Vec<T>> where T: TryFrom<Value>, T::Error: Display {
358        match self {
359            Value::Array(array) => {
360                let mut retval = vec![];
361                for v in array {
362                    match T::try_from(v) {
363                        Ok(v) => retval.push(v),
364                        Err(e) => Err(Error::new(format!("{}", e)))?,
365                    }
366                }
367                Ok(retval)
368            },
369            _ => match T::try_from(self) {
370                Ok(v) => Ok(vec![v]),
371                Err(e) => Err(Error::new(format!("{}", e))),
372            }
373        }
374    }
375
376    /// Takes the value out of the `Value`, leaving a `Null` in its place.
377    ///
378    pub fn take(&mut self) -> Value {
379        mem::replace(self, Value::Null)
380    }
381
382    pub fn recip(&self) -> teo_result::Result<Value> {
383        Ok(match self {
384            Value::Int(n) => Value::Float((*n as f64).recip()),
385            Value::Int64(n) => Value::Float((*n as f64).recip()),
386            Value::Float32(n) => Value::Float32((*n).recip()),
387            Value::Float(n) => Value::Float((*n).recip()),
388            Value::Decimal(n) => Value::Decimal(BigDecimal::from_str("1").unwrap() / n),
389            _ => Err(Error::new("recip: value is not number"))?
390        })
391    }
392
393    pub fn normal_not(&self) -> Value {
394        Value::Bool(match self {
395            Value::Null => true,
396            Value::Bool(b) => !b,
397            Value::Int(i) => i.is_zero(),
398            Value::Int64(i) => i.is_zero(),
399            Value::Float32(f) => f.is_zero(),
400            Value::Float(f) => f.is_zero(),
401            Value::Decimal(d) => d.is_zero(),
402            Value::ObjectId(_) => false,
403            Value::String(s) => s.is_empty(),
404            Value::Date(_) => false,
405            Value::DateTime(_) => false,
406            Value::Array(a) => a.is_empty(),
407            Value::Dictionary(d) => d.is_empty(),
408            Value::Range(_) => false,
409            Value::Tuple(_) => false,
410            Value::OptionVariant(o) => o.normal_not(),
411            Value::Regex(_) => false,
412            Value::InterfaceEnumVariant(_) => false,
413            Value::Type(_) => false,
414        })
415    }
416
417    pub fn and<'a>(&'a self, rhs: &'a Value) -> &'a Value {
418        if self.normal_not().is_false() {
419            rhs
420        } else {
421            self
422        }
423    }
424
425    pub fn or<'a>(&'a self, rhs: &'a Value) -> &'a Value {
426        if self.normal_not().is_false() {
427            self
428        } else {
429            rhs
430        }
431    }
432
433    pub fn is_false(&self) -> bool {
434        self.is_bool() && self.as_bool().unwrap() == false
435    }
436
437    pub fn is_true(&self) -> bool {
438        self.is_bool() && self.as_bool().unwrap() == true
439    }
440}
441
442impl Default for Value {
443    fn default() -> Value {
444        Value::Null
445    }
446}
447
448fn check_enum_operands(name: &str, lhs: &Value, rhs: &Value) -> teo_result::Result<()> {
449    if let (Some(_), Some(_)) = (lhs.as_option_variant(), rhs.as_option_variant()) {
450        Ok(())
451    } else {
452        Err(operands_error_message(lhs, rhs, name))
453    }
454}
455
456fn operand_error_message(operand: &Value, name: &str) -> Error {
457    Error::new(format!("cannot {name} {}", operand))
458}
459
460fn check_operands<F>(lhs: &Value, rhs: &Value, name: &str, matcher: F) -> teo_result::Result<()> where F: Fn(&Value) -> bool {
461    let matcher_wrapper = |value: &Value| {
462        (&matcher)(value)
463    };
464    if !matcher_wrapper(lhs) || !matcher_wrapper(rhs) {
465        return Err(operands_error_message(lhs, rhs, name));
466    }
467    Ok(())
468}
469
470fn operands_error_message(lhs: &Value, rhs: &Value, name: &str) -> Error {
471    Error::new(format!("cannot {name} {:?} with {:?}", lhs, rhs))
472}
473
474impl Add for &Value {
475
476    type Output = teo_result::Result<Value>;
477
478    fn add(self, rhs: Self) -> Self::Output {
479        Ok(match self {
480            Value::Int(v) => {
481                check_operands(&self, &rhs, "add", |v| v.is_any_int())?;
482                Value::Int(v + rhs.to_int().unwrap())
483            },
484            Value::Int64(v) => {
485                check_operands(&self, &rhs, "add", |v| v.is_any_int())?;
486                Value::Int64(v + rhs.to_int64().unwrap())
487            },
488            Value::Float32(v) => {
489                check_operands(&self, &rhs, "add", |v| v.is_any_int_or_float())?;
490                Value::Float32(v + rhs.to_float32().unwrap())
491            },
492            Value::Float(v) => {
493                check_operands(&self, &rhs, "add", |v| v.is_any_int_or_float())?;
494                Value::Float(v + rhs.to_float().unwrap())
495            },
496            Value::Decimal(d) => {
497                check_operands(&self, &rhs, "add", |v| v.is_decimal())?;
498                Value::Decimal(d + rhs.as_decimal().unwrap())
499            },
500            Value::String(s) => {
501                check_operands(&self, &rhs, "add", |v| v.is_string())?;
502                Value::String(s.to_owned() + rhs.as_str().unwrap())
503            }
504            _ => Err(operands_error_message(self, rhs, "add"))?,
505        })
506    }
507}
508
509impl Sub for &Value {
510
511    type Output = teo_result::Result<Value>;
512
513    fn sub(self, rhs: Self) -> Self::Output {
514        Ok(match self {
515            Value::Int(v) => {
516                check_operands(&self, &rhs, "sub", |v| v.is_any_int())?;
517                Value::Int(v - rhs.to_int().unwrap())
518            },
519            Value::Int64(v) => {
520                check_operands(&self, &rhs, "sub", |v| v.is_any_int())?;
521                Value::Int64(v - rhs.to_int64().unwrap())
522            },
523            Value::Float32(v) => {
524                check_operands(&self, &rhs, "sub", |v| v.is_any_int_or_float())?;
525                Value::Float32(v - rhs.to_float32().unwrap())
526            },
527            Value::Float(v) => {
528                check_operands(&self, &rhs, "sub", |v| v.is_any_int_or_float())?;
529                Value::Float(v - rhs.to_float().unwrap())
530            },
531            Value::Decimal(d) => {
532                check_operands(&self, &rhs, "sub", |v| v.is_decimal())?;
533                Value::Decimal(d - rhs.as_decimal().unwrap())
534            },
535            _ => Err(operands_error_message(self, rhs, "sub"))?,
536        })
537    }
538}
539
540impl Mul for &Value {
541
542    type Output = teo_result::Result<Value>;
543
544    fn mul(self, rhs: Self) -> Self::Output {
545        Ok(match self {
546            Value::Int(v) => {
547                check_operands(&self, &rhs, "mul", |v| v.is_any_int())?;
548                Value::Int(v * rhs.to_int().unwrap())
549            },
550            Value::Int64(v) => {
551                check_operands(&self, &rhs, "mul", |v| v.is_any_int())?;
552                Value::Int64(v * rhs.to_int64().unwrap())
553            },
554            Value::Float32(v) => {
555                check_operands(&self, &rhs, "mul", |v| v.is_any_int_or_float())?;
556                Value::Float32(v * rhs.to_float32().unwrap())
557            },
558            Value::Float(v) => {
559                check_operands(&self, &rhs, "mul", |v| v.is_any_int_or_float())?;
560                Value::Float(v * rhs.to_float().unwrap())
561            },
562            Value::Decimal(d) => {
563                check_operands(&self, &rhs, "mul", |v| v.is_decimal())?;
564                Value::Decimal(d * rhs.as_decimal().unwrap())
565            },
566            _ => Err(operands_error_message(self, rhs, "mul"))?,
567        })
568    }
569}
570
571impl Div for &Value {
572
573    type Output = teo_result::Result<Value>;
574
575    fn div(self, rhs: Self) -> Self::Output {
576        Ok(match self {
577            Value::Int(v) => {
578                check_operands(&self, &rhs, "div", |v| v.is_any_int())?;
579                Value::Int(v / rhs.to_int().unwrap())
580            },
581            Value::Int64(v) => {
582                check_operands(&self, &rhs, "div", |v| v.is_any_int())?;
583                Value::Int64(v / rhs.to_int64().unwrap())
584            },
585            Value::Float32(v) => {
586                check_operands(&self, &rhs, "div", |v| v.is_any_int_or_float())?;
587                Value::Float32(v / rhs.to_float32().unwrap())
588            },
589            Value::Float(v) => {
590                check_operands(&self, &rhs, "div", |v| v.is_any_int_or_float())?;
591                Value::Float(v / rhs.to_float().unwrap())
592            },
593            Value::Decimal(d) => {
594                check_operands(&self, &rhs, "div", |v| v.is_decimal())?;
595                Value::Decimal(d / rhs.as_decimal().unwrap())
596            },
597            _ => Err(operands_error_message(self, rhs, "div"))?,
598        })
599    }
600}
601
602impl Rem for &Value {
603
604    type Output = teo_result::Result<Value>;
605
606    fn rem(self, rhs: Self) -> Self::Output {
607        Ok(match self {
608            Value::Int(v) => {
609                check_operands(&self, &rhs, "rem", |v| v.is_any_int())?;
610                Value::Int(v % rhs.to_int().unwrap())
611            },
612            Value::Int64(v) => {
613                check_operands(&self, &rhs, "rem", |v| v.is_any_int())?;
614                Value::Int64(v % rhs.to_int64().unwrap())
615            },
616            Value::Float32(v) => {
617                check_operands(&self, &rhs, "rem", |v| v.is_any_int_or_float())?;
618                Value::Float32(v % rhs.to_float32().unwrap())
619            },
620            Value::Float(v) => {
621                check_operands(&self, &rhs, "rem", |v| v.is_any_int_or_float())?;
622                Value::Float(v % rhs.to_float().unwrap())
623            },
624            Value::Decimal(d) => {
625                check_operands(&self, &rhs, "rem", |v| v.is_decimal())?;
626                Value::Decimal(d % rhs.as_decimal().unwrap())
627            },
628            _ => Err(operands_error_message(self, rhs, "rem"))?,
629        })
630    }
631}
632
633impl Neg for &Value {
634
635    type Output = teo_result::Result<Value>;
636
637    fn neg(self) -> Self::Output {
638        Ok(match self {
639            Value::Int(val) => Value::Int(-*val),
640            Value::Int64(val) => Value::Int64(-*val),
641            Value::Float32(val) => Value::Float32(-*val),
642            Value::Float(val) => Value::Float(-*val),
643            Value::Decimal(val) => Value::Decimal(val.neg()),
644            _ => Err(operand_error_message(self, "neg"))?,
645        })
646    }
647}
648
649impl Shl for &Value {
650
651    type Output = teo_result::Result<Value>;
652
653    fn shl(self, rhs: Self) -> Self::Output {
654        Ok(match self {
655            Value::Int(v) => {
656                check_operands(&self, rhs, "shift left", |v| v.is_any_int())?;
657                Value::Int(v << rhs.as_int().unwrap())
658            },
659            Value::Int64(v) => {
660                check_operands(&self, rhs, "shift left", |v| v.is_any_int())?;
661                Value::Int64(v << rhs.as_int64().unwrap())
662            },
663            _ => Err(operand_error_message(self, "shift left"))?,
664        })
665    }
666}
667
668impl Shr for &Value {
669
670    type Output = teo_result::Result<Value>;
671
672    fn shr(self, rhs: Self) -> Self::Output {
673        Ok(match self {
674            Value::Int(v) => {
675                check_operands(&self, rhs, "shift right", |v| v.is_any_int())?;
676                Value::Int(v >> rhs.as_int().unwrap())
677            },
678            Value::Int64(v) => {
679                check_operands(&self, rhs, "shift right", |v| v.is_any_int())?;
680                Value::Int64(v >> rhs.as_int64().unwrap())
681            },
682            _ => Err(operand_error_message(self, "shift right"))?,
683        })
684    }
685}
686
687impl BitAnd for &Value {
688
689    type Output = teo_result::Result<Value>;
690
691    fn bitand(self, rhs: Self) -> Self::Output {
692        Ok(match self {
693            Value::Int(v) => {
694                check_operands(&self, rhs, "bitand", |v| v.is_any_int())?;
695                Value::Int(v & rhs.as_int().unwrap())
696            },
697            Value::Int64(v) => {
698                check_operands(&self, rhs, "bitand", |v| v.is_any_int())?;
699                Value::Int64(v & rhs.as_int64().unwrap())
700            },
701            Value::OptionVariant(e) => {
702                check_enum_operands("bitand", self, rhs)?;
703                Value::OptionVariant((e & rhs.as_option_variant().unwrap())?)
704            }
705            _ => Err(operand_error_message(self, "bitand"))?,
706        })
707    }
708}
709
710impl BitXor for &Value {
711
712    type Output = teo_result::Result<Value>;
713
714    fn bitxor(self, rhs: Self) -> Self::Output {
715        Ok(match self {
716            Value::Int(v) => {
717                check_operands(&self, rhs, "bitxor", |v| v.is_any_int())?;
718                Value::Int(v ^ rhs.as_int().unwrap())
719            },
720            Value::Int64(v) => {
721                check_operands(&self, rhs, "bitxor", |v| v.is_any_int())?;
722                Value::Int64(v ^ rhs.as_int64().unwrap())
723            },
724            Value::OptionVariant(e) => {
725                check_enum_operands("bitxor", self, rhs)?;
726                Value::OptionVariant((e ^ rhs.as_option_variant().unwrap())?)
727            }
728            _ => Err(operand_error_message(self, "bitxor"))?,
729        })
730    }
731}
732
733impl BitOr for &Value {
734
735    type Output = teo_result::Result<Value>;
736
737    fn bitor(self, rhs: Self) -> Self::Output {
738        Ok(match self {
739            Value::Int(v) => {
740                check_operands(&self, rhs, "bitor", |v| v.is_any_int())?;
741                Value::Int(v | rhs.as_int().unwrap())
742            },
743            Value::Int64(v) => {
744                check_operands(&self, rhs, "bitor", |v| v.is_any_int())?;
745                Value::Int64(v | rhs.as_int64().unwrap())
746            },
747            Value::OptionVariant(e) => {
748                check_enum_operands("bitor", self, rhs)?;
749                Value::OptionVariant((e | rhs.as_option_variant().unwrap())?)
750            }
751            _ => Err(operand_error_message(self, "bitor"))?,
752        })
753    }
754}
755
756// This is bit neg
757impl Not for &Value {
758
759    type Output = teo_result::Result<Value>;
760
761    fn not(self) -> Self::Output {
762        Ok(match self {
763            Value::Int(val) => Value::Int(-*val),
764            Value::Int64(val) => Value::Int64(-*val),
765            Value::Float32(val) => Value::Float32(-*val),
766            Value::Float(val) => Value::Float(-*val),
767            Value::Decimal(val) => Value::Decimal(val.neg()),
768            Value::OptionVariant(e) => Value::OptionVariant(e.not()),
769            _ => Err(operand_error_message(self, "bitneg"))?,
770        })
771    }
772}
773
774impl PartialEq for Value {
775
776    fn eq(&self, other: &Self) -> bool {
777        use Value::*;
778        if self.is_any_int() && other.is_any_int() {
779            return self.to_int64().unwrap() == other.to_int64().unwrap();
780        }
781        if self.is_any_int_or_float() && other.is_any_int_or_float() {
782            return self.to_float().unwrap() == other.to_float().unwrap();
783        }
784        match (self, other) {
785            (Null, Null) => true,
786            (Bool(s), Bool(o)) => s == o,
787            (Decimal(s), Decimal(o)) => s == o,
788            (ObjectId(s), ObjectId(o)) => s == o,
789            (String(s), String(o)) => s == o,
790            (Date(s), Date(o)) => s == o,
791            (DateTime(s), DateTime(o)) => s == o,
792            (Array(s), Array(o)) => s == o,
793            (Dictionary(s), Dictionary(o)) => s == o,
794            (Range(s), Range(o)) => s == o,
795            (Tuple(s), Tuple(o)) => s == o,
796            (OptionVariant(s), OptionVariant(o)) => s.value == o.value,
797            (InterfaceEnumVariant(s), InterfaceEnumVariant(o)) => s == o,
798            (Regex(s), Regex(o)) => s.as_str() == o.as_str(),
799            _ => false,
800        }
801    }
802}
803
804impl PartialOrd for Value {
805
806    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
807        use Value::*;
808        if self.is_any_int() && other.is_any_int() {
809            return self.to_int64().unwrap().partial_cmp(&other.to_int64().unwrap());
810        }
811        if self.is_any_int_or_float() && other.is_any_int_or_float() {
812            return self.to_float().unwrap().partial_cmp(&other.to_float().unwrap());
813        }
814        match (self, other) {
815            (Null, Null) => Some(Ordering::Equal),
816            (Bool(s), Bool(o)) => s.partial_cmp(o),
817            (Decimal(s), Decimal(o)) => s.partial_cmp(o),
818            (ObjectId(s), ObjectId(o)) => s.partial_cmp(o),
819            (String(s), String(o)) => s.partial_cmp(o),
820            (Date(s), Date(o)) => s.partial_cmp(o),
821            (DateTime(s), DateTime(o)) => s.partial_cmp(o),
822            (Array(s), Array(o)) => s.partial_cmp(o),
823            (Tuple(s), Tuple(o)) => s.partial_cmp(o),
824            (OptionVariant(s), OptionVariant(o)) => s.value.partial_cmp(&o.value),
825            (InterfaceEnumVariant(s), InterfaceEnumVariant(o)) => s.value.partial_cmp(&o.value),
826            _ => None,
827        }
828    }
829}
830
831impl AsRef<Value> for Value {
832
833    fn as_ref(&self) -> &Value {
834        &self
835    }
836}
837
838impl Display for Value {
839
840    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
841        match self {
842            Value::Null => f.write_str("null"),
843            Value::Bool(b) => Display::fmt(b, f),
844            Value::Int(i) => Display::fmt(i, f),
845            Value::Int64(i) => Display::fmt(i, f),
846            Value::Float32(n) => Display::fmt(n, f),
847            Value::Float(n) => Display::fmt(n, f),
848            Value::Decimal(d) => {
849                f.write_str("Decimal(\"")?;
850                Display::fmt(d, f)?;
851                f.write_str("\"")
852            },
853            Value::ObjectId(o) => {
854                f.write_str("ObjectId(\"")?;
855                Display::fmt(o, f)?;
856                f.write_str("\"")
857            },
858            Value::String(s) => {
859                f.write_str(&format!("\"{}\"", s.replace("\"", "\\\"")))
860            }
861            Value::Date(d) => f.write_str(&format!("Date(\"{}\")", d.to_string())),
862            Value::DateTime(d) => f.write_str(&format!("DateTime(\"{}\")", d.to_rfc3339_opts(SecondsFormat::Millis, true))),
863            Value::Array(a) => {
864                f.write_str(&("[".to_string() + a.iter().map(|v| format!("{v}")).join(", ").as_str() + "]"))
865            }
866            Value::Dictionary(m) => {
867                f.write_str(&("{".to_string() + m.iter().map(|(k, v)| format!("\"{k}\": {}", format!("{v}"))).join(", ").as_str() + "}"))
868            }
869            Value::Range(r) => Display::fmt(r, f),
870            Value::Tuple(t) => {
871                f.write_str("(")?;
872                for (i, v) in t.iter().enumerate() {
873                    Display::fmt(v, f)?;
874                    if i != t.len() - 1 {
875                        f.write_str(", ")?;
876                    }
877                }
878                if t.len() == 1 {
879                    f.write_str(",")?;
880                }
881                f.write_str(")")
882            }
883            Value::OptionVariant(o) => {
884                f.write_str(&o.display)
885            }
886            Value::Regex(r) => {
887                f.write_str("/")?;
888                f.write_str(&format!("{}", r.as_str().replace("/", "\\/")))?;
889                f.write_str("/")
890            }
891            Value::InterfaceEnumVariant(interface_enum_variant) => Display::fmt(interface_enum_variant, f),
892            Value::Type(t) => Display::fmt(t, f),
893        }
894    }
895}