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 fn normalize_map_entries(
323 mut entries: Vec<(Self, Self)>,
324 ) -> Result<Vec<(Self, Self)>, MapValueError> {
325 Self::validate_map_entries(&entries)?;
326 entries
327 .sort_by(|(left_key, _), (right_key, _)| Self::canonical_cmp_key(left_key, right_key));
328
329 for i in 1..entries.len() {
330 let (left_key, _) = &entries[i - 1];
331 let (right_key, _) = &entries[i];
332 if Self::canonical_cmp_key(left_key, right_key) == Ordering::Equal {
333 return Err(MapValueError::DuplicateKey {
334 left_index: i - 1,
335 right_index: i,
336 });
337 }
338 }
339
340 Ok(entries)
341 }
342
343 pub fn from_enum<E: EnumValue>(value: E) -> Self {
345 Self::Enum(value.to_value_enum())
346 }
347
348 #[must_use]
350 pub fn enum_strict<E: Path>(variant: &str) -> Self {
351 Self::Enum(ValueEnum::strict::<E>(variant))
352 }
353
354 #[must_use]
361 pub const fn is_numeric(&self) -> bool {
362 scalar_registry!(value_is_numeric_from_registry, self)
363 }
364
365 #[must_use]
367 pub const fn supports_numeric_coercion(&self) -> bool {
368 scalar_registry!(value_supports_numeric_coercion_from_registry, self)
369 }
370
371 #[must_use]
373 pub const fn is_text(&self) -> bool {
374 matches!(self, Self::Text(_))
375 }
376
377 #[must_use]
379 pub const fn is_unit(&self) -> bool {
380 matches!(self, Self::Unit)
381 }
382
383 #[must_use]
384 pub const fn is_scalar(&self) -> bool {
385 match self {
386 Self::List(_) | Self::Map(_) | Self::Unit => false,
388 _ => true,
389 }
390 }
391
392 #[must_use]
394 pub(crate) const fn canonical_tag(&self) -> ValueTag {
395 tag::canonical_tag(self)
396 }
397
398 #[must_use]
400 pub(crate) const fn canonical_rank(&self) -> u8 {
401 rank::canonical_rank(self)
402 }
403
404 #[must_use]
406 pub(crate) fn canonical_cmp(left: &Self, right: &Self) -> Ordering {
407 compare::canonical_cmp(left, right)
408 }
409
410 #[must_use]
412 pub fn canonical_cmp_key(left: &Self, right: &Self) -> Ordering {
413 compare::canonical_cmp_key(left, right)
414 }
415
416 #[must_use]
421 pub(crate) fn canonical_cmp_map_entry(
422 left_key: &Self,
423 left_value: &Self,
424 right_key: &Self,
425 right_value: &Self,
426 ) -> Ordering {
427 Self::canonical_cmp_key(left_key, right_key)
428 .then_with(|| Self::canonical_cmp(left_value, right_value))
429 }
430
431 #[must_use]
435 pub(crate) fn strict_order_cmp(left: &Self, right: &Self) -> Option<Ordering> {
436 compare::strict_order_cmp(left, right)
437 }
438
439 fn numeric_repr(&self) -> NumericRepr {
440 if !self.supports_numeric_coercion() {
442 return NumericRepr::None;
443 }
444
445 if let Some(d) = self.to_decimal() {
446 return NumericRepr::Decimal(d);
447 }
448 if let Some(f) = self.to_f64_lossless() {
449 return NumericRepr::F64(f);
450 }
451 NumericRepr::None
452 }
453
454 #[must_use]
463 pub const fn as_storage_key(&self) -> Option<StorageKey> {
464 scalar_registry!(value_storage_key_from_registry, self)
465 }
466
467 #[must_use]
468 pub const fn as_text(&self) -> Option<&str> {
469 if let Self::Text(s) = self {
470 Some(s.as_str())
471 } else {
472 None
473 }
474 }
475
476 #[must_use]
477 pub const fn as_list(&self) -> Option<&[Self]> {
478 if let Self::List(xs) = self {
479 Some(xs.as_slice())
480 } else {
481 None
482 }
483 }
484
485 #[must_use]
486 pub const fn as_map(&self) -> Option<&[(Self, Self)]> {
487 if let Self::Map(entries) = self {
488 Some(entries.as_slice())
489 } else {
490 None
491 }
492 }
493
494 fn to_decimal(&self) -> Option<Decimal> {
495 match self {
496 Self::Decimal(d) => Some(*d),
497 Self::Duration(d) => Decimal::from_u64(d.repr()),
498 Self::Float64(f) => Decimal::from_f64(f.get()),
499 Self::Float32(f) => Decimal::from_f32(f.get()),
500 Self::Int(i) => Decimal::from_i64(*i),
501 Self::Int128(i) => Decimal::from_i128(i.get()),
502 Self::IntBig(i) => i.to_i128().and_then(Decimal::from_i128),
503 Self::Timestamp(t) => Decimal::from_i64(t.repr()),
504 Self::Uint(u) => Decimal::from_u64(*u),
505 Self::Uint128(u) => Decimal::from_u128(u.get()),
506 Self::UintBig(u) => u.to_u128().and_then(Decimal::from_u128),
507
508 _ => None,
509 }
510 }
511
512 pub(crate) fn to_numeric_decimal(&self) -> Option<Decimal> {
514 self.to_decimal()
515 }
516
517 #[expect(clippy::cast_precision_loss)]
519 fn to_f64_lossless(&self) -> Option<f64> {
520 match self {
521 Self::Duration(d) if d.repr() <= F64_SAFE_U64 => Some(d.repr() as f64),
522 Self::Float64(f) => Some(f.get()),
523 Self::Float32(f) => Some(f64::from(f.get())),
524 Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
525 Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
526 Some(i.get() as f64)
527 }
528 Self::IntBig(i) => i.to_i128().and_then(|v| {
529 (-F64_SAFE_I128..=F64_SAFE_I128)
530 .contains(&v)
531 .then_some(v as f64)
532 }),
533 Self::Timestamp(t) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(&t.repr()) => {
534 Some(t.repr() as f64)
535 }
536 Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
537 Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
538 Self::UintBig(u) => u
539 .to_u128()
540 .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
541
542 _ => None,
543 }
544 }
545
546 #[must_use]
548 pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
549 if !self.supports_numeric_coercion() || !other.supports_numeric_coercion() {
550 return None;
551 }
552
553 match (self.numeric_repr(), other.numeric_repr()) {
554 (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
555 (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
556 _ => None,
557 }
558 }
559
560 fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
565 if s.is_ascii() {
566 return std::borrow::Cow::Owned(s.to_ascii_lowercase());
567 }
568 std::borrow::Cow::Owned(s.to_lowercase())
571 }
572
573 fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
574 match mode {
575 TextMode::Cs => std::borrow::Cow::Borrowed(s),
576 TextMode::Ci => Self::fold_ci(s),
577 }
578 }
579
580 fn text_op(
581 &self,
582 other: &Self,
583 mode: TextMode,
584 f: impl Fn(&str, &str) -> bool,
585 ) -> Option<bool> {
586 let (a, b) = (self.as_text()?, other.as_text()?);
587 let a = Self::text_with_mode(a, mode);
588 let b = Self::text_with_mode(b, mode);
589 Some(f(&a, &b))
590 }
591
592 fn ci_key(&self) -> Option<String> {
593 match self {
594 Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
595 Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
596 Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
597 Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
598 _ => None,
599 }
600 }
601
602 fn eq_ci(a: &Self, b: &Self) -> bool {
603 if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
604 return ak == bk;
605 }
606
607 a == b
608 }
609
610 fn normalize_list_ref(v: &Self) -> Vec<&Self> {
611 match v {
612 Self::List(vs) => vs.iter().collect(),
613 v => vec![v],
614 }
615 }
616
617 fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
618 where
619 F: Fn(&Self, &Self) -> bool,
620 {
621 self.as_list()
622 .map(|items| items.iter().any(|v| eq(v, needle)))
623 }
624
625 #[expect(clippy::unnecessary_wraps)]
626 fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
627 where
628 F: Fn(&Self, &Self) -> bool,
629 {
630 let needles = Self::normalize_list_ref(needles);
631 match self {
632 Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
633 scalar => Some(needles.iter().any(|n| eq(scalar, n))),
634 }
635 }
636
637 #[expect(clippy::unnecessary_wraps)]
638 fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
639 where
640 F: Fn(&Self, &Self) -> bool,
641 {
642 let needles = Self::normalize_list_ref(needles);
643 match self {
644 Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
645 scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
646 }
647 }
648
649 fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
650 where
651 F: Fn(&Self, &Self) -> bool,
652 {
653 if let Self::List(items) = haystack {
654 Some(items.iter().any(|h| eq(h, self)))
655 } else {
656 None
657 }
658 }
659
660 #[must_use]
662 pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
663 self.text_op(other, mode, |a, b| a == b)
664 }
665
666 #[must_use]
668 pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
669 self.text_op(needle, mode, |a, b| a.contains(b))
670 }
671
672 #[must_use]
674 pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
675 self.text_op(needle, mode, |a, b| a.starts_with(b))
676 }
677
678 #[must_use]
680 pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
681 self.text_op(needle, mode, |a, b| a.ends_with(b))
682 }
683
684 #[must_use]
689 pub const fn is_empty(&self) -> Option<bool> {
690 match self {
691 Self::List(xs) => Some(xs.is_empty()),
692 Self::Map(entries) => Some(entries.is_empty()),
693 Self::Text(s) => Some(s.is_empty()),
694 Self::Blob(b) => Some(b.is_empty()),
695
696 Self::Null => Some(true),
698
699 _ => None,
700 }
701 }
702
703 #[must_use]
705 pub fn is_not_empty(&self) -> Option<bool> {
706 self.is_empty().map(|b| !b)
707 }
708
709 #[must_use]
715 pub fn contains(&self, needle: &Self) -> Option<bool> {
716 self.contains_by(needle, |a, b| a == b)
717 }
718
719 #[must_use]
721 pub fn contains_any(&self, needles: &Self) -> Option<bool> {
722 self.contains_any_by(needles, |a, b| a == b)
723 }
724
725 #[must_use]
727 pub fn contains_all(&self, needles: &Self) -> Option<bool> {
728 self.contains_all_by(needles, |a, b| a == b)
729 }
730
731 #[must_use]
733 pub fn in_list(&self, haystack: &Self) -> Option<bool> {
734 self.in_list_by(haystack, |a, b| a == b)
735 }
736
737 #[must_use]
739 pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
740 match self {
741 Self::List(_) => self.contains_by(needle, Self::eq_ci),
742 _ => Some(Self::eq_ci(self, needle)),
743 }
744 }
745
746 #[must_use]
748 pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
749 self.contains_any_by(needles, Self::eq_ci)
750 }
751
752 #[must_use]
754 pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
755 self.contains_all_by(needles, Self::eq_ci)
756 }
757
758 #[must_use]
760 pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
761 self.in_list_by(haystack, Self::eq_ci)
762 }
763}
764
765impl FieldValue for Value {
766 fn kind() -> crate::traits::FieldValueKind {
767 crate::traits::FieldValueKind::Atomic
768 }
769
770 fn to_value(&self) -> Value {
771 self.clone()
772 }
773
774 fn from_value(value: &Value) -> Option<Self> {
775 Some(value.clone())
776 }
777}
778
779#[macro_export]
780macro_rules! impl_from_for {
781 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
782 $(
783 impl From<$type> for Value {
784 fn from(v: $type) -> Self {
785 Self::$variant(v.into())
786 }
787 }
788 )*
789 };
790}
791
792impl_from_for! {
793 Account => Account,
794 Date => Date,
795 Decimal => Decimal,
796 Duration => Duration,
797 bool => Bool,
798 i8 => Int,
799 i16 => Int,
800 i32 => Int,
801 i64 => Int,
802 i128 => Int128,
803 Int => IntBig,
804 Principal => Principal,
805 Subaccount => Subaccount,
806 &str => Text,
807 String => Text,
808 Timestamp => Timestamp,
809 u8 => Uint,
810 u16 => Uint,
811 u32 => Uint,
812 u64 => Uint,
813 u128 => Uint128,
814 Nat => UintBig,
815 Ulid => Ulid,
816}
817
818impl CoercionFamilyExt for Value {
819 fn coercion_family(&self) -> CoercionFamily {
825 scalar_registry!(value_coercion_family_from_registry, self)
826 }
827}
828
829impl From<Vec<Self>> for Value {
830 fn from(vec: Vec<Self>) -> Self {
831 Self::List(vec)
832 }
833}
834
835impl TryFrom<Vec<(Self, Self)>> for Value {
836 type Error = SchemaInvariantError;
837
838 fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
839 Self::from_map(entries).map_err(Self::Error::from)
840 }
841}
842
843impl From<()> for Value {
844 fn from((): ()) -> Self {
845 Self::Unit
846 }
847}
848
849impl PartialOrd for Value {
855 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
856 match (self, other) {
857 (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
858 (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
859 (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
860 (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
861 (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
862 (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
863 (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
864 (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
865 (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
866 (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
867 (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
868 (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
869 (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
870 (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
871 (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
872 (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
873 (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
874 (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
875 (Self::Map(a), Self::Map(b)) => {
876 for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
877 let key_cmp = Self::canonical_cmp_key(left_key, right_key);
878 if key_cmp != Ordering::Equal {
879 return Some(key_cmp);
880 }
881
882 match left_value.partial_cmp(right_value) {
883 Some(Ordering::Equal) => {}
884 non_eq => return non_eq,
885 }
886 }
887 a.len().partial_cmp(&b.len())
888 }
889
890 _ => None,
892 }
893 }
894}
895
896#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
902pub struct ValueEnum {
903 variant: String,
904 path: Option<String>,
905 payload: Option<Box<Value>>,
906}
907
908impl ValueEnum {
909 #[must_use]
911 pub fn new(variant: &str, path: Option<&str>) -> Self {
912 Self {
913 variant: variant.to_string(),
914 path: path.map(ToString::to_string),
915 payload: None,
916 }
917 }
918
919 #[must_use]
921 pub fn strict<E: Path>(variant: &str) -> Self {
922 Self::new(variant, Some(E::PATH))
923 }
924
925 #[must_use]
927 pub fn from_enum<E: EnumValue>(value: E) -> Self {
928 value.to_value_enum()
929 }
930
931 #[must_use]
934 pub fn loose(variant: &str) -> Self {
935 Self::new(variant, None)
936 }
937
938 #[must_use]
940 pub fn with_payload(mut self, payload: Value) -> Self {
941 self.payload = Some(Box::new(payload));
942 self
943 }
944
945 #[must_use]
946 pub fn variant(&self) -> &str {
947 &self.variant
948 }
949
950 #[must_use]
951 pub fn path(&self) -> Option<&str> {
952 self.path.as_deref()
953 }
954
955 #[must_use]
956 pub fn payload(&self) -> Option<&Value> {
957 self.payload.as_deref()
958 }
959
960 pub(crate) fn set_path(&mut self, path: Option<String>) {
961 self.path = path;
962 }
963}