1mod coercion;
2mod compare;
3mod rank;
4mod tag;
5mod wire;
6
7#[cfg(test)]
8mod tests;
9
10use crate::{
11 db::StorageKey,
12 prelude::*,
13 traits::{EnumValue, FieldValue, NumFromPrimitive},
14 types::*,
15};
16use candid::CandidType;
17use serde::{Deserialize, Serialize};
18use std::cmp::Ordering;
19
20pub use coercion::{CoercionFamily, CoercionFamilyExt};
22pub use tag::ValueTag;
23
24const F64_SAFE_I64: i64 = 1i64 << 53;
29const F64_SAFE_U64: u64 = 1u64 << 53;
30const F64_SAFE_I128: i128 = 1i128 << 53;
31const F64_SAFE_U128: u128 = 1u128 << 53;
32
33enum NumericRepr {
38 Decimal(Decimal),
39 F64(f64),
40 None,
41}
42
43#[derive(Clone, Copy, Debug, Eq, PartialEq)]
48pub enum TextMode {
49 Cs, Ci, }
52
53#[derive(Clone, Debug, Eq, PartialEq)]
60pub enum MapValueError {
61 EmptyKey {
62 index: usize,
63 },
64 NonScalarKey {
65 index: usize,
66 key: Value,
67 },
68 NonScalarValue {
69 index: usize,
70 value: Value,
71 },
72 DuplicateKey {
73 left_index: usize,
74 right_index: usize,
75 },
76}
77
78impl std::fmt::Display for MapValueError {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 match self {
81 Self::EmptyKey { index } => write!(f, "map key at index {index} must be non-null"),
82 Self::NonScalarKey { index, key } => {
83 write!(f, "map key at index {index} is not scalar: {key:?}")
84 }
85 Self::NonScalarValue { index, value } => {
86 write!(
87 f,
88 "map value at index {index} is not scalar/ref-like: {value:?}"
89 )
90 }
91 Self::DuplicateKey {
92 left_index,
93 right_index,
94 } => write!(
95 f,
96 "map contains duplicate keys at normalized positions {left_index} and {right_index}"
97 ),
98 }
99 }
100}
101
102impl std::error::Error for MapValueError {}
103
104#[derive(Clone, Debug, Eq, PartialEq)]
111pub enum SchemaInvariantError {
112 InvalidMapValue(MapValueError),
113}
114
115impl std::fmt::Display for SchemaInvariantError {
116 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117 match self {
118 Self::InvalidMapValue(err) => write!(f, "{err}"),
119 }
120 }
121}
122
123impl std::error::Error for SchemaInvariantError {}
124
125impl From<MapValueError> for SchemaInvariantError {
126 fn from(value: MapValueError) -> Self {
127 Self::InvalidMapValue(value)
128 }
129}
130
131#[derive(CandidType, Clone, Debug, Eq, PartialEq, Serialize)]
140pub enum Value {
141 Account(Account),
142 Blob(Vec<u8>),
143 Bool(bool),
144 Date(Date),
145 Decimal(Decimal),
146 Duration(Duration),
147 Enum(ValueEnum),
148 Float32(Float32),
149 Float64(Float64),
150 Int(i64),
151 Int128(Int128),
152 IntBig(Int),
153 List(Vec<Self>),
157 Map(Vec<(Self, Self)>),
164 Null,
165 Principal(Principal),
166 Subaccount(Subaccount),
167 Text(String),
168 Timestamp(Timestamp),
169 Uint(u64),
170 Uint128(Nat128),
171 UintBig(Nat),
172 Ulid(Ulid),
173 Unit,
174}
175
176macro_rules! value_is_numeric_from_registry {
178 ( @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) ),* $(,)? ) => {
179 match $value {
180 $( $value_pat => $is_numeric, )*
181 _ => false,
182 }
183 };
184}
185
186macro_rules! value_supports_numeric_coercion_from_registry {
187 ( @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) ),* $(,)? ) => {
188 match $value {
189 $( $value_pat => $supports_numeric_coercion, )*
190 _ => false,
191 }
192 };
193}
194
195macro_rules! value_storage_key_case {
196 ( $value:expr, Unit, true ) => {
197 if let Value::Unit = $value {
198 Some(StorageKey::Unit)
199 } else {
200 None
201 }
202 };
203 ( $value:expr, $scalar:ident, true ) => {
204 if let Value::$scalar(v) = $value {
205 Some(StorageKey::$scalar(*v))
206 } else {
207 None
208 }
209 };
210 ( $value:expr, $scalar:ident, false ) => {
211 None
212 };
213}
214
215macro_rules! value_storage_key_from_registry {
216 ( @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) ),* $(,)? ) => {
217 {
218 let mut key = None;
219 $(
220 match key {
221 Some(_) => {}
222 None => {
223 key = value_storage_key_case!($value, $scalar, $is_storage_key_encodable);
224 }
225 }
226 )*
227 key
228 }
229 };
230}
231
232macro_rules! value_coercion_family_from_registry {
233 ( @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) ),* $(,)? ) => {
234 match $value {
235 $( $value_pat => $coercion_family, )*
236 Value::List(_) => CoercionFamily::Collection,
237 Value::Map(_) => CoercionFamily::Collection,
238 Value::Null => CoercionFamily::Null,
239 }
240 };
241}
242
243impl Value {
244 pub fn from_slice<T>(items: &[T]) -> Self
253 where
254 T: Into<Self> + Clone,
255 {
256 Self::List(items.iter().cloned().map(Into::into).collect())
257 }
258
259 pub fn from_list<T>(items: Vec<T>) -> Self
263 where
264 T: Into<Self>,
265 {
266 Self::List(items.into_iter().map(Into::into).collect())
267 }
268
269 pub fn from_map(entries: Vec<(Self, Self)>) -> Result<Self, MapValueError> {
277 let normalized = Self::normalize_map_entries(entries)?;
278 Ok(Self::Map(normalized))
279 }
280
281 pub fn validate_map_entries(entries: &[(Self, Self)]) -> Result<(), MapValueError> {
283 for (index, (key, value)) in entries.iter().enumerate() {
284 if matches!(key, Self::Null) {
285 return Err(MapValueError::EmptyKey { index });
286 }
287 if !key.is_scalar() {
288 return Err(MapValueError::NonScalarKey {
289 index,
290 key: key.clone(),
291 });
292 }
293
294 if !value.is_scalar() {
295 return Err(MapValueError::NonScalarValue {
296 index,
297 value: value.clone(),
298 });
299 }
300 }
301
302 Ok(())
303 }
304
305 pub fn normalize_map_entries(
307 mut entries: Vec<(Self, Self)>,
308 ) -> Result<Vec<(Self, Self)>, MapValueError> {
309 Self::validate_map_entries(&entries)?;
310 entries
311 .sort_by(|(left_key, _), (right_key, _)| Self::canonical_cmp_key(left_key, right_key));
312
313 for i in 1..entries.len() {
314 let (left_key, _) = &entries[i - 1];
315 let (right_key, _) = &entries[i];
316 if Self::canonical_cmp_key(left_key, right_key) == Ordering::Equal {
317 return Err(MapValueError::DuplicateKey {
318 left_index: i - 1,
319 right_index: i,
320 });
321 }
322 }
323
324 Ok(entries)
325 }
326
327 pub fn from_enum<E: EnumValue>(value: E) -> Self {
329 Self::Enum(value.to_value_enum())
330 }
331
332 #[must_use]
334 pub fn enum_strict<E: Path>(variant: &str) -> Self {
335 Self::Enum(ValueEnum::strict::<E>(variant))
336 }
337
338 #[must_use]
345 pub const fn is_numeric(&self) -> bool {
346 scalar_registry!(value_is_numeric_from_registry, self)
347 }
348
349 #[must_use]
351 pub const fn supports_numeric_coercion(&self) -> bool {
352 scalar_registry!(value_supports_numeric_coercion_from_registry, self)
353 }
354
355 #[must_use]
357 pub const fn is_text(&self) -> bool {
358 matches!(self, Self::Text(_))
359 }
360
361 #[must_use]
363 pub const fn is_unit(&self) -> bool {
364 matches!(self, Self::Unit)
365 }
366
367 #[must_use]
368 pub const fn is_scalar(&self) -> bool {
369 match self {
370 Self::List(_) | Self::Map(_) | Self::Unit => false,
372 _ => true,
373 }
374 }
375
376 #[must_use]
378 pub(crate) const fn canonical_tag(&self) -> ValueTag {
379 tag::canonical_tag(self)
380 }
381
382 #[must_use]
384 pub(crate) const fn canonical_rank(&self) -> u8 {
385 rank::canonical_rank(self)
386 }
387
388 #[must_use]
390 pub(crate) fn canonical_cmp(left: &Self, right: &Self) -> Ordering {
391 compare::canonical_cmp(left, right)
392 }
393
394 #[must_use]
396 pub fn canonical_cmp_key(left: &Self, right: &Self) -> Ordering {
397 compare::canonical_cmp_key(left, right)
398 }
399
400 #[must_use]
404 pub(crate) fn strict_order_cmp(left: &Self, right: &Self) -> Option<Ordering> {
405 compare::strict_order_cmp(left, right)
406 }
407
408 fn numeric_repr(&self) -> NumericRepr {
409 if !self.supports_numeric_coercion() {
411 return NumericRepr::None;
412 }
413
414 if let Some(d) = self.to_decimal() {
415 return NumericRepr::Decimal(d);
416 }
417 if let Some(f) = self.to_f64_lossless() {
418 return NumericRepr::F64(f);
419 }
420 NumericRepr::None
421 }
422
423 #[must_use]
432 pub const fn as_storage_key(&self) -> Option<StorageKey> {
433 scalar_registry!(value_storage_key_from_registry, self)
434 }
435
436 #[must_use]
437 pub const fn as_text(&self) -> Option<&str> {
438 if let Self::Text(s) = self {
439 Some(s.as_str())
440 } else {
441 None
442 }
443 }
444
445 #[must_use]
446 pub const fn as_list(&self) -> Option<&[Self]> {
447 if let Self::List(xs) = self {
448 Some(xs.as_slice())
449 } else {
450 None
451 }
452 }
453
454 #[must_use]
455 pub const fn as_map(&self) -> Option<&[(Self, Self)]> {
456 if let Self::Map(entries) = self {
457 Some(entries.as_slice())
458 } else {
459 None
460 }
461 }
462
463 fn to_decimal(&self) -> Option<Decimal> {
464 match self {
465 Self::Decimal(d) => Some(*d),
466 Self::Duration(d) => Decimal::from_u64(d.repr()),
467 Self::Float64(f) => Decimal::from_f64(f.get()),
468 Self::Float32(f) => Decimal::from_f32(f.get()),
469 Self::Int(i) => Decimal::from_i64(*i),
470 Self::Int128(i) => Decimal::from_i128(i.get()),
471 Self::IntBig(i) => i.to_i128().and_then(Decimal::from_i128),
472 Self::Timestamp(t) => Decimal::from_u64(t.repr()),
473 Self::Uint(u) => Decimal::from_u64(*u),
474 Self::Uint128(u) => Decimal::from_u128(u.get()),
475 Self::UintBig(u) => u.to_u128().and_then(Decimal::from_u128),
476
477 _ => None,
478 }
479 }
480
481 #[expect(clippy::cast_precision_loss)]
483 fn to_f64_lossless(&self) -> Option<f64> {
484 match self {
485 Self::Duration(d) if d.repr() <= F64_SAFE_U64 => Some(d.repr() as f64),
486 Self::Float64(f) => Some(f.get()),
487 Self::Float32(f) => Some(f64::from(f.get())),
488 Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
489 Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
490 Some(i.get() as f64)
491 }
492 Self::IntBig(i) => i.to_i128().and_then(|v| {
493 (-F64_SAFE_I128..=F64_SAFE_I128)
494 .contains(&v)
495 .then_some(v as f64)
496 }),
497 Self::Timestamp(t) if t.repr() <= F64_SAFE_U64 => Some(t.repr() as f64),
498 Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
499 Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
500 Self::UintBig(u) => u
501 .to_u128()
502 .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
503
504 _ => None,
505 }
506 }
507
508 #[must_use]
510 pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
511 if !self.supports_numeric_coercion() || !other.supports_numeric_coercion() {
512 return None;
513 }
514
515 match (self.numeric_repr(), other.numeric_repr()) {
516 (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
517 (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
518 _ => None,
519 }
520 }
521
522 fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
527 if s.is_ascii() {
528 return std::borrow::Cow::Owned(s.to_ascii_lowercase());
529 }
530 std::borrow::Cow::Owned(s.to_lowercase())
533 }
534
535 fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
536 match mode {
537 TextMode::Cs => std::borrow::Cow::Borrowed(s),
538 TextMode::Ci => Self::fold_ci(s),
539 }
540 }
541
542 fn text_op(
543 &self,
544 other: &Self,
545 mode: TextMode,
546 f: impl Fn(&str, &str) -> bool,
547 ) -> Option<bool> {
548 let (a, b) = (self.as_text()?, other.as_text()?);
549 let a = Self::text_with_mode(a, mode);
550 let b = Self::text_with_mode(b, mode);
551 Some(f(&a, &b))
552 }
553
554 fn ci_key(&self) -> Option<String> {
555 match self {
556 Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
557 Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
558 Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
559 Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
560 _ => None,
561 }
562 }
563
564 fn eq_ci(a: &Self, b: &Self) -> bool {
565 if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
566 return ak == bk;
567 }
568
569 a == b
570 }
571
572 fn normalize_list_ref(v: &Self) -> Vec<&Self> {
573 match v {
574 Self::List(vs) => vs.iter().collect(),
575 v => vec![v],
576 }
577 }
578
579 fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
580 where
581 F: Fn(&Self, &Self) -> bool,
582 {
583 self.as_list()
584 .map(|items| items.iter().any(|v| eq(v, needle)))
585 }
586
587 #[expect(clippy::unnecessary_wraps)]
588 fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
589 where
590 F: Fn(&Self, &Self) -> bool,
591 {
592 let needles = Self::normalize_list_ref(needles);
593 match self {
594 Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
595 scalar => Some(needles.iter().any(|n| eq(scalar, n))),
596 }
597 }
598
599 #[expect(clippy::unnecessary_wraps)]
600 fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
601 where
602 F: Fn(&Self, &Self) -> bool,
603 {
604 let needles = Self::normalize_list_ref(needles);
605 match self {
606 Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
607 scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
608 }
609 }
610
611 fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
612 where
613 F: Fn(&Self, &Self) -> bool,
614 {
615 if let Self::List(items) = haystack {
616 Some(items.iter().any(|h| eq(h, self)))
617 } else {
618 None
619 }
620 }
621
622 #[must_use]
623 pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
625 self.text_op(other, mode, |a, b| a == b)
626 }
627
628 #[must_use]
629 pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
631 self.text_op(needle, mode, |a, b| a.contains(b))
632 }
633
634 #[must_use]
635 pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
637 self.text_op(needle, mode, |a, b| a.starts_with(b))
638 }
639
640 #[must_use]
641 pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
643 self.text_op(needle, mode, |a, b| a.ends_with(b))
644 }
645
646 #[must_use]
651 pub const fn is_empty(&self) -> Option<bool> {
652 match self {
653 Self::List(xs) => Some(xs.is_empty()),
654 Self::Map(entries) => Some(entries.is_empty()),
655 Self::Text(s) => Some(s.is_empty()),
656 Self::Blob(b) => Some(b.is_empty()),
657
658 Self::Null => Some(true),
660
661 _ => None,
662 }
663 }
664
665 #[must_use]
666 pub fn is_not_empty(&self) -> Option<bool> {
668 self.is_empty().map(|b| !b)
669 }
670
671 #[must_use]
676 pub fn contains(&self, needle: &Self) -> Option<bool> {
678 self.contains_by(needle, |a, b| a == b)
679 }
680
681 #[must_use]
682 pub fn contains_any(&self, needles: &Self) -> Option<bool> {
684 self.contains_any_by(needles, |a, b| a == b)
685 }
686
687 #[must_use]
688 pub fn contains_all(&self, needles: &Self) -> Option<bool> {
690 self.contains_all_by(needles, |a, b| a == b)
691 }
692
693 #[must_use]
694 pub fn in_list(&self, haystack: &Self) -> Option<bool> {
696 self.in_list_by(haystack, |a, b| a == b)
697 }
698
699 #[must_use]
700 pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
702 match self {
703 Self::List(_) => self.contains_by(needle, Self::eq_ci),
704 _ => Some(Self::eq_ci(self, needle)),
705 }
706 }
707
708 #[must_use]
709 pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
711 self.contains_any_by(needles, Self::eq_ci)
712 }
713
714 #[must_use]
715 pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
717 self.contains_all_by(needles, Self::eq_ci)
718 }
719
720 #[must_use]
721 pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
723 self.in_list_by(haystack, Self::eq_ci)
724 }
725}
726
727impl FieldValue for Value {
728 fn kind() -> crate::traits::FieldValueKind {
729 crate::traits::FieldValueKind::Atomic
730 }
731
732 fn to_value(&self) -> Value {
733 self.clone()
734 }
735
736 fn from_value(value: &Value) -> Option<Self> {
737 Some(value.clone())
738 }
739}
740
741#[macro_export]
742macro_rules! impl_from_for {
743 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
744 $(
745 impl From<$type> for Value {
746 fn from(v: $type) -> Self {
747 Self::$variant(v.into())
748 }
749 }
750 )*
751 };
752}
753
754impl_from_for! {
755 Account => Account,
756 Date => Date,
757 Decimal => Decimal,
758 Duration => Duration,
759 bool => Bool,
760 i8 => Int,
761 i16 => Int,
762 i32 => Int,
763 i64 => Int,
764 i128 => Int128,
765 Int => IntBig,
766 Principal => Principal,
767 Subaccount => Subaccount,
768 &str => Text,
769 String => Text,
770 Timestamp => Timestamp,
771 u8 => Uint,
772 u16 => Uint,
773 u32 => Uint,
774 u64 => Uint,
775 u128 => Uint128,
776 Nat => UintBig,
777 Ulid => Ulid,
778}
779
780impl CoercionFamilyExt for Value {
781 fn coercion_family(&self) -> CoercionFamily {
787 scalar_registry!(value_coercion_family_from_registry, self)
788 }
789}
790
791impl From<Vec<Self>> for Value {
792 fn from(vec: Vec<Self>) -> Self {
793 Self::List(vec)
794 }
795}
796
797impl TryFrom<Vec<(Self, Self)>> for Value {
798 type Error = SchemaInvariantError;
799
800 fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
801 Self::from_map(entries).map_err(Self::Error::from)
802 }
803}
804
805impl From<()> for Value {
806 fn from((): ()) -> Self {
807 Self::Unit
808 }
809}
810
811impl PartialOrd for Value {
817 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
818 match (self, other) {
819 (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
820 (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
821 (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
822 (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
823 (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
824 (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
825 (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
826 (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
827 (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
828 (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
829 (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
830 (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
831 (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
832 (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
833 (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
834 (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
835 (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
836 (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
837 (Self::Map(a), Self::Map(b)) => {
838 for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
839 let key_cmp = Self::canonical_cmp_key(left_key, right_key);
840 if key_cmp != Ordering::Equal {
841 return Some(key_cmp);
842 }
843
844 match left_value.partial_cmp(right_value) {
845 Some(Ordering::Equal) => {}
846 non_eq => return non_eq,
847 }
848 }
849 a.len().partial_cmp(&b.len())
850 }
851
852 _ => None,
854 }
855 }
856}
857
858#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
864pub struct ValueEnum {
865 pub variant: String,
866 pub path: Option<String>,
867 pub payload: Option<Box<Value>>,
868}
869
870impl ValueEnum {
871 #[must_use]
872 pub fn new(variant: &str, path: Option<&str>) -> Self {
874 Self {
875 variant: variant.to_string(),
876 path: path.map(ToString::to_string),
877 payload: None,
878 }
879 }
880
881 #[must_use]
882 pub fn strict<E: Path>(variant: &str) -> Self {
884 Self::new(variant, Some(E::PATH))
885 }
886
887 #[must_use]
888 pub fn from_enum<E: EnumValue>(value: E) -> Self {
890 value.to_value_enum()
891 }
892
893 #[must_use]
894 pub fn loose(variant: &str) -> Self {
897 Self::new(variant, None)
898 }
899
900 #[must_use]
901 pub fn with_payload(mut self, payload: Value) -> Self {
903 self.payload = Some(Box::new(payload));
904 self
905 }
906}