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, NumericValue, Repr},
22 types::*,
23};
24use candid::CandidType;
25use serde::{Deserialize, Serialize, Serializer};
26use serde_bytes::Bytes;
27use std::{cmp::Ordering, fmt};
28
29pub use coercion::{CoercionFamily, CoercionFamilyExt};
31pub(crate) use hash::ValueHashWriter;
32pub(crate) use hash::hash_value;
33#[cfg(test)]
34pub(crate) use hash::with_test_hash_override;
35pub use storage_key::{StorageKey, StorageKeyDecodeError, StorageKeyEncodeError};
36pub use tag::ValueTag;
37
38const F64_SAFE_I64: i64 = 1i64 << 53;
43const F64_SAFE_U64: u64 = 1u64 << 53;
44const F64_SAFE_I128: i128 = 1i128 << 53;
45const F64_SAFE_U128: u128 = 1u128 << 53;
46const VALUE_WIRE_TYPE_NAME: &str = "Value";
47
48enum NumericRepr {
53 Decimal(Decimal),
54 F64(f64),
55 None,
56}
57
58#[derive(Clone, Copy)]
60enum ValueWireVariant {
61 Account,
62 Blob,
63 Bool,
64 Date,
65 Decimal,
66 Duration,
67 Enum,
68 Float32,
69 Float64,
70 Int,
71 Int128,
72 IntBig,
73 List,
74 Map,
75 Null,
76 Principal,
77 Subaccount,
78 Text,
79 Timestamp,
80 Uint,
81 Uint128,
82 UintBig,
83 Ulid,
84 Unit,
85}
86
87impl ValueWireVariant {
88 const fn index(self) -> u32 {
90 match self {
91 Self::Account => 0,
92 Self::Blob => 1,
93 Self::Bool => 2,
94 Self::Date => 3,
95 Self::Decimal => 4,
96 Self::Duration => 5,
97 Self::Enum => 6,
98 Self::Float32 => 7,
99 Self::Float64 => 8,
100 Self::Int => 9,
101 Self::Int128 => 10,
102 Self::IntBig => 11,
103 Self::List => 12,
104 Self::Map => 13,
105 Self::Null => 14,
106 Self::Principal => 15,
107 Self::Subaccount => 16,
108 Self::Text => 17,
109 Self::Timestamp => 18,
110 Self::Uint => 19,
111 Self::Uint128 => 20,
112 Self::UintBig => 21,
113 Self::Ulid => 22,
114 Self::Unit => 23,
115 }
116 }
117
118 const fn label(self) -> &'static str {
120 match self {
121 Self::Account => "Account",
122 Self::Blob => "Blob",
123 Self::Bool => "Bool",
124 Self::Date => "Date",
125 Self::Decimal => "Decimal",
126 Self::Duration => "Duration",
127 Self::Enum => "Enum",
128 Self::Float32 => "Float32",
129 Self::Float64 => "Float64",
130 Self::Int => "Int",
131 Self::Int128 => "Int128",
132 Self::IntBig => "IntBig",
133 Self::List => "List",
134 Self::Map => "Map",
135 Self::Null => "Null",
136 Self::Principal => "Principal",
137 Self::Subaccount => "Subaccount",
138 Self::Text => "Text",
139 Self::Timestamp => "Timestamp",
140 Self::Uint => "Uint",
141 Self::Uint128 => "Uint128",
142 Self::UintBig => "UintBig",
143 Self::Ulid => "Ulid",
144 Self::Unit => "Unit",
145 }
146 }
147}
148
149fn serialize_value_newtype_variant<S, T>(
151 serializer: S,
152 variant: ValueWireVariant,
153 value: &T,
154) -> Result<S::Ok, S::Error>
155where
156 S: Serializer,
157 T: ?Sized + Serialize,
158{
159 serializer.serialize_newtype_variant(
160 VALUE_WIRE_TYPE_NAME,
161 variant.index(),
162 variant.label(),
163 value,
164 )
165}
166
167fn serialize_value_unit_variant<S>(
169 serializer: S,
170 variant: ValueWireVariant,
171) -> Result<S::Ok, S::Error>
172where
173 S: Serializer,
174{
175 serializer.serialize_unit_variant(VALUE_WIRE_TYPE_NAME, variant.index(), variant.label())
176}
177
178#[derive(Clone, Copy, Debug, Eq, PartialEq)]
183pub enum TextMode {
184 Cs, Ci, }
187
188#[derive(Clone, Debug, Eq, PartialEq)]
195pub enum MapValueError {
196 EmptyKey {
197 index: usize,
198 },
199 NonScalarKey {
200 index: usize,
201 key: Value,
202 },
203 NonScalarValue {
204 index: usize,
205 value: Value,
206 },
207 DuplicateKey {
208 left_index: usize,
209 right_index: usize,
210 },
211}
212
213impl std::fmt::Display for MapValueError {
214 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215 match self {
216 Self::EmptyKey { index } => write!(f, "map key at index {index} must be non-null"),
217 Self::NonScalarKey { index, key } => {
218 write!(f, "map key at index {index} is not scalar: {key:?}")
219 }
220 Self::NonScalarValue { index, value } => {
221 write!(
222 f,
223 "map value at index {index} is not scalar/ref-like: {value:?}"
224 )
225 }
226 Self::DuplicateKey {
227 left_index,
228 right_index,
229 } => write!(
230 f,
231 "map contains duplicate keys at normalized positions {left_index} and {right_index}"
232 ),
233 }
234 }
235}
236
237impl std::error::Error for MapValueError {}
238
239#[derive(Clone, Debug, Eq, PartialEq)]
246pub enum SchemaInvariantError {
247 InvalidMapValue(MapValueError),
248}
249
250impl std::fmt::Display for SchemaInvariantError {
251 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
252 match self {
253 Self::InvalidMapValue(err) => write!(f, "{err}"),
254 }
255 }
256}
257
258impl std::error::Error for SchemaInvariantError {}
259
260impl From<MapValueError> for SchemaInvariantError {
261 fn from(value: MapValueError) -> Self {
262 Self::InvalidMapValue(value)
263 }
264}
265
266#[derive(CandidType, Clone, Eq, PartialEq)]
275pub enum Value {
276 Account(Account),
277 Blob(Vec<u8>),
278 Bool(bool),
279 Date(Date),
280 Decimal(Decimal),
281 Duration(Duration),
282 Enum(ValueEnum),
283 Float32(Float32),
284 Float64(Float64),
285 Int(i64),
286 Int128(Int128),
287 IntBig(Int),
288 List(Vec<Self>),
292 Map(Vec<(Self, Self)>),
299 Null,
300 Principal(Principal),
301 Subaccount(Subaccount),
302 Text(String),
303 Timestamp(Timestamp),
304 Uint(u64),
305 Uint128(Nat128),
306 UintBig(Nat),
307 Ulid(Ulid),
308 Unit,
309}
310
311impl fmt::Debug for Value {
312 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313 match self {
314 Self::Account(value) => f.debug_tuple("Account").field(value).finish(),
315 Self::Blob(value) => write!(f, "Blob({} bytes)", value.len()),
316 Self::Bool(value) => f.debug_tuple("Bool").field(value).finish(),
317 Self::Date(value) => f.debug_tuple("Date").field(value).finish(),
318 Self::Decimal(value) => f.debug_tuple("Decimal").field(value).finish(),
319 Self::Duration(value) => f.debug_tuple("Duration").field(value).finish(),
320 Self::Enum(value) => f.debug_tuple("Enum").field(value).finish(),
321 Self::Float32(value) => f.debug_tuple("Float32").field(value).finish(),
322 Self::Float64(value) => f.debug_tuple("Float64").field(value).finish(),
323 Self::Int(value) => f.debug_tuple("Int").field(value).finish(),
324 Self::Int128(value) => f.debug_tuple("Int128").field(value).finish(),
325 Self::IntBig(value) => f.debug_tuple("IntBig").field(value).finish(),
326 Self::List(value) => f.debug_tuple("List").field(value).finish(),
327 Self::Map(value) => f.debug_tuple("Map").field(value).finish(),
328 Self::Null => f.write_str("Null"),
329 Self::Principal(value) => f.debug_tuple("Principal").field(value).finish(),
330 Self::Subaccount(value) => f.debug_tuple("Subaccount").field(value).finish(),
331 Self::Text(value) => f.debug_tuple("Text").field(value).finish(),
332 Self::Timestamp(value) => f.debug_tuple("Timestamp").field(value).finish(),
333 Self::Uint(value) => f.debug_tuple("Uint").field(value).finish(),
334 Self::Uint128(value) => f.debug_tuple("Uint128").field(value).finish(),
335 Self::UintBig(value) => f.debug_tuple("UintBig").field(value).finish(),
336 Self::Ulid(value) => f.debug_tuple("Ulid").field(value).finish(),
337 Self::Unit => f.write_str("Unit"),
338 }
339 }
340}
341
342impl FieldTypeMeta for Value {
343 const KIND: FieldKind = FieldKind::Structured { queryable: false };
344 const STORAGE_DECODE: FieldStorageDecode = FieldStorageDecode::Value;
345}
346
347impl Value {
348 pub const __KIND: FieldKind = FieldKind::Structured { queryable: false };
349 pub const __STORAGE_DECODE: FieldStorageDecode = FieldStorageDecode::Value;
350}
351
352impl Serialize for Value {
353 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
354 where
355 S: Serializer,
356 {
357 match self {
361 Self::Account(value) => {
362 serialize_value_newtype_variant(serializer, ValueWireVariant::Account, value)
363 }
364 Self::Blob(value) => serialize_value_newtype_variant(
365 serializer,
366 ValueWireVariant::Blob,
367 &Bytes::new(value.as_slice()),
368 ),
369 Self::Bool(value) => {
370 serialize_value_newtype_variant(serializer, ValueWireVariant::Bool, value)
371 }
372 Self::Date(value) => {
373 serialize_value_newtype_variant(serializer, ValueWireVariant::Date, value)
374 }
375 Self::Decimal(value) => {
376 serialize_value_newtype_variant(serializer, ValueWireVariant::Decimal, value)
377 }
378 Self::Duration(value) => {
379 serialize_value_newtype_variant(serializer, ValueWireVariant::Duration, value)
380 }
381 Self::Enum(value) => {
382 serialize_value_newtype_variant(serializer, ValueWireVariant::Enum, value)
383 }
384 Self::Float32(value) => {
385 serialize_value_newtype_variant(serializer, ValueWireVariant::Float32, &value.get())
386 }
387 Self::Float64(value) => {
388 serialize_value_newtype_variant(serializer, ValueWireVariant::Float64, &value.get())
389 }
390 Self::Int(value) => {
391 serialize_value_newtype_variant(serializer, ValueWireVariant::Int, value)
392 }
393 Self::Int128(value) => {
394 serialize_value_newtype_variant(serializer, ValueWireVariant::Int128, value)
395 }
396 Self::IntBig(value) => {
397 serialize_value_newtype_variant(serializer, ValueWireVariant::IntBig, value)
398 }
399 Self::List(items) => {
400 serialize_value_newtype_variant(serializer, ValueWireVariant::List, items)
401 }
402 Self::Map(entries) => {
403 serialize_value_newtype_variant(serializer, ValueWireVariant::Map, entries)
404 }
405 Self::Null => serialize_value_unit_variant(serializer, ValueWireVariant::Null),
406 Self::Principal(value) => {
407 serialize_value_newtype_variant(serializer, ValueWireVariant::Principal, value)
408 }
409 Self::Subaccount(value) => {
410 serialize_value_newtype_variant(serializer, ValueWireVariant::Subaccount, value)
411 }
412 Self::Text(value) => {
413 serialize_value_newtype_variant(serializer, ValueWireVariant::Text, value)
414 }
415 Self::Timestamp(value) => {
416 serialize_value_newtype_variant(serializer, ValueWireVariant::Timestamp, value)
417 }
418 Self::Uint(value) => {
419 serialize_value_newtype_variant(serializer, ValueWireVariant::Uint, value)
420 }
421 Self::Uint128(value) => {
422 serialize_value_newtype_variant(serializer, ValueWireVariant::Uint128, value)
423 }
424 Self::UintBig(value) => {
425 serialize_value_newtype_variant(serializer, ValueWireVariant::UintBig, value)
426 }
427 Self::Ulid(value) => {
428 serialize_value_newtype_variant(serializer, ValueWireVariant::Ulid, value)
429 }
430 Self::Unit => serialize_value_unit_variant(serializer, ValueWireVariant::Unit),
431 }
432 }
433}
434
435macro_rules! value_is_numeric_from_registry {
437 ( @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) ),* $(,)? ) => {
438 match $value {
439 $( $value_pat => $is_numeric, )*
440 _ => false,
441 }
442 };
443}
444
445macro_rules! value_supports_numeric_coercion_from_registry {
446 ( @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) ),* $(,)? ) => {
447 match $value {
448 $( $value_pat => $supports_numeric_coercion, )*
449 _ => false,
450 }
451 };
452}
453
454macro_rules! value_storage_key_case {
455 ( $value:expr, Unit, true ) => {
456 if let Value::Unit = $value {
457 Some(StorageKey::Unit)
458 } else {
459 None
460 }
461 };
462 ( $value:expr, $scalar:ident, true ) => {
463 if let Value::$scalar(v) = $value {
464 Some(StorageKey::$scalar(*v))
465 } else {
466 None
467 }
468 };
469 ( $value:expr, $scalar:ident, false ) => {
470 None
471 };
472}
473
474macro_rules! value_storage_key_from_registry {
475 ( @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) ),* $(,)? ) => {
476 {
477 let mut key = None;
478 $(
479 match key {
480 Some(_) => {}
481 None => {
482 key = value_storage_key_case!($value, $scalar, $is_storage_key_encodable);
483 }
484 }
485 )*
486 key
487 }
488 };
489}
490
491macro_rules! value_coercion_family_from_registry {
492 ( @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) ),* $(,)? ) => {
493 match $value {
494 $( $value_pat => $coercion_family, )*
495 Value::List(_) => CoercionFamily::Collection,
496 Value::Map(_) => CoercionFamily::Collection,
497 Value::Null => CoercionFamily::Null,
498 }
499 };
500}
501
502impl Value {
503 pub fn from_slice<T>(items: &[T]) -> Self
512 where
513 T: Into<Self> + Clone,
514 {
515 Self::List(items.iter().cloned().map(Into::into).collect())
516 }
517
518 pub fn from_list<T>(items: Vec<T>) -> Self
522 where
523 T: Into<Self>,
524 {
525 Self::List(items.into_iter().map(Into::into).collect())
526 }
527
528 pub fn from_map(entries: Vec<(Self, Self)>) -> Result<Self, MapValueError> {
536 let normalized = Self::normalize_map_entries(entries)?;
537 Ok(Self::Map(normalized))
538 }
539
540 pub fn validate_map_entries(entries: &[(Self, Self)]) -> Result<(), MapValueError> {
542 for (index, (key, _value)) in entries.iter().enumerate() {
543 if matches!(key, Self::Null) {
544 return Err(MapValueError::EmptyKey { index });
545 }
546 if !key.is_scalar() {
547 return Err(MapValueError::NonScalarKey {
548 index,
549 key: key.clone(),
550 });
551 }
552 }
553
554 Ok(())
555 }
556
557 pub(crate) fn compare_map_entry_keys(left: &(Self, Self), right: &(Self, Self)) -> Ordering {
559 Self::canonical_cmp_key(&left.0, &right.0)
560 }
561
562 pub(crate) fn sort_map_entries_in_place(entries: &mut [(Self, Self)]) {
564 entries.sort_by(Self::compare_map_entry_keys);
565 }
566
567 pub(crate) fn map_entries_are_strictly_canonical(entries: &[(Self, Self)]) -> bool {
570 entries.windows(2).all(|pair| {
571 let [left, right] = pair else {
572 return true;
573 };
574
575 Self::compare_map_entry_keys(left, right) == Ordering::Less
576 })
577 }
578
579 pub fn normalize_map_entries(
581 mut entries: Vec<(Self, Self)>,
582 ) -> Result<Vec<(Self, Self)>, MapValueError> {
583 Self::validate_map_entries(&entries)?;
584 Self::sort_map_entries_in_place(entries.as_mut_slice());
585
586 for i in 1..entries.len() {
587 let (left_key, _) = &entries[i - 1];
588 let (right_key, _) = &entries[i];
589 if Self::canonical_cmp_key(left_key, right_key) == Ordering::Equal {
590 return Err(MapValueError::DuplicateKey {
591 left_index: i - 1,
592 right_index: i,
593 });
594 }
595 }
596
597 Ok(entries)
598 }
599
600 pub fn from_enum<E: EnumValue>(value: E) -> Self {
602 Self::Enum(value.to_value_enum())
603 }
604
605 #[must_use]
607 pub fn enum_strict<E: Path>(variant: &str) -> Self {
608 Self::Enum(ValueEnum::strict::<E>(variant))
609 }
610
611 #[must_use]
618 pub const fn is_numeric(&self) -> bool {
619 scalar_registry!(value_is_numeric_from_registry, self)
620 }
621
622 #[must_use]
624 pub const fn supports_numeric_coercion(&self) -> bool {
625 scalar_registry!(value_supports_numeric_coercion_from_registry, self)
626 }
627
628 #[must_use]
630 pub const fn is_text(&self) -> bool {
631 matches!(self, Self::Text(_))
632 }
633
634 #[must_use]
636 pub const fn is_unit(&self) -> bool {
637 matches!(self, Self::Unit)
638 }
639
640 #[must_use]
641 pub const fn is_scalar(&self) -> bool {
642 match self {
643 Self::List(_) | Self::Map(_) | Self::Unit => false,
645 _ => true,
646 }
647 }
648
649 #[must_use]
651 pub(crate) const fn canonical_tag(&self) -> ValueTag {
652 tag::canonical_tag(self)
653 }
654
655 #[must_use]
657 pub(crate) const fn canonical_rank(&self) -> u8 {
658 rank::canonical_rank(self)
659 }
660
661 #[must_use]
663 pub(crate) fn canonical_cmp(left: &Self, right: &Self) -> Ordering {
664 compare::canonical_cmp(left, right)
665 }
666
667 #[must_use]
669 pub fn canonical_cmp_key(left: &Self, right: &Self) -> Ordering {
670 compare::canonical_cmp_key(left, right)
671 }
672
673 #[must_use]
678 pub(crate) fn canonical_cmp_map_entry(
679 left_key: &Self,
680 left_value: &Self,
681 right_key: &Self,
682 right_value: &Self,
683 ) -> Ordering {
684 Self::canonical_cmp_key(left_key, right_key)
685 .then_with(|| Self::canonical_cmp(left_value, right_value))
686 }
687
688 #[must_use]
691 pub(crate) fn ordered_map_entries(entries: &[(Self, Self)]) -> Vec<&(Self, Self)> {
692 let mut ordered = entries.iter().collect::<Vec<_>>();
693 ordered.sort_by(|left, right| {
694 Self::canonical_cmp_map_entry(&left.0, &left.1, &right.0, &right.1)
695 });
696
697 ordered
698 }
699
700 #[must_use]
704 pub(crate) fn strict_order_cmp(left: &Self, right: &Self) -> Option<Ordering> {
705 compare::strict_order_cmp(left, right)
706 }
707
708 fn numeric_repr(&self) -> NumericRepr {
709 if !self.supports_numeric_coercion() {
711 return NumericRepr::None;
712 }
713
714 if let Some(d) = self.to_decimal() {
715 return NumericRepr::Decimal(d);
716 }
717 if let Some(f) = self.to_f64_lossless() {
718 return NumericRepr::F64(f);
719 }
720 NumericRepr::None
721 }
722
723 #[must_use]
732 pub const fn as_storage_key(&self) -> Option<StorageKey> {
733 scalar_registry!(value_storage_key_from_registry, self)
734 }
735
736 #[must_use]
737 pub const fn as_text(&self) -> Option<&str> {
738 if let Self::Text(s) = self {
739 Some(s.as_str())
740 } else {
741 None
742 }
743 }
744
745 #[must_use]
746 pub const fn as_list(&self) -> Option<&[Self]> {
747 if let Self::List(xs) = self {
748 Some(xs.as_slice())
749 } else {
750 None
751 }
752 }
753
754 #[must_use]
755 pub const fn as_map(&self) -> Option<&[(Self, Self)]> {
756 if let Self::Map(entries) = self {
757 Some(entries.as_slice())
758 } else {
759 None
760 }
761 }
762
763 fn to_decimal(&self) -> Option<Decimal> {
764 match self {
765 Self::Decimal(d) => d.try_to_decimal(),
766 Self::Duration(d) => d.try_to_decimal(),
767 Self::Float64(f) => f.try_to_decimal(),
768 Self::Float32(f) => f.try_to_decimal(),
769 Self::Int(i) => i.try_to_decimal(),
770 Self::Int128(i) => i.try_to_decimal(),
771 Self::IntBig(i) => i.try_to_decimal(),
772 Self::Timestamp(t) => t.try_to_decimal(),
773 Self::Uint(u) => u.try_to_decimal(),
774 Self::Uint128(u) => u.try_to_decimal(),
775 Self::UintBig(u) => u.try_to_decimal(),
776
777 _ => None,
778 }
779 }
780
781 pub(crate) fn to_numeric_decimal(&self) -> Option<Decimal> {
783 self.to_decimal()
784 }
785
786 #[expect(clippy::cast_precision_loss)]
788 fn to_f64_lossless(&self) -> Option<f64> {
789 match self {
790 Self::Duration(d) if d.repr() <= F64_SAFE_U64 => Some(d.repr() as f64),
791 Self::Float64(f) => Some(f.get()),
792 Self::Float32(f) => Some(f64::from(f.get())),
793 Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
794 Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
795 Some(i.get() as f64)
796 }
797 Self::IntBig(i) => i.to_i128().and_then(|v| {
798 (-F64_SAFE_I128..=F64_SAFE_I128)
799 .contains(&v)
800 .then_some(v as f64)
801 }),
802 Self::Timestamp(t) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(&t.repr()) => {
803 Some(t.repr() as f64)
804 }
805 Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
806 Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
807 Self::UintBig(u) => u
808 .to_u128()
809 .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
810
811 _ => None,
812 }
813 }
814
815 #[must_use]
817 pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
818 if !self.supports_numeric_coercion() || !other.supports_numeric_coercion() {
819 return None;
820 }
821
822 match (self.numeric_repr(), other.numeric_repr()) {
823 (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
824 (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
825 _ => None,
826 }
827 }
828
829 fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
834 if s.is_ascii() {
835 return std::borrow::Cow::Owned(s.to_ascii_lowercase());
836 }
837 std::borrow::Cow::Owned(s.to_lowercase())
840 }
841
842 fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
843 match mode {
844 TextMode::Cs => std::borrow::Cow::Borrowed(s),
845 TextMode::Ci => Self::fold_ci(s),
846 }
847 }
848
849 fn text_op(
850 &self,
851 other: &Self,
852 mode: TextMode,
853 f: impl Fn(&str, &str) -> bool,
854 ) -> Option<bool> {
855 let (a, b) = (self.as_text()?, other.as_text()?);
856 let a = Self::text_with_mode(a, mode);
857 let b = Self::text_with_mode(b, mode);
858 Some(f(&a, &b))
859 }
860
861 fn ci_key(&self) -> Option<String> {
862 match self {
863 Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
864 Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
865 Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
866 Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
867 _ => None,
868 }
869 }
870
871 fn eq_ci(a: &Self, b: &Self) -> bool {
872 if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
873 return ak == bk;
874 }
875
876 a == b
877 }
878
879 fn normalize_list_ref(v: &Self) -> Vec<&Self> {
880 match v {
881 Self::List(vs) => vs.iter().collect(),
882 v => vec![v],
883 }
884 }
885
886 fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
887 where
888 F: Fn(&Self, &Self) -> bool,
889 {
890 self.as_list()
891 .map(|items| items.iter().any(|v| eq(v, needle)))
892 }
893
894 #[expect(clippy::unnecessary_wraps)]
895 fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
896 where
897 F: Fn(&Self, &Self) -> bool,
898 {
899 let needles = Self::normalize_list_ref(needles);
900 match self {
901 Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
902 scalar => Some(needles.iter().any(|n| eq(scalar, n))),
903 }
904 }
905
906 #[expect(clippy::unnecessary_wraps)]
907 fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
908 where
909 F: Fn(&Self, &Self) -> bool,
910 {
911 let needles = Self::normalize_list_ref(needles);
912 match self {
913 Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
914 scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
915 }
916 }
917
918 fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
919 where
920 F: Fn(&Self, &Self) -> bool,
921 {
922 if let Self::List(items) = haystack {
923 Some(items.iter().any(|h| eq(h, self)))
924 } else {
925 None
926 }
927 }
928
929 #[must_use]
931 pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
932 self.text_op(other, mode, |a, b| a == b)
933 }
934
935 #[must_use]
937 pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
938 self.text_op(needle, mode, |a, b| a.contains(b))
939 }
940
941 #[must_use]
943 pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
944 self.text_op(needle, mode, |a, b| a.starts_with(b))
945 }
946
947 #[must_use]
949 pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
950 self.text_op(needle, mode, |a, b| a.ends_with(b))
951 }
952
953 #[must_use]
958 pub const fn is_empty(&self) -> Option<bool> {
959 match self {
960 Self::List(xs) => Some(xs.is_empty()),
961 Self::Map(entries) => Some(entries.is_empty()),
962 Self::Text(s) => Some(s.is_empty()),
963 Self::Blob(b) => Some(b.is_empty()),
964
965 Self::Null => Some(true),
967
968 _ => None,
969 }
970 }
971
972 #[must_use]
974 pub fn is_not_empty(&self) -> Option<bool> {
975 self.is_empty().map(|b| !b)
976 }
977
978 #[must_use]
984 pub fn contains(&self, needle: &Self) -> Option<bool> {
985 self.contains_by(needle, |a, b| a == b)
986 }
987
988 #[must_use]
990 pub fn contains_any(&self, needles: &Self) -> Option<bool> {
991 self.contains_any_by(needles, |a, b| a == b)
992 }
993
994 #[must_use]
996 pub fn contains_all(&self, needles: &Self) -> Option<bool> {
997 self.contains_all_by(needles, |a, b| a == b)
998 }
999
1000 #[must_use]
1002 pub fn in_list(&self, haystack: &Self) -> Option<bool> {
1003 self.in_list_by(haystack, |a, b| a == b)
1004 }
1005
1006 #[must_use]
1008 pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
1009 match self {
1010 Self::List(_) => self.contains_by(needle, Self::eq_ci),
1011 _ => Some(Self::eq_ci(self, needle)),
1012 }
1013 }
1014
1015 #[must_use]
1017 pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
1018 self.contains_any_by(needles, Self::eq_ci)
1019 }
1020
1021 #[must_use]
1023 pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
1024 self.contains_all_by(needles, Self::eq_ci)
1025 }
1026
1027 #[must_use]
1029 pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
1030 self.in_list_by(haystack, Self::eq_ci)
1031 }
1032}
1033
1034impl FieldValue for Value {
1035 fn kind() -> crate::traits::FieldValueKind {
1036 crate::traits::FieldValueKind::Atomic
1037 }
1038
1039 fn to_value(&self) -> Value {
1040 self.clone()
1041 }
1042
1043 fn from_value(value: &Value) -> Option<Self> {
1044 Some(value.clone())
1045 }
1046}
1047
1048#[macro_export]
1049macro_rules! impl_from_for {
1050 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
1051 $(
1052 impl From<$type> for Value {
1053 fn from(v: $type) -> Self {
1054 Self::$variant(v.into())
1055 }
1056 }
1057 )*
1058 };
1059}
1060
1061impl_from_for! {
1062 Account => Account,
1063 Date => Date,
1064 Decimal => Decimal,
1065 Duration => Duration,
1066 bool => Bool,
1067 i8 => Int,
1068 i16 => Int,
1069 i32 => Int,
1070 i64 => Int,
1071 i128 => Int128,
1072 Int => IntBig,
1073 Principal => Principal,
1074 Subaccount => Subaccount,
1075 &str => Text,
1076 String => Text,
1077 Timestamp => Timestamp,
1078 u8 => Uint,
1079 u16 => Uint,
1080 u32 => Uint,
1081 u64 => Uint,
1082 u128 => Uint128,
1083 Nat => UintBig,
1084 Ulid => Ulid,
1085}
1086
1087impl CoercionFamilyExt for Value {
1088 fn coercion_family(&self) -> CoercionFamily {
1094 scalar_registry!(value_coercion_family_from_registry, self)
1095 }
1096}
1097
1098impl From<Vec<Self>> for Value {
1099 fn from(vec: Vec<Self>) -> Self {
1100 Self::List(vec)
1101 }
1102}
1103
1104impl TryFrom<Vec<(Self, Self)>> for Value {
1105 type Error = SchemaInvariantError;
1106
1107 fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
1108 Self::from_map(entries).map_err(Self::Error::from)
1109 }
1110}
1111
1112impl From<()> for Value {
1113 fn from((): ()) -> Self {
1114 Self::Unit
1115 }
1116}
1117
1118impl PartialOrd for Value {
1124 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1125 match (self, other) {
1126 (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
1127 (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
1128 (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
1129 (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
1130 (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
1131 (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
1132 (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
1133 (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
1134 (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
1135 (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
1136 (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
1137 (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
1138 (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
1139 (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
1140 (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
1141 (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
1142 (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
1143 (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
1144 (Self::Map(a), Self::Map(b)) => {
1145 for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
1146 let key_cmp = Self::canonical_cmp_key(left_key, right_key);
1147 if key_cmp != Ordering::Equal {
1148 return Some(key_cmp);
1149 }
1150
1151 match left_value.partial_cmp(right_value) {
1152 Some(Ordering::Equal) => {}
1153 non_eq => return non_eq,
1154 }
1155 }
1156 a.len().partial_cmp(&b.len())
1157 }
1158
1159 _ => None,
1161 }
1162 }
1163}
1164
1165#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
1171pub struct ValueEnum {
1172 variant: String,
1173 path: Option<String>,
1174 payload: Option<Box<Value>>,
1175}
1176
1177impl ValueEnum {
1178 #[must_use]
1180 pub fn new(variant: &str, path: Option<&str>) -> Self {
1181 Self {
1182 variant: variant.to_string(),
1183 path: path.map(ToString::to_string),
1184 payload: None,
1185 }
1186 }
1187
1188 #[must_use]
1190 pub fn strict<E: Path>(variant: &str) -> Self {
1191 Self::new(variant, Some(E::PATH))
1192 }
1193
1194 #[must_use]
1196 pub fn from_enum<E: EnumValue>(value: E) -> Self {
1197 value.to_value_enum()
1198 }
1199
1200 #[must_use]
1203 pub fn loose(variant: &str) -> Self {
1204 Self::new(variant, None)
1205 }
1206
1207 #[must_use]
1209 pub fn with_payload(mut self, payload: Value) -> Self {
1210 self.payload = Some(Box::new(payload));
1211 self
1212 }
1213
1214 #[must_use]
1215 pub fn variant(&self) -> &str {
1216 &self.variant
1217 }
1218
1219 #[must_use]
1220 pub fn path(&self) -> Option<&str> {
1221 self.path.as_deref()
1222 }
1223
1224 #[must_use]
1225 pub fn payload(&self) -> Option<&Value> {
1226 self.payload.as_deref()
1227 }
1228
1229 pub(crate) fn set_path(&mut self, path: Option<String>) {
1230 self.path = path;
1231 }
1232}