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::{FieldKind, FieldStorageDecode},
20 prelude::*,
21 traits::{EnumValue, FieldTypeMeta, 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 FieldTypeMeta for Value {
189 const KIND: FieldKind = FieldKind::Structured { queryable: false };
190 const STORAGE_DECODE: FieldStorageDecode = FieldStorageDecode::Value;
191}
192
193impl Value {
194 pub const __KIND: FieldKind = FieldKind::Structured { queryable: false };
195 pub const __STORAGE_DECODE: FieldStorageDecode = FieldStorageDecode::Value;
196}
197
198macro_rules! value_is_numeric_from_registry {
200 ( @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) ),* $(,)? ) => {
201 match $value {
202 $( $value_pat => $is_numeric, )*
203 _ => false,
204 }
205 };
206}
207
208macro_rules! value_supports_numeric_coercion_from_registry {
209 ( @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) ),* $(,)? ) => {
210 match $value {
211 $( $value_pat => $supports_numeric_coercion, )*
212 _ => false,
213 }
214 };
215}
216
217macro_rules! value_storage_key_case {
218 ( $value:expr, Unit, true ) => {
219 if let Value::Unit = $value {
220 Some(StorageKey::Unit)
221 } else {
222 None
223 }
224 };
225 ( $value:expr, $scalar:ident, true ) => {
226 if let Value::$scalar(v) = $value {
227 Some(StorageKey::$scalar(*v))
228 } else {
229 None
230 }
231 };
232 ( $value:expr, $scalar:ident, false ) => {
233 None
234 };
235}
236
237macro_rules! value_storage_key_from_registry {
238 ( @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) ),* $(,)? ) => {
239 {
240 let mut key = None;
241 $(
242 match key {
243 Some(_) => {}
244 None => {
245 key = value_storage_key_case!($value, $scalar, $is_storage_key_encodable);
246 }
247 }
248 )*
249 key
250 }
251 };
252}
253
254macro_rules! value_coercion_family_from_registry {
255 ( @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) ),* $(,)? ) => {
256 match $value {
257 $( $value_pat => $coercion_family, )*
258 Value::List(_) => CoercionFamily::Collection,
259 Value::Map(_) => CoercionFamily::Collection,
260 Value::Null => CoercionFamily::Null,
261 }
262 };
263}
264
265impl Value {
266 pub fn from_slice<T>(items: &[T]) -> Self
275 where
276 T: Into<Self> + Clone,
277 {
278 Self::List(items.iter().cloned().map(Into::into).collect())
279 }
280
281 pub fn from_list<T>(items: Vec<T>) -> Self
285 where
286 T: Into<Self>,
287 {
288 Self::List(items.into_iter().map(Into::into).collect())
289 }
290
291 pub fn from_map(entries: Vec<(Self, Self)>) -> Result<Self, MapValueError> {
299 let normalized = Self::normalize_map_entries(entries)?;
300 Ok(Self::Map(normalized))
301 }
302
303 pub fn validate_map_entries(entries: &[(Self, Self)]) -> Result<(), MapValueError> {
305 for (index, (key, _value)) in entries.iter().enumerate() {
306 if matches!(key, Self::Null) {
307 return Err(MapValueError::EmptyKey { index });
308 }
309 if !key.is_scalar() {
310 return Err(MapValueError::NonScalarKey {
311 index,
312 key: key.clone(),
313 });
314 }
315 }
316
317 Ok(())
318 }
319
320 pub(crate) fn compare_map_entry_keys(left: &(Self, Self), right: &(Self, Self)) -> Ordering {
322 Self::canonical_cmp_key(&left.0, &right.0)
323 }
324
325 pub(crate) fn sort_map_entries_in_place(entries: &mut [(Self, Self)]) {
327 entries.sort_by(Self::compare_map_entry_keys);
328 }
329
330 pub(crate) fn map_entries_are_strictly_canonical(entries: &[(Self, Self)]) -> bool {
333 entries.windows(2).all(|pair| {
334 let [left, right] = pair else {
335 return true;
336 };
337
338 Self::compare_map_entry_keys(left, right) == Ordering::Less
339 })
340 }
341
342 pub fn normalize_map_entries(
344 mut entries: Vec<(Self, Self)>,
345 ) -> Result<Vec<(Self, Self)>, MapValueError> {
346 Self::validate_map_entries(&entries)?;
347 Self::sort_map_entries_in_place(entries.as_mut_slice());
348
349 for i in 1..entries.len() {
350 let (left_key, _) = &entries[i - 1];
351 let (right_key, _) = &entries[i];
352 if Self::canonical_cmp_key(left_key, right_key) == Ordering::Equal {
353 return Err(MapValueError::DuplicateKey {
354 left_index: i - 1,
355 right_index: i,
356 });
357 }
358 }
359
360 Ok(entries)
361 }
362
363 pub fn from_enum<E: EnumValue>(value: E) -> Self {
365 Self::Enum(value.to_value_enum())
366 }
367
368 #[must_use]
370 pub fn enum_strict<E: Path>(variant: &str) -> Self {
371 Self::Enum(ValueEnum::strict::<E>(variant))
372 }
373
374 #[must_use]
381 pub const fn is_numeric(&self) -> bool {
382 scalar_registry!(value_is_numeric_from_registry, self)
383 }
384
385 #[must_use]
387 pub const fn supports_numeric_coercion(&self) -> bool {
388 scalar_registry!(value_supports_numeric_coercion_from_registry, self)
389 }
390
391 #[must_use]
393 pub const fn is_text(&self) -> bool {
394 matches!(self, Self::Text(_))
395 }
396
397 #[must_use]
399 pub const fn is_unit(&self) -> bool {
400 matches!(self, Self::Unit)
401 }
402
403 #[must_use]
404 pub const fn is_scalar(&self) -> bool {
405 match self {
406 Self::List(_) | Self::Map(_) | Self::Unit => false,
408 _ => true,
409 }
410 }
411
412 #[must_use]
414 pub(crate) const fn canonical_tag(&self) -> ValueTag {
415 tag::canonical_tag(self)
416 }
417
418 #[must_use]
420 pub(crate) const fn canonical_rank(&self) -> u8 {
421 rank::canonical_rank(self)
422 }
423
424 #[must_use]
426 pub(crate) fn canonical_cmp(left: &Self, right: &Self) -> Ordering {
427 compare::canonical_cmp(left, right)
428 }
429
430 #[must_use]
432 pub fn canonical_cmp_key(left: &Self, right: &Self) -> Ordering {
433 compare::canonical_cmp_key(left, right)
434 }
435
436 #[must_use]
441 pub(crate) fn canonical_cmp_map_entry(
442 left_key: &Self,
443 left_value: &Self,
444 right_key: &Self,
445 right_value: &Self,
446 ) -> Ordering {
447 Self::canonical_cmp_key(left_key, right_key)
448 .then_with(|| Self::canonical_cmp(left_value, right_value))
449 }
450
451 #[must_use]
454 pub(crate) fn ordered_map_entries(entries: &[(Self, Self)]) -> Vec<&(Self, Self)> {
455 let mut ordered = entries.iter().collect::<Vec<_>>();
456 ordered.sort_by(|left, right| {
457 Self::canonical_cmp_map_entry(&left.0, &left.1, &right.0, &right.1)
458 });
459
460 ordered
461 }
462
463 #[must_use]
467 pub(crate) fn strict_order_cmp(left: &Self, right: &Self) -> Option<Ordering> {
468 compare::strict_order_cmp(left, right)
469 }
470
471 fn numeric_repr(&self) -> NumericRepr {
472 if !self.supports_numeric_coercion() {
474 return NumericRepr::None;
475 }
476
477 if let Some(d) = self.to_decimal() {
478 return NumericRepr::Decimal(d);
479 }
480 if let Some(f) = self.to_f64_lossless() {
481 return NumericRepr::F64(f);
482 }
483 NumericRepr::None
484 }
485
486 #[must_use]
495 pub const fn as_storage_key(&self) -> Option<StorageKey> {
496 scalar_registry!(value_storage_key_from_registry, self)
497 }
498
499 #[must_use]
500 pub const fn as_text(&self) -> Option<&str> {
501 if let Self::Text(s) = self {
502 Some(s.as_str())
503 } else {
504 None
505 }
506 }
507
508 #[must_use]
509 pub const fn as_list(&self) -> Option<&[Self]> {
510 if let Self::List(xs) = self {
511 Some(xs.as_slice())
512 } else {
513 None
514 }
515 }
516
517 #[must_use]
518 pub const fn as_map(&self) -> Option<&[(Self, Self)]> {
519 if let Self::Map(entries) = self {
520 Some(entries.as_slice())
521 } else {
522 None
523 }
524 }
525
526 fn to_decimal(&self) -> Option<Decimal> {
527 match self {
528 Self::Decimal(d) => Some(*d),
529 Self::Duration(d) => Decimal::from_u64(d.repr()),
530 Self::Float64(f) => Decimal::from_f64(f.get()),
531 Self::Float32(f) => Decimal::from_f32(f.get()),
532 Self::Int(i) => Decimal::from_i64(*i),
533 Self::Int128(i) => Decimal::from_i128(i.get()),
534 Self::IntBig(i) => i.to_i128().and_then(Decimal::from_i128),
535 Self::Timestamp(t) => Decimal::from_i64(t.repr()),
536 Self::Uint(u) => Decimal::from_u64(*u),
537 Self::Uint128(u) => Decimal::from_u128(u.get()),
538 Self::UintBig(u) => u.to_u128().and_then(Decimal::from_u128),
539
540 _ => None,
541 }
542 }
543
544 pub(crate) fn to_numeric_decimal(&self) -> Option<Decimal> {
546 self.to_decimal()
547 }
548
549 #[expect(clippy::cast_precision_loss)]
551 fn to_f64_lossless(&self) -> Option<f64> {
552 match self {
553 Self::Duration(d) if d.repr() <= F64_SAFE_U64 => Some(d.repr() as f64),
554 Self::Float64(f) => Some(f.get()),
555 Self::Float32(f) => Some(f64::from(f.get())),
556 Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
557 Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
558 Some(i.get() as f64)
559 }
560 Self::IntBig(i) => i.to_i128().and_then(|v| {
561 (-F64_SAFE_I128..=F64_SAFE_I128)
562 .contains(&v)
563 .then_some(v as f64)
564 }),
565 Self::Timestamp(t) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(&t.repr()) => {
566 Some(t.repr() as f64)
567 }
568 Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
569 Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
570 Self::UintBig(u) => u
571 .to_u128()
572 .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
573
574 _ => None,
575 }
576 }
577
578 #[must_use]
580 pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
581 if !self.supports_numeric_coercion() || !other.supports_numeric_coercion() {
582 return None;
583 }
584
585 match (self.numeric_repr(), other.numeric_repr()) {
586 (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
587 (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
588 _ => None,
589 }
590 }
591
592 fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
597 if s.is_ascii() {
598 return std::borrow::Cow::Owned(s.to_ascii_lowercase());
599 }
600 std::borrow::Cow::Owned(s.to_lowercase())
603 }
604
605 fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
606 match mode {
607 TextMode::Cs => std::borrow::Cow::Borrowed(s),
608 TextMode::Ci => Self::fold_ci(s),
609 }
610 }
611
612 fn text_op(
613 &self,
614 other: &Self,
615 mode: TextMode,
616 f: impl Fn(&str, &str) -> bool,
617 ) -> Option<bool> {
618 let (a, b) = (self.as_text()?, other.as_text()?);
619 let a = Self::text_with_mode(a, mode);
620 let b = Self::text_with_mode(b, mode);
621 Some(f(&a, &b))
622 }
623
624 fn ci_key(&self) -> Option<String> {
625 match self {
626 Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
627 Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
628 Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
629 Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
630 _ => None,
631 }
632 }
633
634 fn eq_ci(a: &Self, b: &Self) -> bool {
635 if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
636 return ak == bk;
637 }
638
639 a == b
640 }
641
642 fn normalize_list_ref(v: &Self) -> Vec<&Self> {
643 match v {
644 Self::List(vs) => vs.iter().collect(),
645 v => vec![v],
646 }
647 }
648
649 fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
650 where
651 F: Fn(&Self, &Self) -> bool,
652 {
653 self.as_list()
654 .map(|items| items.iter().any(|v| eq(v, needle)))
655 }
656
657 #[expect(clippy::unnecessary_wraps)]
658 fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
659 where
660 F: Fn(&Self, &Self) -> bool,
661 {
662 let needles = Self::normalize_list_ref(needles);
663 match self {
664 Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
665 scalar => Some(needles.iter().any(|n| eq(scalar, n))),
666 }
667 }
668
669 #[expect(clippy::unnecessary_wraps)]
670 fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
671 where
672 F: Fn(&Self, &Self) -> bool,
673 {
674 let needles = Self::normalize_list_ref(needles);
675 match self {
676 Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
677 scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
678 }
679 }
680
681 fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
682 where
683 F: Fn(&Self, &Self) -> bool,
684 {
685 if let Self::List(items) = haystack {
686 Some(items.iter().any(|h| eq(h, self)))
687 } else {
688 None
689 }
690 }
691
692 #[must_use]
694 pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
695 self.text_op(other, mode, |a, b| a == b)
696 }
697
698 #[must_use]
700 pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
701 self.text_op(needle, mode, |a, b| a.contains(b))
702 }
703
704 #[must_use]
706 pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
707 self.text_op(needle, mode, |a, b| a.starts_with(b))
708 }
709
710 #[must_use]
712 pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
713 self.text_op(needle, mode, |a, b| a.ends_with(b))
714 }
715
716 #[must_use]
721 pub const fn is_empty(&self) -> Option<bool> {
722 match self {
723 Self::List(xs) => Some(xs.is_empty()),
724 Self::Map(entries) => Some(entries.is_empty()),
725 Self::Text(s) => Some(s.is_empty()),
726 Self::Blob(b) => Some(b.is_empty()),
727
728 Self::Null => Some(true),
730
731 _ => None,
732 }
733 }
734
735 #[must_use]
737 pub fn is_not_empty(&self) -> Option<bool> {
738 self.is_empty().map(|b| !b)
739 }
740
741 #[must_use]
747 pub fn contains(&self, needle: &Self) -> Option<bool> {
748 self.contains_by(needle, |a, b| a == b)
749 }
750
751 #[must_use]
753 pub fn contains_any(&self, needles: &Self) -> Option<bool> {
754 self.contains_any_by(needles, |a, b| a == b)
755 }
756
757 #[must_use]
759 pub fn contains_all(&self, needles: &Self) -> Option<bool> {
760 self.contains_all_by(needles, |a, b| a == b)
761 }
762
763 #[must_use]
765 pub fn in_list(&self, haystack: &Self) -> Option<bool> {
766 self.in_list_by(haystack, |a, b| a == b)
767 }
768
769 #[must_use]
771 pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
772 match self {
773 Self::List(_) => self.contains_by(needle, Self::eq_ci),
774 _ => Some(Self::eq_ci(self, needle)),
775 }
776 }
777
778 #[must_use]
780 pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
781 self.contains_any_by(needles, Self::eq_ci)
782 }
783
784 #[must_use]
786 pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
787 self.contains_all_by(needles, Self::eq_ci)
788 }
789
790 #[must_use]
792 pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
793 self.in_list_by(haystack, Self::eq_ci)
794 }
795}
796
797impl FieldValue for Value {
798 fn kind() -> crate::traits::FieldValueKind {
799 crate::traits::FieldValueKind::Atomic
800 }
801
802 fn to_value(&self) -> Value {
803 self.clone()
804 }
805
806 fn from_value(value: &Value) -> Option<Self> {
807 Some(value.clone())
808 }
809}
810
811#[macro_export]
812macro_rules! impl_from_for {
813 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
814 $(
815 impl From<$type> for Value {
816 fn from(v: $type) -> Self {
817 Self::$variant(v.into())
818 }
819 }
820 )*
821 };
822}
823
824impl_from_for! {
825 Account => Account,
826 Date => Date,
827 Decimal => Decimal,
828 Duration => Duration,
829 bool => Bool,
830 i8 => Int,
831 i16 => Int,
832 i32 => Int,
833 i64 => Int,
834 i128 => Int128,
835 Int => IntBig,
836 Principal => Principal,
837 Subaccount => Subaccount,
838 &str => Text,
839 String => Text,
840 Timestamp => Timestamp,
841 u8 => Uint,
842 u16 => Uint,
843 u32 => Uint,
844 u64 => Uint,
845 u128 => Uint128,
846 Nat => UintBig,
847 Ulid => Ulid,
848}
849
850impl CoercionFamilyExt for Value {
851 fn coercion_family(&self) -> CoercionFamily {
857 scalar_registry!(value_coercion_family_from_registry, self)
858 }
859}
860
861impl From<Vec<Self>> for Value {
862 fn from(vec: Vec<Self>) -> Self {
863 Self::List(vec)
864 }
865}
866
867impl TryFrom<Vec<(Self, Self)>> for Value {
868 type Error = SchemaInvariantError;
869
870 fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
871 Self::from_map(entries).map_err(Self::Error::from)
872 }
873}
874
875impl From<()> for Value {
876 fn from((): ()) -> Self {
877 Self::Unit
878 }
879}
880
881impl PartialOrd for Value {
887 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
888 match (self, other) {
889 (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
890 (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
891 (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
892 (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
893 (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
894 (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
895 (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
896 (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
897 (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
898 (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
899 (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
900 (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
901 (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
902 (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
903 (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
904 (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
905 (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
906 (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
907 (Self::Map(a), Self::Map(b)) => {
908 for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
909 let key_cmp = Self::canonical_cmp_key(left_key, right_key);
910 if key_cmp != Ordering::Equal {
911 return Some(key_cmp);
912 }
913
914 match left_value.partial_cmp(right_value) {
915 Some(Ordering::Equal) => {}
916 non_eq => return non_eq,
917 }
918 }
919 a.len().partial_cmp(&b.len())
920 }
921
922 _ => None,
924 }
925 }
926}
927
928#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
934pub struct ValueEnum {
935 variant: String,
936 path: Option<String>,
937 payload: Option<Box<Value>>,
938}
939
940impl ValueEnum {
941 #[must_use]
943 pub fn new(variant: &str, path: Option<&str>) -> Self {
944 Self {
945 variant: variant.to_string(),
946 path: path.map(ToString::to_string),
947 payload: None,
948 }
949 }
950
951 #[must_use]
953 pub fn strict<E: Path>(variant: &str) -> Self {
954 Self::new(variant, Some(E::PATH))
955 }
956
957 #[must_use]
959 pub fn from_enum<E: EnumValue>(value: E) -> Self {
960 value.to_value_enum()
961 }
962
963 #[must_use]
966 pub fn loose(variant: &str) -> Self {
967 Self::new(variant, None)
968 }
969
970 #[must_use]
972 pub fn with_payload(mut self, payload: Value) -> Self {
973 self.payload = Some(Box::new(payload));
974 self
975 }
976
977 #[must_use]
978 pub fn variant(&self) -> &str {
979 &self.variant
980 }
981
982 #[must_use]
983 pub fn path(&self) -> Option<&str> {
984 self.path.as_deref()
985 }
986
987 #[must_use]
988 pub fn payload(&self) -> Option<&Value> {
989 self.payload.as_deref()
990 }
991
992 pub(crate) fn set_path(&mut self, path: Option<String>) {
993 self.path = path;
994 }
995}