1mod coercion;
8mod compare;
9mod hash;
10mod rank;
11mod storage_key;
12mod tag;
13mod wire;
14
15#[cfg(test)]
16mod tests;
17
18use crate::{
19 model::field::FieldStorageDecode,
20 prelude::*,
21 traits::{EnumValue, FieldValue, NumFromPrimitive, Repr},
22 types::*,
23};
24use candid::CandidType;
25use serde::{Deserialize, Serialize};
26use std::cmp::Ordering;
27
28pub use coercion::{CoercionFamily, CoercionFamilyExt};
30pub(crate) use hash::hash_value;
31#[cfg(test)]
32pub(crate) use hash::with_test_hash_override;
33pub use storage_key::{StorageKey, StorageKeyDecodeError, StorageKeyEncodeError};
34pub use tag::ValueTag;
35
36const F64_SAFE_I64: i64 = 1i64 << 53;
41const F64_SAFE_U64: u64 = 1u64 << 53;
42const F64_SAFE_I128: i128 = 1i128 << 53;
43const F64_SAFE_U128: u128 = 1u128 << 53;
44
45enum NumericRepr {
50 Decimal(Decimal),
51 F64(f64),
52 None,
53}
54
55#[derive(Clone, Copy, Debug, Eq, PartialEq)]
60pub enum TextMode {
61 Cs, Ci, }
64
65#[derive(Clone, Debug, Eq, PartialEq)]
72pub enum MapValueError {
73 EmptyKey {
74 index: usize,
75 },
76 NonScalarKey {
77 index: usize,
78 key: Value,
79 },
80 NonScalarValue {
81 index: usize,
82 value: Value,
83 },
84 DuplicateKey {
85 left_index: usize,
86 right_index: usize,
87 },
88}
89
90impl std::fmt::Display for MapValueError {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 match self {
93 Self::EmptyKey { index } => write!(f, "map key at index {index} must be non-null"),
94 Self::NonScalarKey { index, key } => {
95 write!(f, "map key at index {index} is not scalar: {key:?}")
96 }
97 Self::NonScalarValue { index, value } => {
98 write!(
99 f,
100 "map value at index {index} is not scalar/ref-like: {value:?}"
101 )
102 }
103 Self::DuplicateKey {
104 left_index,
105 right_index,
106 } => write!(
107 f,
108 "map contains duplicate keys at normalized positions {left_index} and {right_index}"
109 ),
110 }
111 }
112}
113
114impl std::error::Error for MapValueError {}
115
116#[derive(Clone, Debug, Eq, PartialEq)]
123pub enum SchemaInvariantError {
124 InvalidMapValue(MapValueError),
125}
126
127impl std::fmt::Display for SchemaInvariantError {
128 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129 match self {
130 Self::InvalidMapValue(err) => write!(f, "{err}"),
131 }
132 }
133}
134
135impl std::error::Error for SchemaInvariantError {}
136
137impl From<MapValueError> for SchemaInvariantError {
138 fn from(value: MapValueError) -> Self {
139 Self::InvalidMapValue(value)
140 }
141}
142
143#[derive(CandidType, Clone, Debug, Eq, PartialEq, Serialize)]
152pub enum Value {
153 Account(Account),
154 Blob(Vec<u8>),
155 Bool(bool),
156 Date(Date),
157 Decimal(Decimal),
158 Duration(Duration),
159 Enum(ValueEnum),
160 Float32(Float32),
161 Float64(Float64),
162 Int(i64),
163 Int128(Int128),
164 IntBig(Int),
165 List(Vec<Self>),
169 Map(Vec<(Self, Self)>),
176 Null,
177 Principal(Principal),
178 Subaccount(Subaccount),
179 Text(String),
180 Timestamp(Timestamp),
181 Uint(u64),
182 Uint128(Nat128),
183 UintBig(Nat),
184 Ulid(Ulid),
185 Unit,
186}
187
188impl Value {
189 pub const STORAGE_DECODE: FieldStorageDecode = FieldStorageDecode::Value;
190}
191
192macro_rules! value_is_numeric_from_registry {
194 ( @args $value:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
195 match $value {
196 $( $value_pat => $is_numeric, )*
197 _ => false,
198 }
199 };
200}
201
202macro_rules! value_supports_numeric_coercion_from_registry {
203 ( @args $value:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
204 match $value {
205 $( $value_pat => $supports_numeric_coercion, )*
206 _ => false,
207 }
208 };
209}
210
211macro_rules! value_storage_key_case {
212 ( $value:expr, Unit, true ) => {
213 if let Value::Unit = $value {
214 Some(StorageKey::Unit)
215 } else {
216 None
217 }
218 };
219 ( $value:expr, $scalar:ident, true ) => {
220 if let Value::$scalar(v) = $value {
221 Some(StorageKey::$scalar(*v))
222 } else {
223 None
224 }
225 };
226 ( $value:expr, $scalar:ident, false ) => {
227 None
228 };
229}
230
231macro_rules! value_storage_key_from_registry {
232 ( @args $value:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:tt, is_storage_key_encodable = $is_storage_key_encodable:tt) ),* $(,)? ) => {
233 {
234 let mut key = None;
235 $(
236 match key {
237 Some(_) => {}
238 None => {
239 key = value_storage_key_case!($value, $scalar, $is_storage_key_encodable);
240 }
241 }
242 )*
243 key
244 }
245 };
246}
247
248macro_rules! value_coercion_family_from_registry {
249 ( @args $value:expr; @entries $( ($scalar:ident, $coercion_family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
250 match $value {
251 $( $value_pat => $coercion_family, )*
252 Value::List(_) => CoercionFamily::Collection,
253 Value::Map(_) => CoercionFamily::Collection,
254 Value::Null => CoercionFamily::Null,
255 }
256 };
257}
258
259impl Value {
260 pub fn from_slice<T>(items: &[T]) -> Self
269 where
270 T: Into<Self> + Clone,
271 {
272 Self::List(items.iter().cloned().map(Into::into).collect())
273 }
274
275 pub fn from_list<T>(items: Vec<T>) -> Self
279 where
280 T: Into<Self>,
281 {
282 Self::List(items.into_iter().map(Into::into).collect())
283 }
284
285 pub fn from_map(entries: Vec<(Self, Self)>) -> Result<Self, MapValueError> {
293 let normalized = Self::normalize_map_entries(entries)?;
294 Ok(Self::Map(normalized))
295 }
296
297 pub fn validate_map_entries(entries: &[(Self, Self)]) -> Result<(), MapValueError> {
299 for (index, (key, value)) in entries.iter().enumerate() {
300 if matches!(key, Self::Null) {
301 return Err(MapValueError::EmptyKey { index });
302 }
303 if !key.is_scalar() {
304 return Err(MapValueError::NonScalarKey {
305 index,
306 key: key.clone(),
307 });
308 }
309
310 if !value.is_scalar() {
311 return Err(MapValueError::NonScalarValue {
312 index,
313 value: value.clone(),
314 });
315 }
316 }
317
318 Ok(())
319 }
320
321 pub(crate) fn compare_map_entry_keys(left: &(Self, Self), right: &(Self, Self)) -> Ordering {
323 Self::canonical_cmp_key(&left.0, &right.0)
324 }
325
326 pub(crate) fn sort_map_entries_in_place(entries: &mut [(Self, Self)]) {
328 entries.sort_by(Self::compare_map_entry_keys);
329 }
330
331 pub(crate) fn map_entries_are_strictly_canonical(entries: &[(Self, Self)]) -> bool {
334 entries.windows(2).all(|pair| {
335 let [left, right] = pair else {
336 return true;
337 };
338
339 Self::compare_map_entry_keys(left, right) == Ordering::Less
340 })
341 }
342
343 pub fn normalize_map_entries(
345 mut entries: Vec<(Self, Self)>,
346 ) -> Result<Vec<(Self, Self)>, MapValueError> {
347 Self::validate_map_entries(&entries)?;
348 Self::sort_map_entries_in_place(entries.as_mut_slice());
349
350 for i in 1..entries.len() {
351 let (left_key, _) = &entries[i - 1];
352 let (right_key, _) = &entries[i];
353 if Self::canonical_cmp_key(left_key, right_key) == Ordering::Equal {
354 return Err(MapValueError::DuplicateKey {
355 left_index: i - 1,
356 right_index: i,
357 });
358 }
359 }
360
361 Ok(entries)
362 }
363
364 pub fn from_enum<E: EnumValue>(value: E) -> Self {
366 Self::Enum(value.to_value_enum())
367 }
368
369 #[must_use]
371 pub fn enum_strict<E: Path>(variant: &str) -> Self {
372 Self::Enum(ValueEnum::strict::<E>(variant))
373 }
374
375 #[must_use]
382 pub const fn is_numeric(&self) -> bool {
383 scalar_registry!(value_is_numeric_from_registry, self)
384 }
385
386 #[must_use]
388 pub const fn supports_numeric_coercion(&self) -> bool {
389 scalar_registry!(value_supports_numeric_coercion_from_registry, self)
390 }
391
392 #[must_use]
394 pub const fn is_text(&self) -> bool {
395 matches!(self, Self::Text(_))
396 }
397
398 #[must_use]
400 pub const fn is_unit(&self) -> bool {
401 matches!(self, Self::Unit)
402 }
403
404 #[must_use]
405 pub const fn is_scalar(&self) -> bool {
406 match self {
407 Self::List(_) | Self::Map(_) | Self::Unit => false,
409 _ => true,
410 }
411 }
412
413 #[must_use]
415 pub(crate) const fn canonical_tag(&self) -> ValueTag {
416 tag::canonical_tag(self)
417 }
418
419 #[must_use]
421 pub(crate) const fn canonical_rank(&self) -> u8 {
422 rank::canonical_rank(self)
423 }
424
425 #[must_use]
427 pub(crate) fn canonical_cmp(left: &Self, right: &Self) -> Ordering {
428 compare::canonical_cmp(left, right)
429 }
430
431 #[must_use]
433 pub fn canonical_cmp_key(left: &Self, right: &Self) -> Ordering {
434 compare::canonical_cmp_key(left, right)
435 }
436
437 #[must_use]
442 pub(crate) fn canonical_cmp_map_entry(
443 left_key: &Self,
444 left_value: &Self,
445 right_key: &Self,
446 right_value: &Self,
447 ) -> Ordering {
448 Self::canonical_cmp_key(left_key, right_key)
449 .then_with(|| Self::canonical_cmp(left_value, right_value))
450 }
451
452 #[must_use]
456 pub(crate) fn strict_order_cmp(left: &Self, right: &Self) -> Option<Ordering> {
457 compare::strict_order_cmp(left, right)
458 }
459
460 fn numeric_repr(&self) -> NumericRepr {
461 if !self.supports_numeric_coercion() {
463 return NumericRepr::None;
464 }
465
466 if let Some(d) = self.to_decimal() {
467 return NumericRepr::Decimal(d);
468 }
469 if let Some(f) = self.to_f64_lossless() {
470 return NumericRepr::F64(f);
471 }
472 NumericRepr::None
473 }
474
475 #[must_use]
484 pub const fn as_storage_key(&self) -> Option<StorageKey> {
485 scalar_registry!(value_storage_key_from_registry, self)
486 }
487
488 #[must_use]
489 pub const fn as_text(&self) -> Option<&str> {
490 if let Self::Text(s) = self {
491 Some(s.as_str())
492 } else {
493 None
494 }
495 }
496
497 #[must_use]
498 pub const fn as_list(&self) -> Option<&[Self]> {
499 if let Self::List(xs) = self {
500 Some(xs.as_slice())
501 } else {
502 None
503 }
504 }
505
506 #[must_use]
507 pub const fn as_map(&self) -> Option<&[(Self, Self)]> {
508 if let Self::Map(entries) = self {
509 Some(entries.as_slice())
510 } else {
511 None
512 }
513 }
514
515 fn to_decimal(&self) -> Option<Decimal> {
516 match self {
517 Self::Decimal(d) => Some(*d),
518 Self::Duration(d) => Decimal::from_u64(d.repr()),
519 Self::Float64(f) => Decimal::from_f64(f.get()),
520 Self::Float32(f) => Decimal::from_f32(f.get()),
521 Self::Int(i) => Decimal::from_i64(*i),
522 Self::Int128(i) => Decimal::from_i128(i.get()),
523 Self::IntBig(i) => i.to_i128().and_then(Decimal::from_i128),
524 Self::Timestamp(t) => Decimal::from_i64(t.repr()),
525 Self::Uint(u) => Decimal::from_u64(*u),
526 Self::Uint128(u) => Decimal::from_u128(u.get()),
527 Self::UintBig(u) => u.to_u128().and_then(Decimal::from_u128),
528
529 _ => None,
530 }
531 }
532
533 pub(crate) fn to_numeric_decimal(&self) -> Option<Decimal> {
535 self.to_decimal()
536 }
537
538 #[expect(clippy::cast_precision_loss)]
540 fn to_f64_lossless(&self) -> Option<f64> {
541 match self {
542 Self::Duration(d) if d.repr() <= F64_SAFE_U64 => Some(d.repr() as f64),
543 Self::Float64(f) => Some(f.get()),
544 Self::Float32(f) => Some(f64::from(f.get())),
545 Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
546 Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
547 Some(i.get() as f64)
548 }
549 Self::IntBig(i) => i.to_i128().and_then(|v| {
550 (-F64_SAFE_I128..=F64_SAFE_I128)
551 .contains(&v)
552 .then_some(v as f64)
553 }),
554 Self::Timestamp(t) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(&t.repr()) => {
555 Some(t.repr() as f64)
556 }
557 Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
558 Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
559 Self::UintBig(u) => u
560 .to_u128()
561 .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
562
563 _ => None,
564 }
565 }
566
567 #[must_use]
569 pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
570 if !self.supports_numeric_coercion() || !other.supports_numeric_coercion() {
571 return None;
572 }
573
574 match (self.numeric_repr(), other.numeric_repr()) {
575 (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
576 (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
577 _ => None,
578 }
579 }
580
581 fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
586 if s.is_ascii() {
587 return std::borrow::Cow::Owned(s.to_ascii_lowercase());
588 }
589 std::borrow::Cow::Owned(s.to_lowercase())
592 }
593
594 fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
595 match mode {
596 TextMode::Cs => std::borrow::Cow::Borrowed(s),
597 TextMode::Ci => Self::fold_ci(s),
598 }
599 }
600
601 fn text_op(
602 &self,
603 other: &Self,
604 mode: TextMode,
605 f: impl Fn(&str, &str) -> bool,
606 ) -> Option<bool> {
607 let (a, b) = (self.as_text()?, other.as_text()?);
608 let a = Self::text_with_mode(a, mode);
609 let b = Self::text_with_mode(b, mode);
610 Some(f(&a, &b))
611 }
612
613 fn ci_key(&self) -> Option<String> {
614 match self {
615 Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
616 Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
617 Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
618 Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
619 _ => None,
620 }
621 }
622
623 fn eq_ci(a: &Self, b: &Self) -> bool {
624 if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
625 return ak == bk;
626 }
627
628 a == b
629 }
630
631 fn normalize_list_ref(v: &Self) -> Vec<&Self> {
632 match v {
633 Self::List(vs) => vs.iter().collect(),
634 v => vec![v],
635 }
636 }
637
638 fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
639 where
640 F: Fn(&Self, &Self) -> bool,
641 {
642 self.as_list()
643 .map(|items| items.iter().any(|v| eq(v, needle)))
644 }
645
646 #[expect(clippy::unnecessary_wraps)]
647 fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
648 where
649 F: Fn(&Self, &Self) -> bool,
650 {
651 let needles = Self::normalize_list_ref(needles);
652 match self {
653 Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
654 scalar => Some(needles.iter().any(|n| eq(scalar, n))),
655 }
656 }
657
658 #[expect(clippy::unnecessary_wraps)]
659 fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
660 where
661 F: Fn(&Self, &Self) -> bool,
662 {
663 let needles = Self::normalize_list_ref(needles);
664 match self {
665 Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
666 scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
667 }
668 }
669
670 fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
671 where
672 F: Fn(&Self, &Self) -> bool,
673 {
674 if let Self::List(items) = haystack {
675 Some(items.iter().any(|h| eq(h, self)))
676 } else {
677 None
678 }
679 }
680
681 #[must_use]
683 pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
684 self.text_op(other, mode, |a, b| a == b)
685 }
686
687 #[must_use]
689 pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
690 self.text_op(needle, mode, |a, b| a.contains(b))
691 }
692
693 #[must_use]
695 pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
696 self.text_op(needle, mode, |a, b| a.starts_with(b))
697 }
698
699 #[must_use]
701 pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
702 self.text_op(needle, mode, |a, b| a.ends_with(b))
703 }
704
705 #[must_use]
710 pub const fn is_empty(&self) -> Option<bool> {
711 match self {
712 Self::List(xs) => Some(xs.is_empty()),
713 Self::Map(entries) => Some(entries.is_empty()),
714 Self::Text(s) => Some(s.is_empty()),
715 Self::Blob(b) => Some(b.is_empty()),
716
717 Self::Null => Some(true),
719
720 _ => None,
721 }
722 }
723
724 #[must_use]
726 pub fn is_not_empty(&self) -> Option<bool> {
727 self.is_empty().map(|b| !b)
728 }
729
730 #[must_use]
736 pub fn contains(&self, needle: &Self) -> Option<bool> {
737 self.contains_by(needle, |a, b| a == b)
738 }
739
740 #[must_use]
742 pub fn contains_any(&self, needles: &Self) -> Option<bool> {
743 self.contains_any_by(needles, |a, b| a == b)
744 }
745
746 #[must_use]
748 pub fn contains_all(&self, needles: &Self) -> Option<bool> {
749 self.contains_all_by(needles, |a, b| a == b)
750 }
751
752 #[must_use]
754 pub fn in_list(&self, haystack: &Self) -> Option<bool> {
755 self.in_list_by(haystack, |a, b| a == b)
756 }
757
758 #[must_use]
760 pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
761 match self {
762 Self::List(_) => self.contains_by(needle, Self::eq_ci),
763 _ => Some(Self::eq_ci(self, needle)),
764 }
765 }
766
767 #[must_use]
769 pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
770 self.contains_any_by(needles, Self::eq_ci)
771 }
772
773 #[must_use]
775 pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
776 self.contains_all_by(needles, Self::eq_ci)
777 }
778
779 #[must_use]
781 pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
782 self.in_list_by(haystack, Self::eq_ci)
783 }
784}
785
786impl FieldValue for Value {
787 fn kind() -> crate::traits::FieldValueKind {
788 crate::traits::FieldValueKind::Atomic
789 }
790
791 fn to_value(&self) -> Value {
792 self.clone()
793 }
794
795 fn from_value(value: &Value) -> Option<Self> {
796 Some(value.clone())
797 }
798}
799
800#[macro_export]
801macro_rules! impl_from_for {
802 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
803 $(
804 impl From<$type> for Value {
805 fn from(v: $type) -> Self {
806 Self::$variant(v.into())
807 }
808 }
809 )*
810 };
811}
812
813impl_from_for! {
814 Account => Account,
815 Date => Date,
816 Decimal => Decimal,
817 Duration => Duration,
818 bool => Bool,
819 i8 => Int,
820 i16 => Int,
821 i32 => Int,
822 i64 => Int,
823 i128 => Int128,
824 Int => IntBig,
825 Principal => Principal,
826 Subaccount => Subaccount,
827 &str => Text,
828 String => Text,
829 Timestamp => Timestamp,
830 u8 => Uint,
831 u16 => Uint,
832 u32 => Uint,
833 u64 => Uint,
834 u128 => Uint128,
835 Nat => UintBig,
836 Ulid => Ulid,
837}
838
839impl CoercionFamilyExt for Value {
840 fn coercion_family(&self) -> CoercionFamily {
846 scalar_registry!(value_coercion_family_from_registry, self)
847 }
848}
849
850impl From<Vec<Self>> for Value {
851 fn from(vec: Vec<Self>) -> Self {
852 Self::List(vec)
853 }
854}
855
856impl TryFrom<Vec<(Self, Self)>> for Value {
857 type Error = SchemaInvariantError;
858
859 fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
860 Self::from_map(entries).map_err(Self::Error::from)
861 }
862}
863
864impl From<()> for Value {
865 fn from((): ()) -> Self {
866 Self::Unit
867 }
868}
869
870impl PartialOrd for Value {
876 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
877 match (self, other) {
878 (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
879 (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
880 (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
881 (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
882 (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
883 (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
884 (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
885 (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
886 (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
887 (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
888 (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
889 (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
890 (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
891 (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
892 (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
893 (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
894 (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
895 (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
896 (Self::Map(a), Self::Map(b)) => {
897 for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
898 let key_cmp = Self::canonical_cmp_key(left_key, right_key);
899 if key_cmp != Ordering::Equal {
900 return Some(key_cmp);
901 }
902
903 match left_value.partial_cmp(right_value) {
904 Some(Ordering::Equal) => {}
905 non_eq => return non_eq,
906 }
907 }
908 a.len().partial_cmp(&b.len())
909 }
910
911 _ => None,
913 }
914 }
915}
916
917#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
923pub struct ValueEnum {
924 variant: String,
925 path: Option<String>,
926 payload: Option<Box<Value>>,
927}
928
929impl ValueEnum {
930 #[must_use]
932 pub fn new(variant: &str, path: Option<&str>) -> Self {
933 Self {
934 variant: variant.to_string(),
935 path: path.map(ToString::to_string),
936 payload: None,
937 }
938 }
939
940 #[must_use]
942 pub fn strict<E: Path>(variant: &str) -> Self {
943 Self::new(variant, Some(E::PATH))
944 }
945
946 #[must_use]
948 pub fn from_enum<E: EnumValue>(value: E) -> Self {
949 value.to_value_enum()
950 }
951
952 #[must_use]
955 pub fn loose(variant: &str) -> Self {
956 Self::new(variant, None)
957 }
958
959 #[must_use]
961 pub fn with_payload(mut self, payload: Value) -> Self {
962 self.payload = Some(Box::new(payload));
963 self
964 }
965
966 #[must_use]
967 pub fn variant(&self) -> &str {
968 &self.variant
969 }
970
971 #[must_use]
972 pub fn path(&self) -> Option<&str> {
973 self.path.as_deref()
974 }
975
976 #[must_use]
977 pub fn payload(&self) -> Option<&Value> {
978 self.payload.as_deref()
979 }
980
981 pub(crate) fn set_path(&mut self, path: Option<String>) {
982 self.path = path;
983 }
984}