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