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_i64(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 (-F64_SAFE_I64..=F64_SAFE_I64).contains(&t.repr()) => {
522 Some(t.repr() as f64)
523 }
524 Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
525 Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
526 Self::UintBig(u) => u
527 .to_u128()
528 .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
529
530 _ => None,
531 }
532 }
533
534 #[must_use]
536 pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
537 if !self.supports_numeric_coercion() || !other.supports_numeric_coercion() {
538 return None;
539 }
540
541 match (self.numeric_repr(), other.numeric_repr()) {
542 (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
543 (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
544 _ => None,
545 }
546 }
547
548 fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
553 if s.is_ascii() {
554 return std::borrow::Cow::Owned(s.to_ascii_lowercase());
555 }
556 std::borrow::Cow::Owned(s.to_lowercase())
559 }
560
561 fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
562 match mode {
563 TextMode::Cs => std::borrow::Cow::Borrowed(s),
564 TextMode::Ci => Self::fold_ci(s),
565 }
566 }
567
568 fn text_op(
569 &self,
570 other: &Self,
571 mode: TextMode,
572 f: impl Fn(&str, &str) -> bool,
573 ) -> Option<bool> {
574 let (a, b) = (self.as_text()?, other.as_text()?);
575 let a = Self::text_with_mode(a, mode);
576 let b = Self::text_with_mode(b, mode);
577 Some(f(&a, &b))
578 }
579
580 fn ci_key(&self) -> Option<String> {
581 match self {
582 Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
583 Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
584 Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
585 Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
586 _ => None,
587 }
588 }
589
590 fn eq_ci(a: &Self, b: &Self) -> bool {
591 if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
592 return ak == bk;
593 }
594
595 a == b
596 }
597
598 fn normalize_list_ref(v: &Self) -> Vec<&Self> {
599 match v {
600 Self::List(vs) => vs.iter().collect(),
601 v => vec![v],
602 }
603 }
604
605 fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
606 where
607 F: Fn(&Self, &Self) -> bool,
608 {
609 self.as_list()
610 .map(|items| items.iter().any(|v| eq(v, needle)))
611 }
612
613 #[expect(clippy::unnecessary_wraps)]
614 fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
615 where
616 F: Fn(&Self, &Self) -> bool,
617 {
618 let needles = Self::normalize_list_ref(needles);
619 match self {
620 Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
621 scalar => Some(needles.iter().any(|n| eq(scalar, n))),
622 }
623 }
624
625 #[expect(clippy::unnecessary_wraps)]
626 fn contains_all_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().all(|n| items.iter().any(|v| eq(v, n)))),
633 scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
634 }
635 }
636
637 fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
638 where
639 F: Fn(&Self, &Self) -> bool,
640 {
641 if let Self::List(items) = haystack {
642 Some(items.iter().any(|h| eq(h, self)))
643 } else {
644 None
645 }
646 }
647
648 #[must_use]
650 pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
651 self.text_op(other, mode, |a, b| a == b)
652 }
653
654 #[must_use]
656 pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
657 self.text_op(needle, mode, |a, b| a.contains(b))
658 }
659
660 #[must_use]
662 pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
663 self.text_op(needle, mode, |a, b| a.starts_with(b))
664 }
665
666 #[must_use]
668 pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
669 self.text_op(needle, mode, |a, b| a.ends_with(b))
670 }
671
672 #[must_use]
677 pub const fn is_empty(&self) -> Option<bool> {
678 match self {
679 Self::List(xs) => Some(xs.is_empty()),
680 Self::Map(entries) => Some(entries.is_empty()),
681 Self::Text(s) => Some(s.is_empty()),
682 Self::Blob(b) => Some(b.is_empty()),
683
684 Self::Null => Some(true),
686
687 _ => None,
688 }
689 }
690
691 #[must_use]
693 pub fn is_not_empty(&self) -> Option<bool> {
694 self.is_empty().map(|b| !b)
695 }
696
697 #[must_use]
703 pub fn contains(&self, needle: &Self) -> Option<bool> {
704 self.contains_by(needle, |a, b| a == b)
705 }
706
707 #[must_use]
709 pub fn contains_any(&self, needles: &Self) -> Option<bool> {
710 self.contains_any_by(needles, |a, b| a == b)
711 }
712
713 #[must_use]
715 pub fn contains_all(&self, needles: &Self) -> Option<bool> {
716 self.contains_all_by(needles, |a, b| a == b)
717 }
718
719 #[must_use]
721 pub fn in_list(&self, haystack: &Self) -> Option<bool> {
722 self.in_list_by(haystack, |a, b| a == b)
723 }
724
725 #[must_use]
727 pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
728 match self {
729 Self::List(_) => self.contains_by(needle, Self::eq_ci),
730 _ => Some(Self::eq_ci(self, needle)),
731 }
732 }
733
734 #[must_use]
736 pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
737 self.contains_any_by(needles, Self::eq_ci)
738 }
739
740 #[must_use]
742 pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
743 self.contains_all_by(needles, Self::eq_ci)
744 }
745
746 #[must_use]
748 pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
749 self.in_list_by(haystack, Self::eq_ci)
750 }
751}
752
753impl FieldValue for Value {
754 fn kind() -> crate::traits::FieldValueKind {
755 crate::traits::FieldValueKind::Atomic
756 }
757
758 fn to_value(&self) -> Value {
759 self.clone()
760 }
761
762 fn from_value(value: &Value) -> Option<Self> {
763 Some(value.clone())
764 }
765}
766
767#[macro_export]
768macro_rules! impl_from_for {
769 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
770 $(
771 impl From<$type> for Value {
772 fn from(v: $type) -> Self {
773 Self::$variant(v.into())
774 }
775 }
776 )*
777 };
778}
779
780impl_from_for! {
781 Account => Account,
782 Date => Date,
783 Decimal => Decimal,
784 Duration => Duration,
785 bool => Bool,
786 i8 => Int,
787 i16 => Int,
788 i32 => Int,
789 i64 => Int,
790 i128 => Int128,
791 Int => IntBig,
792 Principal => Principal,
793 Subaccount => Subaccount,
794 &str => Text,
795 String => Text,
796 Timestamp => Timestamp,
797 u8 => Uint,
798 u16 => Uint,
799 u32 => Uint,
800 u64 => Uint,
801 u128 => Uint128,
802 Nat => UintBig,
803 Ulid => Ulid,
804}
805
806impl CoercionFamilyExt for Value {
807 fn coercion_family(&self) -> CoercionFamily {
813 scalar_registry!(value_coercion_family_from_registry, self)
814 }
815}
816
817impl From<Vec<Self>> for Value {
818 fn from(vec: Vec<Self>) -> Self {
819 Self::List(vec)
820 }
821}
822
823impl TryFrom<Vec<(Self, Self)>> for Value {
824 type Error = SchemaInvariantError;
825
826 fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
827 Self::from_map(entries).map_err(Self::Error::from)
828 }
829}
830
831impl From<()> for Value {
832 fn from((): ()) -> Self {
833 Self::Unit
834 }
835}
836
837impl PartialOrd for Value {
843 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
844 match (self, other) {
845 (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
846 (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
847 (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
848 (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
849 (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
850 (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
851 (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
852 (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
853 (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
854 (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
855 (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
856 (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
857 (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
858 (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
859 (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
860 (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
861 (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
862 (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
863 (Self::Map(a), Self::Map(b)) => {
864 for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
865 let key_cmp = Self::canonical_cmp_key(left_key, right_key);
866 if key_cmp != Ordering::Equal {
867 return Some(key_cmp);
868 }
869
870 match left_value.partial_cmp(right_value) {
871 Some(Ordering::Equal) => {}
872 non_eq => return non_eq,
873 }
874 }
875 a.len().partial_cmp(&b.len())
876 }
877
878 _ => None,
880 }
881 }
882}
883
884#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
890pub struct ValueEnum {
891 variant: String,
892 path: Option<String>,
893 payload: Option<Box<Value>>,
894}
895
896impl ValueEnum {
897 #[must_use]
899 pub fn new(variant: &str, path: Option<&str>) -> Self {
900 Self {
901 variant: variant.to_string(),
902 path: path.map(ToString::to_string),
903 payload: None,
904 }
905 }
906
907 #[must_use]
909 pub fn strict<E: Path>(variant: &str) -> Self {
910 Self::new(variant, Some(E::PATH))
911 }
912
913 #[must_use]
915 pub fn from_enum<E: EnumValue>(value: E) -> Self {
916 value.to_value_enum()
917 }
918
919 #[must_use]
922 pub fn loose(variant: &str) -> Self {
923 Self::new(variant, None)
924 }
925
926 #[must_use]
928 pub fn with_payload(mut self, payload: Value) -> Self {
929 self.payload = Some(Box::new(payload));
930 self
931 }
932
933 #[must_use]
934 pub fn variant(&self) -> &str {
935 &self.variant
936 }
937
938 #[must_use]
939 pub fn path(&self) -> Option<&str> {
940 self.path.as_deref()
941 }
942
943 #[must_use]
944 pub fn payload(&self) -> Option<&Value> {
945 self.payload.as_deref()
946 }
947
948 pub(crate) fn set_path(&mut self, path: Option<String>) {
949 self.path = path;
950 }
951}