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 prelude::*,
20 traits::{EnumValue, FieldValue, NumFromPrimitive, Repr},
21 types::*,
22};
23use candid::CandidType;
24use serde::{Deserialize, Serialize};
25use std::cmp::Ordering;
26
27pub use coercion::{CoercionFamily, CoercionFamilyExt};
29pub(crate) use hash::hash_value;
30#[cfg(test)]
31pub(crate) use hash::with_test_hash_override;
32pub use storage_key::{StorageKey, StorageKeyDecodeError, StorageKeyEncodeError};
33pub use tag::ValueTag;
34
35const F64_SAFE_I64: i64 = 1i64 << 53;
40const F64_SAFE_U64: u64 = 1u64 << 53;
41const F64_SAFE_I128: i128 = 1i128 << 53;
42const F64_SAFE_U128: u128 = 1u128 << 53;
43
44enum NumericRepr {
49 Decimal(Decimal),
50 F64(f64),
51 None,
52}
53
54#[derive(Clone, Copy, Debug, Eq, PartialEq)]
59pub enum TextMode {
60 Cs, Ci, }
63
64#[derive(Clone, Debug, Eq, PartialEq)]
71pub enum MapValueError {
72 EmptyKey {
73 index: usize,
74 },
75 NonScalarKey {
76 index: usize,
77 key: Value,
78 },
79 NonScalarValue {
80 index: usize,
81 value: Value,
82 },
83 DuplicateKey {
84 left_index: usize,
85 right_index: usize,
86 },
87}
88
89impl std::fmt::Display for MapValueError {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 match self {
92 Self::EmptyKey { index } => write!(f, "map key at index {index} must be non-null"),
93 Self::NonScalarKey { index, key } => {
94 write!(f, "map key at index {index} is not scalar: {key:?}")
95 }
96 Self::NonScalarValue { index, value } => {
97 write!(
98 f,
99 "map value at index {index} is not scalar/ref-like: {value:?}"
100 )
101 }
102 Self::DuplicateKey {
103 left_index,
104 right_index,
105 } => write!(
106 f,
107 "map contains duplicate keys at normalized positions {left_index} and {right_index}"
108 ),
109 }
110 }
111}
112
113impl std::error::Error for MapValueError {}
114
115#[derive(Clone, Debug, Eq, PartialEq)]
122pub enum SchemaInvariantError {
123 InvalidMapValue(MapValueError),
124}
125
126impl std::fmt::Display for SchemaInvariantError {
127 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128 match self {
129 Self::InvalidMapValue(err) => write!(f, "{err}"),
130 }
131 }
132}
133
134impl std::error::Error for SchemaInvariantError {}
135
136impl From<MapValueError> for SchemaInvariantError {
137 fn from(value: MapValueError) -> Self {
138 Self::InvalidMapValue(value)
139 }
140}
141
142#[derive(CandidType, Clone, Debug, Eq, PartialEq, Serialize)]
151pub enum Value {
152 Account(Account),
153 Blob(Vec<u8>),
154 Bool(bool),
155 Date(Date),
156 Decimal(Decimal),
157 Duration(Duration),
158 Enum(ValueEnum),
159 Float32(Float32),
160 Float64(Float64),
161 Int(i64),
162 Int128(Int128),
163 IntBig(Int),
164 List(Vec<Self>),
168 Map(Vec<(Self, Self)>),
175 Null,
176 Principal(Principal),
177 Subaccount(Subaccount),
178 Text(String),
179 Timestamp(Timestamp),
180 Uint(u64),
181 Uint128(Nat128),
182 UintBig(Nat),
183 Ulid(Ulid),
184 Unit,
185}
186
187macro_rules! value_is_numeric_from_registry {
189 ( @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) ),* $(,)? ) => {
190 match $value {
191 $( $value_pat => $is_numeric, )*
192 _ => false,
193 }
194 };
195}
196
197macro_rules! value_supports_numeric_coercion_from_registry {
198 ( @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) ),* $(,)? ) => {
199 match $value {
200 $( $value_pat => $supports_numeric_coercion, )*
201 _ => false,
202 }
203 };
204}
205
206macro_rules! value_storage_key_case {
207 ( $value:expr, Unit, true ) => {
208 if let Value::Unit = $value {
209 Some(StorageKey::Unit)
210 } else {
211 None
212 }
213 };
214 ( $value:expr, $scalar:ident, true ) => {
215 if let Value::$scalar(v) = $value {
216 Some(StorageKey::$scalar(*v))
217 } else {
218 None
219 }
220 };
221 ( $value:expr, $scalar:ident, false ) => {
222 None
223 };
224}
225
226macro_rules! value_storage_key_from_registry {
227 ( @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) ),* $(,)? ) => {
228 {
229 let mut key = None;
230 $(
231 match key {
232 Some(_) => {}
233 None => {
234 key = value_storage_key_case!($value, $scalar, $is_storage_key_encodable);
235 }
236 }
237 )*
238 key
239 }
240 };
241}
242
243macro_rules! value_coercion_family_from_registry {
244 ( @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) ),* $(,)? ) => {
245 match $value {
246 $( $value_pat => $coercion_family, )*
247 Value::List(_) => CoercionFamily::Collection,
248 Value::Map(_) => CoercionFamily::Collection,
249 Value::Null => CoercionFamily::Null,
250 }
251 };
252}
253
254impl Value {
255 pub fn from_slice<T>(items: &[T]) -> Self
264 where
265 T: Into<Self> + Clone,
266 {
267 Self::List(items.iter().cloned().map(Into::into).collect())
268 }
269
270 pub fn from_list<T>(items: Vec<T>) -> Self
274 where
275 T: Into<Self>,
276 {
277 Self::List(items.into_iter().map(Into::into).collect())
278 }
279
280 pub fn from_map(entries: Vec<(Self, Self)>) -> Result<Self, MapValueError> {
288 let normalized = Self::normalize_map_entries(entries)?;
289 Ok(Self::Map(normalized))
290 }
291
292 pub fn validate_map_entries(entries: &[(Self, Self)]) -> Result<(), MapValueError> {
294 for (index, (key, value)) in entries.iter().enumerate() {
295 if matches!(key, Self::Null) {
296 return Err(MapValueError::EmptyKey { index });
297 }
298 if !key.is_scalar() {
299 return Err(MapValueError::NonScalarKey {
300 index,
301 key: key.clone(),
302 });
303 }
304
305 if !value.is_scalar() {
306 return Err(MapValueError::NonScalarValue {
307 index,
308 value: value.clone(),
309 });
310 }
311 }
312
313 Ok(())
314 }
315
316 pub fn normalize_map_entries(
318 mut entries: Vec<(Self, Self)>,
319 ) -> Result<Vec<(Self, Self)>, MapValueError> {
320 Self::validate_map_entries(&entries)?;
321 entries
322 .sort_by(|(left_key, _), (right_key, _)| Self::canonical_cmp_key(left_key, right_key));
323
324 for i in 1..entries.len() {
325 let (left_key, _) = &entries[i - 1];
326 let (right_key, _) = &entries[i];
327 if Self::canonical_cmp_key(left_key, right_key) == Ordering::Equal {
328 return Err(MapValueError::DuplicateKey {
329 left_index: i - 1,
330 right_index: i,
331 });
332 }
333 }
334
335 Ok(entries)
336 }
337
338 pub fn from_enum<E: EnumValue>(value: E) -> Self {
340 Self::Enum(value.to_value_enum())
341 }
342
343 #[must_use]
345 pub fn enum_strict<E: Path>(variant: &str) -> Self {
346 Self::Enum(ValueEnum::strict::<E>(variant))
347 }
348
349 #[must_use]
356 pub const fn is_numeric(&self) -> bool {
357 scalar_registry!(value_is_numeric_from_registry, self)
358 }
359
360 #[must_use]
362 pub const fn supports_numeric_coercion(&self) -> bool {
363 scalar_registry!(value_supports_numeric_coercion_from_registry, self)
364 }
365
366 #[must_use]
368 pub const fn is_text(&self) -> bool {
369 matches!(self, Self::Text(_))
370 }
371
372 #[must_use]
374 pub const fn is_unit(&self) -> bool {
375 matches!(self, Self::Unit)
376 }
377
378 #[must_use]
379 pub const fn is_scalar(&self) -> bool {
380 match self {
381 Self::List(_) | Self::Map(_) | Self::Unit => false,
383 _ => true,
384 }
385 }
386
387 #[must_use]
389 pub(crate) const fn canonical_tag(&self) -> ValueTag {
390 tag::canonical_tag(self)
391 }
392
393 #[must_use]
395 pub(crate) const fn canonical_rank(&self) -> u8 {
396 rank::canonical_rank(self)
397 }
398
399 #[must_use]
401 pub(crate) fn canonical_cmp(left: &Self, right: &Self) -> Ordering {
402 compare::canonical_cmp(left, right)
403 }
404
405 #[must_use]
407 pub fn canonical_cmp_key(left: &Self, right: &Self) -> Ordering {
408 compare::canonical_cmp_key(left, right)
409 }
410
411 #[must_use]
416 pub(crate) fn canonical_cmp_map_entry(
417 left_key: &Self,
418 left_value: &Self,
419 right_key: &Self,
420 right_value: &Self,
421 ) -> Ordering {
422 Self::canonical_cmp_key(left_key, right_key)
423 .then_with(|| Self::canonical_cmp(left_value, right_value))
424 }
425
426 #[must_use]
430 pub(crate) fn strict_order_cmp(left: &Self, right: &Self) -> Option<Ordering> {
431 compare::strict_order_cmp(left, right)
432 }
433
434 fn numeric_repr(&self) -> NumericRepr {
435 if !self.supports_numeric_coercion() {
437 return NumericRepr::None;
438 }
439
440 if let Some(d) = self.to_decimal() {
441 return NumericRepr::Decimal(d);
442 }
443 if let Some(f) = self.to_f64_lossless() {
444 return NumericRepr::F64(f);
445 }
446 NumericRepr::None
447 }
448
449 #[must_use]
458 pub const fn as_storage_key(&self) -> Option<StorageKey> {
459 scalar_registry!(value_storage_key_from_registry, self)
460 }
461
462 #[must_use]
463 pub const fn as_text(&self) -> Option<&str> {
464 if let Self::Text(s) = self {
465 Some(s.as_str())
466 } else {
467 None
468 }
469 }
470
471 #[must_use]
472 pub const fn as_list(&self) -> Option<&[Self]> {
473 if let Self::List(xs) = self {
474 Some(xs.as_slice())
475 } else {
476 None
477 }
478 }
479
480 #[must_use]
481 pub const fn as_map(&self) -> Option<&[(Self, Self)]> {
482 if let Self::Map(entries) = self {
483 Some(entries.as_slice())
484 } else {
485 None
486 }
487 }
488
489 fn to_decimal(&self) -> Option<Decimal> {
490 match self {
491 Self::Decimal(d) => Some(*d),
492 Self::Duration(d) => Decimal::from_u64(d.repr()),
493 Self::Float64(f) => Decimal::from_f64(f.get()),
494 Self::Float32(f) => Decimal::from_f32(f.get()),
495 Self::Int(i) => Decimal::from_i64(*i),
496 Self::Int128(i) => Decimal::from_i128(i.get()),
497 Self::IntBig(i) => i.to_i128().and_then(Decimal::from_i128),
498 Self::Timestamp(t) => Decimal::from_i64(t.repr()),
499 Self::Uint(u) => Decimal::from_u64(*u),
500 Self::Uint128(u) => Decimal::from_u128(u.get()),
501 Self::UintBig(u) => u.to_u128().and_then(Decimal::from_u128),
502
503 _ => None,
504 }
505 }
506
507 pub(crate) fn to_numeric_decimal(&self) -> Option<Decimal> {
509 self.to_decimal()
510 }
511
512 #[expect(clippy::cast_precision_loss)]
514 fn to_f64_lossless(&self) -> Option<f64> {
515 match self {
516 Self::Duration(d) if d.repr() <= F64_SAFE_U64 => Some(d.repr() as f64),
517 Self::Float64(f) => Some(f.get()),
518 Self::Float32(f) => Some(f64::from(f.get())),
519 Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
520 Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
521 Some(i.get() as f64)
522 }
523 Self::IntBig(i) => i.to_i128().and_then(|v| {
524 (-F64_SAFE_I128..=F64_SAFE_I128)
525 .contains(&v)
526 .then_some(v as f64)
527 }),
528 Self::Timestamp(t) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(&t.repr()) => {
529 Some(t.repr() as f64)
530 }
531 Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
532 Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
533 Self::UintBig(u) => u
534 .to_u128()
535 .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
536
537 _ => None,
538 }
539 }
540
541 #[must_use]
543 pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
544 if !self.supports_numeric_coercion() || !other.supports_numeric_coercion() {
545 return None;
546 }
547
548 match (self.numeric_repr(), other.numeric_repr()) {
549 (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
550 (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
551 _ => None,
552 }
553 }
554
555 fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
560 if s.is_ascii() {
561 return std::borrow::Cow::Owned(s.to_ascii_lowercase());
562 }
563 std::borrow::Cow::Owned(s.to_lowercase())
566 }
567
568 fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
569 match mode {
570 TextMode::Cs => std::borrow::Cow::Borrowed(s),
571 TextMode::Ci => Self::fold_ci(s),
572 }
573 }
574
575 fn text_op(
576 &self,
577 other: &Self,
578 mode: TextMode,
579 f: impl Fn(&str, &str) -> bool,
580 ) -> Option<bool> {
581 let (a, b) = (self.as_text()?, other.as_text()?);
582 let a = Self::text_with_mode(a, mode);
583 let b = Self::text_with_mode(b, mode);
584 Some(f(&a, &b))
585 }
586
587 fn ci_key(&self) -> Option<String> {
588 match self {
589 Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
590 Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
591 Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
592 Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
593 _ => None,
594 }
595 }
596
597 fn eq_ci(a: &Self, b: &Self) -> bool {
598 if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
599 return ak == bk;
600 }
601
602 a == b
603 }
604
605 fn normalize_list_ref(v: &Self) -> Vec<&Self> {
606 match v {
607 Self::List(vs) => vs.iter().collect(),
608 v => vec![v],
609 }
610 }
611
612 fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
613 where
614 F: Fn(&Self, &Self) -> bool,
615 {
616 self.as_list()
617 .map(|items| items.iter().any(|v| eq(v, needle)))
618 }
619
620 #[expect(clippy::unnecessary_wraps)]
621 fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
622 where
623 F: Fn(&Self, &Self) -> bool,
624 {
625 let needles = Self::normalize_list_ref(needles);
626 match self {
627 Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
628 scalar => Some(needles.iter().any(|n| eq(scalar, n))),
629 }
630 }
631
632 #[expect(clippy::unnecessary_wraps)]
633 fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
634 where
635 F: Fn(&Self, &Self) -> bool,
636 {
637 let needles = Self::normalize_list_ref(needles);
638 match self {
639 Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
640 scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
641 }
642 }
643
644 fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
645 where
646 F: Fn(&Self, &Self) -> bool,
647 {
648 if let Self::List(items) = haystack {
649 Some(items.iter().any(|h| eq(h, self)))
650 } else {
651 None
652 }
653 }
654
655 #[must_use]
657 pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
658 self.text_op(other, mode, |a, b| a == b)
659 }
660
661 #[must_use]
663 pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
664 self.text_op(needle, mode, |a, b| a.contains(b))
665 }
666
667 #[must_use]
669 pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
670 self.text_op(needle, mode, |a, b| a.starts_with(b))
671 }
672
673 #[must_use]
675 pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
676 self.text_op(needle, mode, |a, b| a.ends_with(b))
677 }
678
679 #[must_use]
684 pub const fn is_empty(&self) -> Option<bool> {
685 match self {
686 Self::List(xs) => Some(xs.is_empty()),
687 Self::Map(entries) => Some(entries.is_empty()),
688 Self::Text(s) => Some(s.is_empty()),
689 Self::Blob(b) => Some(b.is_empty()),
690
691 Self::Null => Some(true),
693
694 _ => None,
695 }
696 }
697
698 #[must_use]
700 pub fn is_not_empty(&self) -> Option<bool> {
701 self.is_empty().map(|b| !b)
702 }
703
704 #[must_use]
710 pub fn contains(&self, needle: &Self) -> Option<bool> {
711 self.contains_by(needle, |a, b| a == b)
712 }
713
714 #[must_use]
716 pub fn contains_any(&self, needles: &Self) -> Option<bool> {
717 self.contains_any_by(needles, |a, b| a == b)
718 }
719
720 #[must_use]
722 pub fn contains_all(&self, needles: &Self) -> Option<bool> {
723 self.contains_all_by(needles, |a, b| a == b)
724 }
725
726 #[must_use]
728 pub fn in_list(&self, haystack: &Self) -> Option<bool> {
729 self.in_list_by(haystack, |a, b| a == b)
730 }
731
732 #[must_use]
734 pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
735 match self {
736 Self::List(_) => self.contains_by(needle, Self::eq_ci),
737 _ => Some(Self::eq_ci(self, needle)),
738 }
739 }
740
741 #[must_use]
743 pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
744 self.contains_any_by(needles, Self::eq_ci)
745 }
746
747 #[must_use]
749 pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
750 self.contains_all_by(needles, Self::eq_ci)
751 }
752
753 #[must_use]
755 pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
756 self.in_list_by(haystack, Self::eq_ci)
757 }
758}
759
760impl FieldValue for Value {
761 fn kind() -> crate::traits::FieldValueKind {
762 crate::traits::FieldValueKind::Atomic
763 }
764
765 fn to_value(&self) -> Value {
766 self.clone()
767 }
768
769 fn from_value(value: &Value) -> Option<Self> {
770 Some(value.clone())
771 }
772}
773
774#[macro_export]
775macro_rules! impl_from_for {
776 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
777 $(
778 impl From<$type> for Value {
779 fn from(v: $type) -> Self {
780 Self::$variant(v.into())
781 }
782 }
783 )*
784 };
785}
786
787impl_from_for! {
788 Account => Account,
789 Date => Date,
790 Decimal => Decimal,
791 Duration => Duration,
792 bool => Bool,
793 i8 => Int,
794 i16 => Int,
795 i32 => Int,
796 i64 => Int,
797 i128 => Int128,
798 Int => IntBig,
799 Principal => Principal,
800 Subaccount => Subaccount,
801 &str => Text,
802 String => Text,
803 Timestamp => Timestamp,
804 u8 => Uint,
805 u16 => Uint,
806 u32 => Uint,
807 u64 => Uint,
808 u128 => Uint128,
809 Nat => UintBig,
810 Ulid => Ulid,
811}
812
813impl CoercionFamilyExt for Value {
814 fn coercion_family(&self) -> CoercionFamily {
820 scalar_registry!(value_coercion_family_from_registry, self)
821 }
822}
823
824impl From<Vec<Self>> for Value {
825 fn from(vec: Vec<Self>) -> Self {
826 Self::List(vec)
827 }
828}
829
830impl TryFrom<Vec<(Self, Self)>> for Value {
831 type Error = SchemaInvariantError;
832
833 fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
834 Self::from_map(entries).map_err(Self::Error::from)
835 }
836}
837
838impl From<()> for Value {
839 fn from((): ()) -> Self {
840 Self::Unit
841 }
842}
843
844impl PartialOrd for Value {
850 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
851 match (self, other) {
852 (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
853 (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
854 (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
855 (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
856 (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
857 (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
858 (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
859 (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
860 (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
861 (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
862 (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
863 (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
864 (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
865 (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
866 (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
867 (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
868 (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
869 (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
870 (Self::Map(a), Self::Map(b)) => {
871 for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
872 let key_cmp = Self::canonical_cmp_key(left_key, right_key);
873 if key_cmp != Ordering::Equal {
874 return Some(key_cmp);
875 }
876
877 match left_value.partial_cmp(right_value) {
878 Some(Ordering::Equal) => {}
879 non_eq => return non_eq,
880 }
881 }
882 a.len().partial_cmp(&b.len())
883 }
884
885 _ => None,
887 }
888 }
889}
890
891#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
897pub struct ValueEnum {
898 variant: String,
899 path: Option<String>,
900 payload: Option<Box<Value>>,
901}
902
903impl ValueEnum {
904 #[must_use]
906 pub fn new(variant: &str, path: Option<&str>) -> Self {
907 Self {
908 variant: variant.to_string(),
909 path: path.map(ToString::to_string),
910 payload: None,
911 }
912 }
913
914 #[must_use]
916 pub fn strict<E: Path>(variant: &str) -> Self {
917 Self::new(variant, Some(E::PATH))
918 }
919
920 #[must_use]
922 pub fn from_enum<E: EnumValue>(value: E) -> Self {
923 value.to_value_enum()
924 }
925
926 #[must_use]
929 pub fn loose(variant: &str) -> Self {
930 Self::new(variant, None)
931 }
932
933 #[must_use]
935 pub fn with_payload(mut self, payload: Value) -> Self {
936 self.payload = Some(Box::new(payload));
937 self
938 }
939
940 #[must_use]
941 pub fn variant(&self) -> &str {
942 &self.variant
943 }
944
945 #[must_use]
946 pub fn path(&self) -> Option<&str> {
947 self.path.as_deref()
948 }
949
950 #[must_use]
951 pub fn payload(&self) -> Option<&Value> {
952 self.payload.as_deref()
953 }
954
955 pub(crate) fn set_path(&mut self, path: Option<String>) {
956 self.path = path;
957 }
958}