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