1mod coercion;
2mod compare;
3mod hash;
4mod rank;
5mod tag;
6mod wire;
7
8#[cfg(test)]
9mod tests;
10
11use crate::{
12 db::StorageKey,
13 prelude::*,
14 traits::{EnumValue, FieldValue, NumFromPrimitive},
15 types::*,
16};
17use candid::CandidType;
18use serde::{Deserialize, Serialize};
19use std::cmp::Ordering;
20
21pub use coercion::{CoercionFamily, CoercionFamilyExt};
23pub(crate) use hash::hash_value;
24#[cfg(test)]
25pub(crate) use hash::with_test_hash_override;
26pub use tag::ValueTag;
27
28const F64_SAFE_I64: i64 = 1i64 << 53;
33const F64_SAFE_U64: u64 = 1u64 << 53;
34const F64_SAFE_I128: i128 = 1i128 << 53;
35const F64_SAFE_U128: u128 = 1u128 << 53;
36
37enum NumericRepr {
42 Decimal(Decimal),
43 F64(f64),
44 None,
45}
46
47#[derive(Clone, Copy, Debug, Eq, PartialEq)]
52pub enum TextMode {
53 Cs, Ci, }
56
57#[derive(Clone, Debug, Eq, PartialEq)]
64pub enum MapValueError {
65 EmptyKey {
66 index: usize,
67 },
68 NonScalarKey {
69 index: usize,
70 key: Value,
71 },
72 NonScalarValue {
73 index: usize,
74 value: Value,
75 },
76 DuplicateKey {
77 left_index: usize,
78 right_index: usize,
79 },
80}
81
82impl std::fmt::Display for MapValueError {
83 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84 match self {
85 Self::EmptyKey { index } => write!(f, "map key at index {index} must be non-null"),
86 Self::NonScalarKey { index, key } => {
87 write!(f, "map key at index {index} is not scalar: {key:?}")
88 }
89 Self::NonScalarValue { index, value } => {
90 write!(
91 f,
92 "map value at index {index} is not scalar/ref-like: {value:?}"
93 )
94 }
95 Self::DuplicateKey {
96 left_index,
97 right_index,
98 } => write!(
99 f,
100 "map contains duplicate keys at normalized positions {left_index} and {right_index}"
101 ),
102 }
103 }
104}
105
106impl std::error::Error for MapValueError {}
107
108#[derive(Clone, Debug, Eq, PartialEq)]
115pub enum SchemaInvariantError {
116 InvalidMapValue(MapValueError),
117}
118
119impl std::fmt::Display for SchemaInvariantError {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 match self {
122 Self::InvalidMapValue(err) => write!(f, "{err}"),
123 }
124 }
125}
126
127impl std::error::Error for SchemaInvariantError {}
128
129impl From<MapValueError> for SchemaInvariantError {
130 fn from(value: MapValueError) -> Self {
131 Self::InvalidMapValue(value)
132 }
133}
134
135#[derive(CandidType, Clone, Debug, Eq, PartialEq, Serialize)]
144pub enum Value {
145 Account(Account),
146 Blob(Vec<u8>),
147 Bool(bool),
148 Date(Date),
149 Decimal(Decimal),
150 Duration(Duration),
151 Enum(ValueEnum),
152 Float32(Float32),
153 Float64(Float64),
154 Int(i64),
155 Int128(Int128),
156 IntBig(Int),
157 List(Vec<Self>),
161 Map(Vec<(Self, Self)>),
168 Null,
169 Principal(Principal),
170 Subaccount(Subaccount),
171 Text(String),
172 Timestamp(Timestamp),
173 Uint(u64),
174 Uint128(Nat128),
175 UintBig(Nat),
176 Ulid(Ulid),
177 Unit,
178}
179
180macro_rules! value_is_numeric_from_registry {
182 ( @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) ),* $(,)? ) => {
183 match $value {
184 $( $value_pat => $is_numeric, )*
185 _ => false,
186 }
187 };
188}
189
190macro_rules! value_supports_numeric_coercion_from_registry {
191 ( @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) ),* $(,)? ) => {
192 match $value {
193 $( $value_pat => $supports_numeric_coercion, )*
194 _ => false,
195 }
196 };
197}
198
199macro_rules! value_storage_key_case {
200 ( $value:expr, Unit, true ) => {
201 if let Value::Unit = $value {
202 Some(StorageKey::Unit)
203 } else {
204 None
205 }
206 };
207 ( $value:expr, $scalar:ident, true ) => {
208 if let Value::$scalar(v) = $value {
209 Some(StorageKey::$scalar(*v))
210 } else {
211 None
212 }
213 };
214 ( $value:expr, $scalar:ident, false ) => {
215 None
216 };
217}
218
219macro_rules! value_storage_key_from_registry {
220 ( @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) ),* $(,)? ) => {
221 {
222 let mut key = None;
223 $(
224 match key {
225 Some(_) => {}
226 None => {
227 key = value_storage_key_case!($value, $scalar, $is_storage_key_encodable);
228 }
229 }
230 )*
231 key
232 }
233 };
234}
235
236macro_rules! value_coercion_family_from_registry {
237 ( @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) ),* $(,)? ) => {
238 match $value {
239 $( $value_pat => $coercion_family, )*
240 Value::List(_) => CoercionFamily::Collection,
241 Value::Map(_) => CoercionFamily::Collection,
242 Value::Null => CoercionFamily::Null,
243 }
244 };
245}
246
247impl Value {
248 pub fn from_slice<T>(items: &[T]) -> Self
257 where
258 T: Into<Self> + Clone,
259 {
260 Self::List(items.iter().cloned().map(Into::into).collect())
261 }
262
263 pub fn from_list<T>(items: Vec<T>) -> Self
267 where
268 T: Into<Self>,
269 {
270 Self::List(items.into_iter().map(Into::into).collect())
271 }
272
273 pub fn from_map(entries: Vec<(Self, Self)>) -> Result<Self, MapValueError> {
281 let normalized = Self::normalize_map_entries(entries)?;
282 Ok(Self::Map(normalized))
283 }
284
285 pub fn validate_map_entries(entries: &[(Self, Self)]) -> Result<(), MapValueError> {
287 for (index, (key, value)) in entries.iter().enumerate() {
288 if matches!(key, Self::Null) {
289 return Err(MapValueError::EmptyKey { index });
290 }
291 if !key.is_scalar() {
292 return Err(MapValueError::NonScalarKey {
293 index,
294 key: key.clone(),
295 });
296 }
297
298 if !value.is_scalar() {
299 return Err(MapValueError::NonScalarValue {
300 index,
301 value: value.clone(),
302 });
303 }
304 }
305
306 Ok(())
307 }
308
309 pub fn normalize_map_entries(
311 mut entries: Vec<(Self, Self)>,
312 ) -> Result<Vec<(Self, Self)>, MapValueError> {
313 Self::validate_map_entries(&entries)?;
314 entries
315 .sort_by(|(left_key, _), (right_key, _)| Self::canonical_cmp_key(left_key, right_key));
316
317 for i in 1..entries.len() {
318 let (left_key, _) = &entries[i - 1];
319 let (right_key, _) = &entries[i];
320 if Self::canonical_cmp_key(left_key, right_key) == Ordering::Equal {
321 return Err(MapValueError::DuplicateKey {
322 left_index: i - 1,
323 right_index: i,
324 });
325 }
326 }
327
328 Ok(entries)
329 }
330
331 pub fn from_enum<E: EnumValue>(value: E) -> Self {
333 Self::Enum(value.to_value_enum())
334 }
335
336 #[must_use]
338 pub fn enum_strict<E: Path>(variant: &str) -> Self {
339 Self::Enum(ValueEnum::strict::<E>(variant))
340 }
341
342 #[must_use]
349 pub const fn is_numeric(&self) -> bool {
350 scalar_registry!(value_is_numeric_from_registry, self)
351 }
352
353 #[must_use]
355 pub const fn supports_numeric_coercion(&self) -> bool {
356 scalar_registry!(value_supports_numeric_coercion_from_registry, self)
357 }
358
359 #[must_use]
361 pub const fn is_text(&self) -> bool {
362 matches!(self, Self::Text(_))
363 }
364
365 #[must_use]
367 pub const fn is_unit(&self) -> bool {
368 matches!(self, Self::Unit)
369 }
370
371 #[must_use]
372 pub const fn is_scalar(&self) -> bool {
373 match self {
374 Self::List(_) | Self::Map(_) | Self::Unit => false,
376 _ => true,
377 }
378 }
379
380 #[must_use]
382 pub(crate) const fn canonical_tag(&self) -> ValueTag {
383 tag::canonical_tag(self)
384 }
385
386 #[must_use]
388 pub(crate) const fn canonical_rank(&self) -> u8 {
389 rank::canonical_rank(self)
390 }
391
392 #[must_use]
394 pub(crate) fn canonical_cmp(left: &Self, right: &Self) -> Ordering {
395 compare::canonical_cmp(left, right)
396 }
397
398 #[must_use]
400 pub fn canonical_cmp_key(left: &Self, right: &Self) -> Ordering {
401 compare::canonical_cmp_key(left, right)
402 }
403
404 #[must_use]
409 pub(crate) fn canonical_cmp_map_entry(
410 left_key: &Self,
411 left_value: &Self,
412 right_key: &Self,
413 right_value: &Self,
414 ) -> Ordering {
415 Self::canonical_cmp_key(left_key, right_key)
416 .then_with(|| Self::canonical_cmp(left_value, right_value))
417 }
418
419 #[must_use]
423 pub(crate) fn strict_order_cmp(left: &Self, right: &Self) -> Option<Ordering> {
424 compare::strict_order_cmp(left, right)
425 }
426
427 fn numeric_repr(&self) -> NumericRepr {
428 if !self.supports_numeric_coercion() {
430 return NumericRepr::None;
431 }
432
433 if let Some(d) = self.to_decimal() {
434 return NumericRepr::Decimal(d);
435 }
436 if let Some(f) = self.to_f64_lossless() {
437 return NumericRepr::F64(f);
438 }
439 NumericRepr::None
440 }
441
442 #[must_use]
451 pub const fn as_storage_key(&self) -> Option<StorageKey> {
452 scalar_registry!(value_storage_key_from_registry, self)
453 }
454
455 #[must_use]
456 pub const fn as_text(&self) -> Option<&str> {
457 if let Self::Text(s) = self {
458 Some(s.as_str())
459 } else {
460 None
461 }
462 }
463
464 #[must_use]
465 pub const fn as_list(&self) -> Option<&[Self]> {
466 if let Self::List(xs) = self {
467 Some(xs.as_slice())
468 } else {
469 None
470 }
471 }
472
473 #[must_use]
474 pub const fn as_map(&self) -> Option<&[(Self, Self)]> {
475 if let Self::Map(entries) = self {
476 Some(entries.as_slice())
477 } else {
478 None
479 }
480 }
481
482 fn to_decimal(&self) -> Option<Decimal> {
483 match self {
484 Self::Decimal(d) => Some(*d),
485 Self::Duration(d) => Decimal::from_u64(d.repr()),
486 Self::Float64(f) => Decimal::from_f64(f.get()),
487 Self::Float32(f) => Decimal::from_f32(f.get()),
488 Self::Int(i) => Decimal::from_i64(*i),
489 Self::Int128(i) => Decimal::from_i128(i.get()),
490 Self::IntBig(i) => i.to_i128().and_then(Decimal::from_i128),
491 Self::Timestamp(t) => Decimal::from_u64(t.repr()),
492 Self::Uint(u) => Decimal::from_u64(*u),
493 Self::Uint128(u) => Decimal::from_u128(u.get()),
494 Self::UintBig(u) => u.to_u128().and_then(Decimal::from_u128),
495
496 _ => None,
497 }
498 }
499
500 pub(crate) fn to_numeric_decimal(&self) -> Option<Decimal> {
502 self.to_decimal()
503 }
504
505 #[expect(clippy::cast_precision_loss)]
507 fn to_f64_lossless(&self) -> Option<f64> {
508 match self {
509 Self::Duration(d) if d.repr() <= F64_SAFE_U64 => Some(d.repr() as f64),
510 Self::Float64(f) => Some(f.get()),
511 Self::Float32(f) => Some(f64::from(f.get())),
512 Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
513 Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
514 Some(i.get() as f64)
515 }
516 Self::IntBig(i) => i.to_i128().and_then(|v| {
517 (-F64_SAFE_I128..=F64_SAFE_I128)
518 .contains(&v)
519 .then_some(v as f64)
520 }),
521 Self::Timestamp(t) if t.repr() <= F64_SAFE_U64 => Some(t.repr() as f64),
522 Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
523 Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
524 Self::UintBig(u) => u
525 .to_u128()
526 .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
527
528 _ => None,
529 }
530 }
531
532 #[must_use]
534 pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
535 if !self.supports_numeric_coercion() || !other.supports_numeric_coercion() {
536 return None;
537 }
538
539 match (self.numeric_repr(), other.numeric_repr()) {
540 (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
541 (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
542 _ => None,
543 }
544 }
545
546 fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
551 if s.is_ascii() {
552 return std::borrow::Cow::Owned(s.to_ascii_lowercase());
553 }
554 std::borrow::Cow::Owned(s.to_lowercase())
557 }
558
559 fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
560 match mode {
561 TextMode::Cs => std::borrow::Cow::Borrowed(s),
562 TextMode::Ci => Self::fold_ci(s),
563 }
564 }
565
566 fn text_op(
567 &self,
568 other: &Self,
569 mode: TextMode,
570 f: impl Fn(&str, &str) -> bool,
571 ) -> Option<bool> {
572 let (a, b) = (self.as_text()?, other.as_text()?);
573 let a = Self::text_with_mode(a, mode);
574 let b = Self::text_with_mode(b, mode);
575 Some(f(&a, &b))
576 }
577
578 fn ci_key(&self) -> Option<String> {
579 match self {
580 Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
581 Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
582 Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
583 Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
584 _ => None,
585 }
586 }
587
588 fn eq_ci(a: &Self, b: &Self) -> bool {
589 if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
590 return ak == bk;
591 }
592
593 a == b
594 }
595
596 fn normalize_list_ref(v: &Self) -> Vec<&Self> {
597 match v {
598 Self::List(vs) => vs.iter().collect(),
599 v => vec![v],
600 }
601 }
602
603 fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
604 where
605 F: Fn(&Self, &Self) -> bool,
606 {
607 self.as_list()
608 .map(|items| items.iter().any(|v| eq(v, needle)))
609 }
610
611 #[expect(clippy::unnecessary_wraps)]
612 fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
613 where
614 F: Fn(&Self, &Self) -> bool,
615 {
616 let needles = Self::normalize_list_ref(needles);
617 match self {
618 Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
619 scalar => Some(needles.iter().any(|n| eq(scalar, n))),
620 }
621 }
622
623 #[expect(clippy::unnecessary_wraps)]
624 fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
625 where
626 F: Fn(&Self, &Self) -> bool,
627 {
628 let needles = Self::normalize_list_ref(needles);
629 match self {
630 Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
631 scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
632 }
633 }
634
635 fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
636 where
637 F: Fn(&Self, &Self) -> bool,
638 {
639 if let Self::List(items) = haystack {
640 Some(items.iter().any(|h| eq(h, self)))
641 } else {
642 None
643 }
644 }
645
646 #[must_use]
647 pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
649 self.text_op(other, mode, |a, b| a == b)
650 }
651
652 #[must_use]
653 pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
655 self.text_op(needle, mode, |a, b| a.contains(b))
656 }
657
658 #[must_use]
659 pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
661 self.text_op(needle, mode, |a, b| a.starts_with(b))
662 }
663
664 #[must_use]
665 pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
667 self.text_op(needle, mode, |a, b| a.ends_with(b))
668 }
669
670 #[must_use]
675 pub const fn is_empty(&self) -> Option<bool> {
676 match self {
677 Self::List(xs) => Some(xs.is_empty()),
678 Self::Map(entries) => Some(entries.is_empty()),
679 Self::Text(s) => Some(s.is_empty()),
680 Self::Blob(b) => Some(b.is_empty()),
681
682 Self::Null => Some(true),
684
685 _ => None,
686 }
687 }
688
689 #[must_use]
690 pub fn is_not_empty(&self) -> Option<bool> {
692 self.is_empty().map(|b| !b)
693 }
694
695 #[must_use]
700 pub fn contains(&self, needle: &Self) -> Option<bool> {
702 self.contains_by(needle, |a, b| a == b)
703 }
704
705 #[must_use]
706 pub fn contains_any(&self, needles: &Self) -> Option<bool> {
708 self.contains_any_by(needles, |a, b| a == b)
709 }
710
711 #[must_use]
712 pub fn contains_all(&self, needles: &Self) -> Option<bool> {
714 self.contains_all_by(needles, |a, b| a == b)
715 }
716
717 #[must_use]
718 pub fn in_list(&self, haystack: &Self) -> Option<bool> {
720 self.in_list_by(haystack, |a, b| a == b)
721 }
722
723 #[must_use]
724 pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
726 match self {
727 Self::List(_) => self.contains_by(needle, Self::eq_ci),
728 _ => Some(Self::eq_ci(self, needle)),
729 }
730 }
731
732 #[must_use]
733 pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
735 self.contains_any_by(needles, Self::eq_ci)
736 }
737
738 #[must_use]
739 pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
741 self.contains_all_by(needles, Self::eq_ci)
742 }
743
744 #[must_use]
745 pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
747 self.in_list_by(haystack, Self::eq_ci)
748 }
749}
750
751impl FieldValue for Value {
752 fn kind() -> crate::traits::FieldValueKind {
753 crate::traits::FieldValueKind::Atomic
754 }
755
756 fn to_value(&self) -> Value {
757 self.clone()
758 }
759
760 fn from_value(value: &Value) -> Option<Self> {
761 Some(value.clone())
762 }
763}
764
765#[macro_export]
766macro_rules! impl_from_for {
767 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
768 $(
769 impl From<$type> for Value {
770 fn from(v: $type) -> Self {
771 Self::$variant(v.into())
772 }
773 }
774 )*
775 };
776}
777
778impl_from_for! {
779 Account => Account,
780 Date => Date,
781 Decimal => Decimal,
782 Duration => Duration,
783 bool => Bool,
784 i8 => Int,
785 i16 => Int,
786 i32 => Int,
787 i64 => Int,
788 i128 => Int128,
789 Int => IntBig,
790 Principal => Principal,
791 Subaccount => Subaccount,
792 &str => Text,
793 String => Text,
794 Timestamp => Timestamp,
795 u8 => Uint,
796 u16 => Uint,
797 u32 => Uint,
798 u64 => Uint,
799 u128 => Uint128,
800 Nat => UintBig,
801 Ulid => Ulid,
802}
803
804impl CoercionFamilyExt for Value {
805 fn coercion_family(&self) -> CoercionFamily {
811 scalar_registry!(value_coercion_family_from_registry, self)
812 }
813}
814
815impl From<Vec<Self>> for Value {
816 fn from(vec: Vec<Self>) -> Self {
817 Self::List(vec)
818 }
819}
820
821impl TryFrom<Vec<(Self, Self)>> for Value {
822 type Error = SchemaInvariantError;
823
824 fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
825 Self::from_map(entries).map_err(Self::Error::from)
826 }
827}
828
829impl From<()> for Value {
830 fn from((): ()) -> Self {
831 Self::Unit
832 }
833}
834
835impl PartialOrd for Value {
841 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
842 match (self, other) {
843 (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
844 (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
845 (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
846 (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
847 (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
848 (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
849 (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
850 (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
851 (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
852 (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
853 (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
854 (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
855 (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
856 (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
857 (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
858 (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
859 (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
860 (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
861 (Self::Map(a), Self::Map(b)) => {
862 for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
863 let key_cmp = Self::canonical_cmp_key(left_key, right_key);
864 if key_cmp != Ordering::Equal {
865 return Some(key_cmp);
866 }
867
868 match left_value.partial_cmp(right_value) {
869 Some(Ordering::Equal) => {}
870 non_eq => return non_eq,
871 }
872 }
873 a.len().partial_cmp(&b.len())
874 }
875
876 _ => None,
878 }
879 }
880}
881
882#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
888pub struct ValueEnum {
889 pub variant: String,
890 pub path: Option<String>,
891 pub payload: Option<Box<Value>>,
892}
893
894impl ValueEnum {
895 #[must_use]
896 pub fn new(variant: &str, path: Option<&str>) -> Self {
898 Self {
899 variant: variant.to_string(),
900 path: path.map(ToString::to_string),
901 payload: None,
902 }
903 }
904
905 #[must_use]
906 pub fn strict<E: Path>(variant: &str) -> Self {
908 Self::new(variant, Some(E::PATH))
909 }
910
911 #[must_use]
912 pub fn from_enum<E: EnumValue>(value: E) -> Self {
914 value.to_value_enum()
915 }
916
917 #[must_use]
918 pub fn loose(variant: &str) -> Self {
921 Self::new(variant, None)
922 }
923
924 #[must_use]
925 pub fn with_payload(mut self, payload: Value) -> Self {
927 self.payload = Some(Box::new(payload));
928 self
929 }
930}