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]
408 pub(crate) fn strict_order_cmp(left: &Self, right: &Self) -> Option<Ordering> {
409 compare::strict_order_cmp(left, right)
410 }
411
412 fn numeric_repr(&self) -> NumericRepr {
413 if !self.supports_numeric_coercion() {
415 return NumericRepr::None;
416 }
417
418 if let Some(d) = self.to_decimal() {
419 return NumericRepr::Decimal(d);
420 }
421 if let Some(f) = self.to_f64_lossless() {
422 return NumericRepr::F64(f);
423 }
424 NumericRepr::None
425 }
426
427 #[must_use]
436 pub const fn as_storage_key(&self) -> Option<StorageKey> {
437 scalar_registry!(value_storage_key_from_registry, self)
438 }
439
440 #[must_use]
441 pub const fn as_text(&self) -> Option<&str> {
442 if let Self::Text(s) = self {
443 Some(s.as_str())
444 } else {
445 None
446 }
447 }
448
449 #[must_use]
450 pub const fn as_list(&self) -> Option<&[Self]> {
451 if let Self::List(xs) = self {
452 Some(xs.as_slice())
453 } else {
454 None
455 }
456 }
457
458 #[must_use]
459 pub const fn as_map(&self) -> Option<&[(Self, Self)]> {
460 if let Self::Map(entries) = self {
461 Some(entries.as_slice())
462 } else {
463 None
464 }
465 }
466
467 fn to_decimal(&self) -> Option<Decimal> {
468 match self {
469 Self::Decimal(d) => Some(*d),
470 Self::Duration(d) => Decimal::from_u64(d.repr()),
471 Self::Float64(f) => Decimal::from_f64(f.get()),
472 Self::Float32(f) => Decimal::from_f32(f.get()),
473 Self::Int(i) => Decimal::from_i64(*i),
474 Self::Int128(i) => Decimal::from_i128(i.get()),
475 Self::IntBig(i) => i.to_i128().and_then(Decimal::from_i128),
476 Self::Timestamp(t) => Decimal::from_u64(t.repr()),
477 Self::Uint(u) => Decimal::from_u64(*u),
478 Self::Uint128(u) => Decimal::from_u128(u.get()),
479 Self::UintBig(u) => u.to_u128().and_then(Decimal::from_u128),
480
481 _ => None,
482 }
483 }
484
485 pub(crate) fn to_numeric_decimal(&self) -> Option<Decimal> {
487 self.to_decimal()
488 }
489
490 #[expect(clippy::cast_precision_loss)]
492 fn to_f64_lossless(&self) -> Option<f64> {
493 match self {
494 Self::Duration(d) if d.repr() <= F64_SAFE_U64 => Some(d.repr() as f64),
495 Self::Float64(f) => Some(f.get()),
496 Self::Float32(f) => Some(f64::from(f.get())),
497 Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
498 Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
499 Some(i.get() as f64)
500 }
501 Self::IntBig(i) => i.to_i128().and_then(|v| {
502 (-F64_SAFE_I128..=F64_SAFE_I128)
503 .contains(&v)
504 .then_some(v as f64)
505 }),
506 Self::Timestamp(t) if t.repr() <= F64_SAFE_U64 => Some(t.repr() as f64),
507 Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
508 Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
509 Self::UintBig(u) => u
510 .to_u128()
511 .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
512
513 _ => None,
514 }
515 }
516
517 #[must_use]
519 pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
520 if !self.supports_numeric_coercion() || !other.supports_numeric_coercion() {
521 return None;
522 }
523
524 match (self.numeric_repr(), other.numeric_repr()) {
525 (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
526 (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
527 _ => None,
528 }
529 }
530
531 fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
536 if s.is_ascii() {
537 return std::borrow::Cow::Owned(s.to_ascii_lowercase());
538 }
539 std::borrow::Cow::Owned(s.to_lowercase())
542 }
543
544 fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
545 match mode {
546 TextMode::Cs => std::borrow::Cow::Borrowed(s),
547 TextMode::Ci => Self::fold_ci(s),
548 }
549 }
550
551 fn text_op(
552 &self,
553 other: &Self,
554 mode: TextMode,
555 f: impl Fn(&str, &str) -> bool,
556 ) -> Option<bool> {
557 let (a, b) = (self.as_text()?, other.as_text()?);
558 let a = Self::text_with_mode(a, mode);
559 let b = Self::text_with_mode(b, mode);
560 Some(f(&a, &b))
561 }
562
563 fn ci_key(&self) -> Option<String> {
564 match self {
565 Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
566 Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
567 Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
568 Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
569 _ => None,
570 }
571 }
572
573 fn eq_ci(a: &Self, b: &Self) -> bool {
574 if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
575 return ak == bk;
576 }
577
578 a == b
579 }
580
581 fn normalize_list_ref(v: &Self) -> Vec<&Self> {
582 match v {
583 Self::List(vs) => vs.iter().collect(),
584 v => vec![v],
585 }
586 }
587
588 fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
589 where
590 F: Fn(&Self, &Self) -> bool,
591 {
592 self.as_list()
593 .map(|items| items.iter().any(|v| eq(v, needle)))
594 }
595
596 #[expect(clippy::unnecessary_wraps)]
597 fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
598 where
599 F: Fn(&Self, &Self) -> bool,
600 {
601 let needles = Self::normalize_list_ref(needles);
602 match self {
603 Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
604 scalar => Some(needles.iter().any(|n| eq(scalar, n))),
605 }
606 }
607
608 #[expect(clippy::unnecessary_wraps)]
609 fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
610 where
611 F: Fn(&Self, &Self) -> bool,
612 {
613 let needles = Self::normalize_list_ref(needles);
614 match self {
615 Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
616 scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
617 }
618 }
619
620 fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
621 where
622 F: Fn(&Self, &Self) -> bool,
623 {
624 if let Self::List(items) = haystack {
625 Some(items.iter().any(|h| eq(h, self)))
626 } else {
627 None
628 }
629 }
630
631 #[must_use]
632 pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
634 self.text_op(other, mode, |a, b| a == b)
635 }
636
637 #[must_use]
638 pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
640 self.text_op(needle, mode, |a, b| a.contains(b))
641 }
642
643 #[must_use]
644 pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
646 self.text_op(needle, mode, |a, b| a.starts_with(b))
647 }
648
649 #[must_use]
650 pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
652 self.text_op(needle, mode, |a, b| a.ends_with(b))
653 }
654
655 #[must_use]
660 pub const fn is_empty(&self) -> Option<bool> {
661 match self {
662 Self::List(xs) => Some(xs.is_empty()),
663 Self::Map(entries) => Some(entries.is_empty()),
664 Self::Text(s) => Some(s.is_empty()),
665 Self::Blob(b) => Some(b.is_empty()),
666
667 Self::Null => Some(true),
669
670 _ => None,
671 }
672 }
673
674 #[must_use]
675 pub fn is_not_empty(&self) -> Option<bool> {
677 self.is_empty().map(|b| !b)
678 }
679
680 #[must_use]
685 pub fn contains(&self, needle: &Self) -> Option<bool> {
687 self.contains_by(needle, |a, b| a == b)
688 }
689
690 #[must_use]
691 pub fn contains_any(&self, needles: &Self) -> Option<bool> {
693 self.contains_any_by(needles, |a, b| a == b)
694 }
695
696 #[must_use]
697 pub fn contains_all(&self, needles: &Self) -> Option<bool> {
699 self.contains_all_by(needles, |a, b| a == b)
700 }
701
702 #[must_use]
703 pub fn in_list(&self, haystack: &Self) -> Option<bool> {
705 self.in_list_by(haystack, |a, b| a == b)
706 }
707
708 #[must_use]
709 pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
711 match self {
712 Self::List(_) => self.contains_by(needle, Self::eq_ci),
713 _ => Some(Self::eq_ci(self, needle)),
714 }
715 }
716
717 #[must_use]
718 pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
720 self.contains_any_by(needles, Self::eq_ci)
721 }
722
723 #[must_use]
724 pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
726 self.contains_all_by(needles, Self::eq_ci)
727 }
728
729 #[must_use]
730 pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
732 self.in_list_by(haystack, Self::eq_ci)
733 }
734}
735
736impl FieldValue for Value {
737 fn kind() -> crate::traits::FieldValueKind {
738 crate::traits::FieldValueKind::Atomic
739 }
740
741 fn to_value(&self) -> Value {
742 self.clone()
743 }
744
745 fn from_value(value: &Value) -> Option<Self> {
746 Some(value.clone())
747 }
748}
749
750#[macro_export]
751macro_rules! impl_from_for {
752 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
753 $(
754 impl From<$type> for Value {
755 fn from(v: $type) -> Self {
756 Self::$variant(v.into())
757 }
758 }
759 )*
760 };
761}
762
763impl_from_for! {
764 Account => Account,
765 Date => Date,
766 Decimal => Decimal,
767 Duration => Duration,
768 bool => Bool,
769 i8 => Int,
770 i16 => Int,
771 i32 => Int,
772 i64 => Int,
773 i128 => Int128,
774 Int => IntBig,
775 Principal => Principal,
776 Subaccount => Subaccount,
777 &str => Text,
778 String => Text,
779 Timestamp => Timestamp,
780 u8 => Uint,
781 u16 => Uint,
782 u32 => Uint,
783 u64 => Uint,
784 u128 => Uint128,
785 Nat => UintBig,
786 Ulid => Ulid,
787}
788
789impl CoercionFamilyExt for Value {
790 fn coercion_family(&self) -> CoercionFamily {
796 scalar_registry!(value_coercion_family_from_registry, self)
797 }
798}
799
800impl From<Vec<Self>> for Value {
801 fn from(vec: Vec<Self>) -> Self {
802 Self::List(vec)
803 }
804}
805
806impl TryFrom<Vec<(Self, Self)>> for Value {
807 type Error = SchemaInvariantError;
808
809 fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
810 Self::from_map(entries).map_err(Self::Error::from)
811 }
812}
813
814impl From<()> for Value {
815 fn from((): ()) -> Self {
816 Self::Unit
817 }
818}
819
820impl PartialOrd for Value {
826 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
827 match (self, other) {
828 (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
829 (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
830 (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
831 (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
832 (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
833 (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
834 (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
835 (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
836 (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
837 (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
838 (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
839 (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
840 (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
841 (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
842 (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
843 (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
844 (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
845 (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
846 (Self::Map(a), Self::Map(b)) => {
847 for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
848 let key_cmp = Self::canonical_cmp_key(left_key, right_key);
849 if key_cmp != Ordering::Equal {
850 return Some(key_cmp);
851 }
852
853 match left_value.partial_cmp(right_value) {
854 Some(Ordering::Equal) => {}
855 non_eq => return non_eq,
856 }
857 }
858 a.len().partial_cmp(&b.len())
859 }
860
861 _ => None,
863 }
864 }
865}
866
867#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
873pub struct ValueEnum {
874 pub variant: String,
875 pub path: Option<String>,
876 pub payload: Option<Box<Value>>,
877}
878
879impl ValueEnum {
880 #[must_use]
881 pub fn new(variant: &str, path: Option<&str>) -> Self {
883 Self {
884 variant: variant.to_string(),
885 path: path.map(ToString::to_string),
886 payload: None,
887 }
888 }
889
890 #[must_use]
891 pub fn strict<E: Path>(variant: &str) -> Self {
893 Self::new(variant, Some(E::PATH))
894 }
895
896 #[must_use]
897 pub fn from_enum<E: EnumValue>(value: E) -> Self {
899 value.to_value_enum()
900 }
901
902 #[must_use]
903 pub fn loose(variant: &str) -> Self {
906 Self::new(variant, None)
907 }
908
909 #[must_use]
910 pub fn with_payload(mut self, payload: Value) -> Self {
912 self.payload = Some(Box::new(payload));
913 self
914 }
915}