Skip to main content

icydb_core/value/
mod.rs

1//! Module: value
2//!
3//! Responsibility: module-local ownership and contracts for value.
4//! Does not own: cross-module orchestration outside this module.
5//! Boundary: exposes this module API while keeping implementation details internal.
6
7mod 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;
28
29// re-exports
30pub use coercion::{CoercionFamily, CoercionFamilyExt};
31pub(crate) use hash::hash_value;
32#[cfg(test)]
33pub(crate) use hash::with_test_hash_override;
34pub use storage_key::{StorageKey, StorageKeyDecodeError, StorageKeyEncodeError};
35pub use tag::ValueTag;
36
37//
38// CONSTANTS
39//
40
41const F64_SAFE_I64: i64 = 1i64 << 53;
42const F64_SAFE_U64: u64 = 1u64 << 53;
43const F64_SAFE_I128: i128 = 1i128 << 53;
44const F64_SAFE_U128: u128 = 1u128 << 53;
45const VALUE_WIRE_TYPE_NAME: &str = "Value";
46
47//
48// NumericRepr
49//
50
51enum NumericRepr {
52    Decimal(Decimal),
53    F64(f64),
54    None,
55}
56
57// Name and discriminant owner for the stable `Value` serde wire shape.
58#[derive(Clone, Copy)]
59enum ValueWireVariant {
60    Account,
61    Blob,
62    Bool,
63    Date,
64    Decimal,
65    Duration,
66    Enum,
67    Float32,
68    Float64,
69    Int,
70    Int128,
71    IntBig,
72    List,
73    Map,
74    Null,
75    Principal,
76    Subaccount,
77    Text,
78    Timestamp,
79    Uint,
80    Uint128,
81    UintBig,
82    Ulid,
83    Unit,
84}
85
86impl ValueWireVariant {
87    // Return the stable serde discriminant index for this `Value` variant.
88    const fn index(self) -> u32 {
89        match self {
90            Self::Account => 0,
91            Self::Blob => 1,
92            Self::Bool => 2,
93            Self::Date => 3,
94            Self::Decimal => 4,
95            Self::Duration => 5,
96            Self::Enum => 6,
97            Self::Float32 => 7,
98            Self::Float64 => 8,
99            Self::Int => 9,
100            Self::Int128 => 10,
101            Self::IntBig => 11,
102            Self::List => 12,
103            Self::Map => 13,
104            Self::Null => 14,
105            Self::Principal => 15,
106            Self::Subaccount => 16,
107            Self::Text => 17,
108            Self::Timestamp => 18,
109            Self::Uint => 19,
110            Self::Uint128 => 20,
111            Self::UintBig => 21,
112            Self::Ulid => 22,
113            Self::Unit => 23,
114        }
115    }
116
117    // Return the stable serde variant label for this `Value` variant.
118    const fn label(self) -> &'static str {
119        match self {
120            Self::Account => "Account",
121            Self::Blob => "Blob",
122            Self::Bool => "Bool",
123            Self::Date => "Date",
124            Self::Decimal => "Decimal",
125            Self::Duration => "Duration",
126            Self::Enum => "Enum",
127            Self::Float32 => "Float32",
128            Self::Float64 => "Float64",
129            Self::Int => "Int",
130            Self::Int128 => "Int128",
131            Self::IntBig => "IntBig",
132            Self::List => "List",
133            Self::Map => "Map",
134            Self::Null => "Null",
135            Self::Principal => "Principal",
136            Self::Subaccount => "Subaccount",
137            Self::Text => "Text",
138            Self::Timestamp => "Timestamp",
139            Self::Uint => "Uint",
140            Self::Uint128 => "Uint128",
141            Self::UintBig => "UintBig",
142            Self::Ulid => "Ulid",
143            Self::Unit => "Unit",
144        }
145    }
146}
147
148// Serialize one non-unit `Value` variant through the stable wire descriptor.
149fn serialize_value_newtype_variant<S, T>(
150    serializer: S,
151    variant: ValueWireVariant,
152    value: &T,
153) -> Result<S::Ok, S::Error>
154where
155    S: Serializer,
156    T: ?Sized + Serialize,
157{
158    serializer.serialize_newtype_variant(
159        VALUE_WIRE_TYPE_NAME,
160        variant.index(),
161        variant.label(),
162        value,
163    )
164}
165
166// Serialize one unit `Value` variant through the stable wire descriptor.
167fn serialize_value_unit_variant<S>(
168    serializer: S,
169    variant: ValueWireVariant,
170) -> Result<S::Ok, S::Error>
171where
172    S: Serializer,
173{
174    serializer.serialize_unit_variant(VALUE_WIRE_TYPE_NAME, variant.index(), variant.label())
175}
176
177//
178// TextMode
179//
180
181#[derive(Clone, Copy, Debug, Eq, PartialEq)]
182pub enum TextMode {
183    Cs, // case-sensitive
184    Ci, // case-insensitive
185}
186
187//
188// MapValueError
189//
190// Invariant violations for `Value::Map` construction/normalization.
191//
192
193#[derive(Clone, Debug, Eq, PartialEq)]
194pub enum MapValueError {
195    EmptyKey {
196        index: usize,
197    },
198    NonScalarKey {
199        index: usize,
200        key: Value,
201    },
202    NonScalarValue {
203        index: usize,
204        value: Value,
205    },
206    DuplicateKey {
207        left_index: usize,
208        right_index: usize,
209    },
210}
211
212impl std::fmt::Display for MapValueError {
213    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214        match self {
215            Self::EmptyKey { index } => write!(f, "map key at index {index} must be non-null"),
216            Self::NonScalarKey { index, key } => {
217                write!(f, "map key at index {index} is not scalar: {key:?}")
218            }
219            Self::NonScalarValue { index, value } => {
220                write!(
221                    f,
222                    "map value at index {index} is not scalar/ref-like: {value:?}"
223                )
224            }
225            Self::DuplicateKey {
226                left_index,
227                right_index,
228            } => write!(
229                f,
230                "map contains duplicate keys at normalized positions {left_index} and {right_index}"
231            ),
232        }
233    }
234}
235
236impl std::error::Error for MapValueError {}
237
238//
239// SchemaInvariantError
240//
241// Invariant violations encountered while materializing schema/runtime values.
242//
243
244#[derive(Clone, Debug, Eq, PartialEq)]
245pub enum SchemaInvariantError {
246    InvalidMapValue(MapValueError),
247}
248
249impl std::fmt::Display for SchemaInvariantError {
250    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
251        match self {
252            Self::InvalidMapValue(err) => write!(f, "{err}"),
253        }
254    }
255}
256
257impl std::error::Error for SchemaInvariantError {}
258
259impl From<MapValueError> for SchemaInvariantError {
260    fn from(value: MapValueError) -> Self {
261        Self::InvalidMapValue(value)
262    }
263}
264
265//
266// Value
267// can be used in WHERE statements
268//
269// Null        → the field’s value is Option::None (i.e., SQL NULL).
270// Unit        → internal placeholder for RHS; not a real value.
271//
272
273#[derive(CandidType, Clone, Debug, Eq, PartialEq)]
274pub enum Value {
275    Account(Account),
276    Blob(Vec<u8>),
277    Bool(bool),
278    Date(Date),
279    Decimal(Decimal),
280    Duration(Duration),
281    Enum(ValueEnum),
282    Float32(Float32),
283    Float64(Float64),
284    Int(i64),
285    Int128(Int128),
286    IntBig(Int),
287    /// Ordered list of values.
288    /// Used for many-cardinality transport.
289    /// List order is preserved for normalization and fingerprints.
290    List(Vec<Self>),
291    /// Canonical deterministic map representation.
292    ///
293    /// - Maps are unordered values; insertion order is discarded.
294    /// - Entries are always sorted by canonical key order and keys are unique.
295    /// - Map fields remain non-queryable and persist as atomic value replacements.
296    /// - Persistence treats map fields as atomic value replacements per row save.
297    Map(Vec<(Self, Self)>),
298    Null,
299    Principal(Principal),
300    Subaccount(Subaccount),
301    Text(String),
302    Timestamp(Timestamp),
303    Uint(u64),
304    Uint128(Nat128),
305    UintBig(Nat),
306    Ulid(Ulid),
307    Unit,
308}
309
310impl FieldTypeMeta for Value {
311    const KIND: FieldKind = FieldKind::Structured { queryable: false };
312    const STORAGE_DECODE: FieldStorageDecode = FieldStorageDecode::Value;
313}
314
315impl Value {
316    pub const __KIND: FieldKind = FieldKind::Structured { queryable: false };
317    pub const __STORAGE_DECODE: FieldStorageDecode = FieldStorageDecode::Value;
318}
319
320impl Serialize for Value {
321    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
322    where
323        S: Serializer,
324    {
325        // Keep `Value` serialization aligned with the structural value-storage
326        // decoder so persisted `FieldStorageDecode::Value` slots can roundtrip
327        // every nested variant through fresh write + immediate readback.
328        match self {
329            Self::Account(value) => {
330                serialize_value_newtype_variant(serializer, ValueWireVariant::Account, value)
331            }
332            Self::Blob(value) => serialize_value_newtype_variant(
333                serializer,
334                ValueWireVariant::Blob,
335                &Bytes::new(value.as_slice()),
336            ),
337            Self::Bool(value) => {
338                serialize_value_newtype_variant(serializer, ValueWireVariant::Bool, value)
339            }
340            Self::Date(value) => {
341                serialize_value_newtype_variant(serializer, ValueWireVariant::Date, value)
342            }
343            Self::Decimal(value) => {
344                serialize_value_newtype_variant(serializer, ValueWireVariant::Decimal, value)
345            }
346            Self::Duration(value) => {
347                serialize_value_newtype_variant(serializer, ValueWireVariant::Duration, value)
348            }
349            Self::Enum(value) => {
350                serialize_value_newtype_variant(serializer, ValueWireVariant::Enum, value)
351            }
352            Self::Float32(value) => {
353                serialize_value_newtype_variant(serializer, ValueWireVariant::Float32, &value.get())
354            }
355            Self::Float64(value) => {
356                serialize_value_newtype_variant(serializer, ValueWireVariant::Float64, &value.get())
357            }
358            Self::Int(value) => {
359                serialize_value_newtype_variant(serializer, ValueWireVariant::Int, value)
360            }
361            Self::Int128(value) => {
362                serialize_value_newtype_variant(serializer, ValueWireVariant::Int128, value)
363            }
364            Self::IntBig(value) => {
365                serialize_value_newtype_variant(serializer, ValueWireVariant::IntBig, value)
366            }
367            Self::List(items) => {
368                serialize_value_newtype_variant(serializer, ValueWireVariant::List, items)
369            }
370            Self::Map(entries) => {
371                serialize_value_newtype_variant(serializer, ValueWireVariant::Map, entries)
372            }
373            Self::Null => serialize_value_unit_variant(serializer, ValueWireVariant::Null),
374            Self::Principal(value) => {
375                serialize_value_newtype_variant(serializer, ValueWireVariant::Principal, value)
376            }
377            Self::Subaccount(value) => {
378                serialize_value_newtype_variant(serializer, ValueWireVariant::Subaccount, value)
379            }
380            Self::Text(value) => {
381                serialize_value_newtype_variant(serializer, ValueWireVariant::Text, value)
382            }
383            Self::Timestamp(value) => {
384                serialize_value_newtype_variant(serializer, ValueWireVariant::Timestamp, value)
385            }
386            Self::Uint(value) => {
387                serialize_value_newtype_variant(serializer, ValueWireVariant::Uint, value)
388            }
389            Self::Uint128(value) => {
390                serialize_value_newtype_variant(serializer, ValueWireVariant::Uint128, value)
391            }
392            Self::UintBig(value) => {
393                serialize_value_newtype_variant(serializer, ValueWireVariant::UintBig, value)
394            }
395            Self::Ulid(value) => {
396                serialize_value_newtype_variant(serializer, ValueWireVariant::Ulid, value)
397            }
398            Self::Unit => serialize_value_unit_variant(serializer, ValueWireVariant::Unit),
399        }
400    }
401}
402
403// Local helpers to expand the scalar registry into match arms.
404macro_rules! value_is_numeric_from_registry {
405    ( @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) ),* $(,)? ) => {
406        match $value {
407            $( $value_pat => $is_numeric, )*
408            _ => false,
409        }
410    };
411}
412
413macro_rules! value_supports_numeric_coercion_from_registry {
414    ( @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) ),* $(,)? ) => {
415        match $value {
416            $( $value_pat => $supports_numeric_coercion, )*
417            _ => false,
418        }
419    };
420}
421
422macro_rules! value_storage_key_case {
423    ( $value:expr, Unit, true ) => {
424        if let Value::Unit = $value {
425            Some(StorageKey::Unit)
426        } else {
427            None
428        }
429    };
430    ( $value:expr, $scalar:ident, true ) => {
431        if let Value::$scalar(v) = $value {
432            Some(StorageKey::$scalar(*v))
433        } else {
434            None
435        }
436    };
437    ( $value:expr, $scalar:ident, false ) => {
438        None
439    };
440}
441
442macro_rules! value_storage_key_from_registry {
443    ( @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) ),* $(,)? ) => {
444        {
445            let mut key = None;
446            $(
447                match key {
448                    Some(_) => {}
449                    None => {
450                        key = value_storage_key_case!($value, $scalar, $is_storage_key_encodable);
451                    }
452                }
453            )*
454            key
455        }
456    };
457}
458
459macro_rules! value_coercion_family_from_registry {
460    ( @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) ),* $(,)? ) => {
461        match $value {
462            $( $value_pat => $coercion_family, )*
463            Value::List(_) => CoercionFamily::Collection,
464            Value::Map(_) => CoercionFamily::Collection,
465            Value::Null => CoercionFamily::Null,
466        }
467    };
468}
469
470impl Value {
471    ///
472    /// CONSTRUCTION
473    ///
474
475    /// Build a `Value::List` from a list literal.
476    ///
477    /// Intended for tests and inline construction.
478    /// Requires `Clone` because items are borrowed.
479    pub fn from_slice<T>(items: &[T]) -> Self
480    where
481        T: Into<Self> + Clone,
482    {
483        Self::List(items.iter().cloned().map(Into::into).collect())
484    }
485
486    /// Build a `Value::List` from owned items.
487    ///
488    /// This is the canonical constructor for query / DTO boundaries.
489    pub fn from_list<T>(items: Vec<T>) -> Self
490    where
491        T: Into<Self>,
492    {
493        Self::List(items.into_iter().map(Into::into).collect())
494    }
495
496    /// Build a canonical `Value::Map` from owned key/value entries.
497    ///
498    /// Invariants are validated and entries are normalized:
499    /// - keys must be scalar and non-null
500    /// - values may be scalar or structured
501    /// - entries are sorted by canonical key order
502    /// - duplicate keys are rejected
503    pub fn from_map(entries: Vec<(Self, Self)>) -> Result<Self, MapValueError> {
504        let normalized = Self::normalize_map_entries(entries)?;
505        Ok(Self::Map(normalized))
506    }
507
508    /// Validate map entry invariants without changing order.
509    pub fn validate_map_entries(entries: &[(Self, Self)]) -> Result<(), MapValueError> {
510        for (index, (key, _value)) in entries.iter().enumerate() {
511            if matches!(key, Self::Null) {
512                return Err(MapValueError::EmptyKey { index });
513            }
514            if !key.is_scalar() {
515                return Err(MapValueError::NonScalarKey {
516                    index,
517                    key: key.clone(),
518                });
519            }
520        }
521
522        Ok(())
523    }
524
525    // Compare two map entries by canonical key order.
526    pub(crate) fn compare_map_entry_keys(left: &(Self, Self), right: &(Self, Self)) -> Ordering {
527        Self::canonical_cmp_key(&left.0, &right.0)
528    }
529
530    // Sort map entries in canonical key order without changing ownership.
531    pub(crate) fn sort_map_entries_in_place(entries: &mut [(Self, Self)]) {
532        entries.sort_by(Self::compare_map_entry_keys);
533    }
534
535    // Return `true` when map entries are already in strict canonical order and
536    // therefore contain no duplicate canonical keys.
537    pub(crate) fn map_entries_are_strictly_canonical(entries: &[(Self, Self)]) -> bool {
538        entries.windows(2).all(|pair| {
539            let [left, right] = pair else {
540                return true;
541            };
542
543            Self::compare_map_entry_keys(left, right) == Ordering::Less
544        })
545    }
546
547    /// Normalize map entries into canonical deterministic order.
548    pub fn normalize_map_entries(
549        mut entries: Vec<(Self, Self)>,
550    ) -> Result<Vec<(Self, Self)>, MapValueError> {
551        Self::validate_map_entries(&entries)?;
552        Self::sort_map_entries_in_place(entries.as_mut_slice());
553
554        for i in 1..entries.len() {
555            let (left_key, _) = &entries[i - 1];
556            let (right_key, _) = &entries[i];
557            if Self::canonical_cmp_key(left_key, right_key) == Ordering::Equal {
558                return Err(MapValueError::DuplicateKey {
559                    left_index: i - 1,
560                    right_index: i,
561                });
562            }
563        }
564
565        Ok(entries)
566    }
567
568    /// Build a `Value::Enum` from a domain enum using its explicit mapping.
569    pub fn from_enum<E: EnumValue>(value: E) -> Self {
570        Self::Enum(value.to_value_enum())
571    }
572
573    /// Build a strict enum value using the canonical path of `E`.
574    #[must_use]
575    pub fn enum_strict<E: Path>(variant: &str) -> Self {
576        Self::Enum(ValueEnum::strict::<E>(variant))
577    }
578
579    ///
580    /// TYPES
581    ///
582
583    /// Returns true if the value is one of the numeric-like variants
584    /// supported by numeric comparison/ordering.
585    #[must_use]
586    pub const fn is_numeric(&self) -> bool {
587        scalar_registry!(value_is_numeric_from_registry, self)
588    }
589
590    /// Returns true when numeric coercion/comparison is explicitly allowed.
591    #[must_use]
592    pub const fn supports_numeric_coercion(&self) -> bool {
593        scalar_registry!(value_supports_numeric_coercion_from_registry, self)
594    }
595
596    /// Returns true if the value is Text.
597    #[must_use]
598    pub const fn is_text(&self) -> bool {
599        matches!(self, Self::Text(_))
600    }
601
602    /// Returns true if the value is Unit (used for presence/null comparators).
603    #[must_use]
604    pub const fn is_unit(&self) -> bool {
605        matches!(self, Self::Unit)
606    }
607
608    #[must_use]
609    pub const fn is_scalar(&self) -> bool {
610        match self {
611            // definitely not scalar:
612            Self::List(_) | Self::Map(_) | Self::Unit => false,
613            _ => true,
614        }
615    }
616
617    /// Stable canonical variant tag used by hash/fingerprint encodings.
618    #[must_use]
619    pub(crate) const fn canonical_tag(&self) -> ValueTag {
620        tag::canonical_tag(self)
621    }
622
623    /// Stable canonical rank used by all cross-variant ordering surfaces.
624    #[must_use]
625    pub(crate) const fn canonical_rank(&self) -> u8 {
626        rank::canonical_rank(self)
627    }
628
629    /// Total canonical comparator used by planner/predicate/fingerprint surfaces.
630    #[must_use]
631    pub(crate) fn canonical_cmp(left: &Self, right: &Self) -> Ordering {
632        compare::canonical_cmp(left, right)
633    }
634
635    /// Total canonical comparator used for map-key normalization.
636    #[must_use]
637    pub fn canonical_cmp_key(left: &Self, right: &Self) -> Ordering {
638        compare::canonical_cmp_key(left, right)
639    }
640
641    /// Total canonical comparator for one map entry `(key, value)`.
642    ///
643    /// This keeps map-entry ordering aligned across normalization, hashing,
644    /// and fingerprint-adjacent surfaces.
645    #[must_use]
646    pub(crate) fn canonical_cmp_map_entry(
647        left_key: &Self,
648        left_value: &Self,
649        right_key: &Self,
650        right_value: &Self,
651    ) -> Ordering {
652        Self::canonical_cmp_key(left_key, right_key)
653            .then_with(|| Self::canonical_cmp(left_value, right_value))
654    }
655
656    /// Build one borrowed canonical map-entry order for hashing and
657    /// fingerprint-adjacent encoding surfaces.
658    #[must_use]
659    pub(crate) fn ordered_map_entries(entries: &[(Self, Self)]) -> Vec<&(Self, Self)> {
660        let mut ordered = entries.iter().collect::<Vec<_>>();
661        ordered.sort_by(|left, right| {
662            Self::canonical_cmp_map_entry(&left.0, &left.1, &right.0, &right.1)
663        });
664
665        ordered
666    }
667
668    /// Strict comparator for identical orderable variants.
669    ///
670    /// Returns `None` for mismatched or non-orderable variants.
671    #[must_use]
672    pub(crate) fn strict_order_cmp(left: &Self, right: &Self) -> Option<Ordering> {
673        compare::strict_order_cmp(left, right)
674    }
675
676    fn numeric_repr(&self) -> NumericRepr {
677        // Numeric comparison eligibility is registry-authoritative.
678        if !self.supports_numeric_coercion() {
679            return NumericRepr::None;
680        }
681
682        if let Some(d) = self.to_decimal() {
683            return NumericRepr::Decimal(d);
684        }
685        if let Some(f) = self.to_f64_lossless() {
686            return NumericRepr::F64(f);
687        }
688        NumericRepr::None
689    }
690
691    ///
692    /// CONVERSION
693    ///
694
695    /// NOTE:
696    /// `Unit` is intentionally treated as a valid storage key and indexable,
697    /// used for singleton tables and synthetic identity entities.
698    /// Only `Null` is non-indexable.
699    #[must_use]
700    pub const fn as_storage_key(&self) -> Option<StorageKey> {
701        scalar_registry!(value_storage_key_from_registry, self)
702    }
703
704    #[must_use]
705    pub const fn as_text(&self) -> Option<&str> {
706        if let Self::Text(s) = self {
707            Some(s.as_str())
708        } else {
709            None
710        }
711    }
712
713    #[must_use]
714    pub const fn as_list(&self) -> Option<&[Self]> {
715        if let Self::List(xs) = self {
716            Some(xs.as_slice())
717        } else {
718            None
719        }
720    }
721
722    #[must_use]
723    pub const fn as_map(&self) -> Option<&[(Self, Self)]> {
724        if let Self::Map(entries) = self {
725            Some(entries.as_slice())
726        } else {
727            None
728        }
729    }
730
731    fn to_decimal(&self) -> Option<Decimal> {
732        match self {
733            Self::Decimal(d) => d.try_to_decimal(),
734            Self::Duration(d) => d.try_to_decimal(),
735            Self::Float64(f) => f.try_to_decimal(),
736            Self::Float32(f) => f.try_to_decimal(),
737            Self::Int(i) => i.try_to_decimal(),
738            Self::Int128(i) => i.try_to_decimal(),
739            Self::IntBig(i) => i.try_to_decimal(),
740            Self::Timestamp(t) => t.try_to_decimal(),
741            Self::Uint(u) => u.try_to_decimal(),
742            Self::Uint128(u) => u.try_to_decimal(),
743            Self::UintBig(u) => u.try_to_decimal(),
744
745            _ => None,
746        }
747    }
748
749    // Internal numeric coercion helper for aggregate arithmetic.
750    pub(crate) fn to_numeric_decimal(&self) -> Option<Decimal> {
751        self.to_decimal()
752    }
753
754    // it's lossless, trust me bro
755    #[expect(clippy::cast_precision_loss)]
756    fn to_f64_lossless(&self) -> Option<f64> {
757        match self {
758            Self::Duration(d) if d.repr() <= F64_SAFE_U64 => Some(d.repr() as f64),
759            Self::Float64(f) => Some(f.get()),
760            Self::Float32(f) => Some(f64::from(f.get())),
761            Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
762            Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
763                Some(i.get() as f64)
764            }
765            Self::IntBig(i) => i.to_i128().and_then(|v| {
766                (-F64_SAFE_I128..=F64_SAFE_I128)
767                    .contains(&v)
768                    .then_some(v as f64)
769            }),
770            Self::Timestamp(t) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(&t.repr()) => {
771                Some(t.repr() as f64)
772            }
773            Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
774            Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
775            Self::UintBig(u) => u
776                .to_u128()
777                .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
778
779            _ => None,
780        }
781    }
782
783    /// Cross-type numeric comparison; returns None if non-numeric.
784    #[must_use]
785    pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
786        if !self.supports_numeric_coercion() || !other.supports_numeric_coercion() {
787            return None;
788        }
789
790        match (self.numeric_repr(), other.numeric_repr()) {
791            (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
792            (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
793            _ => None,
794        }
795    }
796
797    ///
798    /// TEXT COMPARISON
799    ///
800
801    fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
802        if s.is_ascii() {
803            return std::borrow::Cow::Owned(s.to_ascii_lowercase());
804        }
805        // NOTE: Unicode fallback — temporary to_lowercase for non‑ASCII.
806        // Future: replace with proper NFKC + full casefold when available.
807        std::borrow::Cow::Owned(s.to_lowercase())
808    }
809
810    fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
811        match mode {
812            TextMode::Cs => std::borrow::Cow::Borrowed(s),
813            TextMode::Ci => Self::fold_ci(s),
814        }
815    }
816
817    fn text_op(
818        &self,
819        other: &Self,
820        mode: TextMode,
821        f: impl Fn(&str, &str) -> bool,
822    ) -> Option<bool> {
823        let (a, b) = (self.as_text()?, other.as_text()?);
824        let a = Self::text_with_mode(a, mode);
825        let b = Self::text_with_mode(b, mode);
826        Some(f(&a, &b))
827    }
828
829    fn ci_key(&self) -> Option<String> {
830        match self {
831            Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
832            Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
833            Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
834            Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
835            _ => None,
836        }
837    }
838
839    fn eq_ci(a: &Self, b: &Self) -> bool {
840        if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
841            return ak == bk;
842        }
843
844        a == b
845    }
846
847    fn normalize_list_ref(v: &Self) -> Vec<&Self> {
848        match v {
849            Self::List(vs) => vs.iter().collect(),
850            v => vec![v],
851        }
852    }
853
854    fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
855    where
856        F: Fn(&Self, &Self) -> bool,
857    {
858        self.as_list()
859            .map(|items| items.iter().any(|v| eq(v, needle)))
860    }
861
862    #[expect(clippy::unnecessary_wraps)]
863    fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
864    where
865        F: Fn(&Self, &Self) -> bool,
866    {
867        let needles = Self::normalize_list_ref(needles);
868        match self {
869            Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
870            scalar => Some(needles.iter().any(|n| eq(scalar, n))),
871        }
872    }
873
874    #[expect(clippy::unnecessary_wraps)]
875    fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
876    where
877        F: Fn(&Self, &Self) -> bool,
878    {
879        let needles = Self::normalize_list_ref(needles);
880        match self {
881            Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
882            scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
883        }
884    }
885
886    fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
887    where
888        F: Fn(&Self, &Self) -> bool,
889    {
890        if let Self::List(items) = haystack {
891            Some(items.iter().any(|h| eq(h, self)))
892        } else {
893            None
894        }
895    }
896
897    /// Case-sensitive/insensitive equality check for text-like values.
898    #[must_use]
899    pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
900        self.text_op(other, mode, |a, b| a == b)
901    }
902
903    /// Check whether `other` is a substring of `self` under the given text mode.
904    #[must_use]
905    pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
906        self.text_op(needle, mode, |a, b| a.contains(b))
907    }
908
909    /// Check whether `self` starts with `other` under the given text mode.
910    #[must_use]
911    pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
912        self.text_op(needle, mode, |a, b| a.starts_with(b))
913    }
914
915    /// Check whether `self` ends with `other` under the given text mode.
916    #[must_use]
917    pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
918        self.text_op(needle, mode, |a, b| a.ends_with(b))
919    }
920
921    ///
922    /// EMPTY
923    ///
924
925    #[must_use]
926    pub const fn is_empty(&self) -> Option<bool> {
927        match self {
928            Self::List(xs) => Some(xs.is_empty()),
929            Self::Map(entries) => Some(entries.is_empty()),
930            Self::Text(s) => Some(s.is_empty()),
931            Self::Blob(b) => Some(b.is_empty()),
932
933            //  fields represented as Value::Null:
934            Self::Null => Some(true),
935
936            _ => None,
937        }
938    }
939
940    /// Logical negation of [`is_empty`](Self::is_empty).
941    #[must_use]
942    pub fn is_not_empty(&self) -> Option<bool> {
943        self.is_empty().map(|b| !b)
944    }
945
946    ///
947    /// COLLECTIONS
948    ///
949
950    /// Returns true if `self` contains `needle` (or equals it for scalars).
951    #[must_use]
952    pub fn contains(&self, needle: &Self) -> Option<bool> {
953        self.contains_by(needle, |a, b| a == b)
954    }
955
956    /// Returns true if any item in `needles` matches a member of `self`.
957    #[must_use]
958    pub fn contains_any(&self, needles: &Self) -> Option<bool> {
959        self.contains_any_by(needles, |a, b| a == b)
960    }
961
962    /// Returns true if every item in `needles` matches a member of `self`.
963    #[must_use]
964    pub fn contains_all(&self, needles: &Self) -> Option<bool> {
965        self.contains_all_by(needles, |a, b| a == b)
966    }
967
968    /// Returns true if `self` exists inside the provided list.
969    #[must_use]
970    pub fn in_list(&self, haystack: &Self) -> Option<bool> {
971        self.in_list_by(haystack, |a, b| a == b)
972    }
973
974    /// Case-insensitive `contains` supporting text and identifier variants.
975    #[must_use]
976    pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
977        match self {
978            Self::List(_) => self.contains_by(needle, Self::eq_ci),
979            _ => Some(Self::eq_ci(self, needle)),
980        }
981    }
982
983    /// Case-insensitive variant of [`contains_any`](Self::contains_any).
984    #[must_use]
985    pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
986        self.contains_any_by(needles, Self::eq_ci)
987    }
988
989    /// Case-insensitive variant of [`contains_all`](Self::contains_all).
990    #[must_use]
991    pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
992        self.contains_all_by(needles, Self::eq_ci)
993    }
994
995    /// Case-insensitive variant of [`in_list`](Self::in_list).
996    #[must_use]
997    pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
998        self.in_list_by(haystack, Self::eq_ci)
999    }
1000}
1001
1002impl FieldValue for Value {
1003    fn kind() -> crate::traits::FieldValueKind {
1004        crate::traits::FieldValueKind::Atomic
1005    }
1006
1007    fn to_value(&self) -> Value {
1008        self.clone()
1009    }
1010
1011    fn from_value(value: &Value) -> Option<Self> {
1012        Some(value.clone())
1013    }
1014}
1015
1016#[macro_export]
1017macro_rules! impl_from_for {
1018    ( $( $type:ty => $variant:ident ),* $(,)? ) => {
1019        $(
1020            impl From<$type> for Value {
1021                fn from(v: $type) -> Self {
1022                    Self::$variant(v.into())
1023                }
1024            }
1025        )*
1026    };
1027}
1028
1029impl_from_for! {
1030    Account    => Account,
1031    Date       => Date,
1032    Decimal    => Decimal,
1033    Duration   => Duration,
1034    bool       => Bool,
1035    i8         => Int,
1036    i16        => Int,
1037    i32        => Int,
1038    i64        => Int,
1039    i128       => Int128,
1040    Int        => IntBig,
1041    Principal  => Principal,
1042    Subaccount => Subaccount,
1043    &str       => Text,
1044    String     => Text,
1045    Timestamp  => Timestamp,
1046    u8         => Uint,
1047    u16        => Uint,
1048    u32        => Uint,
1049    u64        => Uint,
1050    u128       => Uint128,
1051    Nat        => UintBig,
1052    Ulid       => Ulid,
1053}
1054
1055impl CoercionFamilyExt for Value {
1056    /// Returns the coercion-routing family for this value.
1057    ///
1058    /// NOTE:
1059    /// This does NOT imply numeric, arithmetic, ordering, or keyability support.
1060    /// All scalar capabilities are registry-driven.
1061    fn coercion_family(&self) -> CoercionFamily {
1062        scalar_registry!(value_coercion_family_from_registry, self)
1063    }
1064}
1065
1066impl From<Vec<Self>> for Value {
1067    fn from(vec: Vec<Self>) -> Self {
1068        Self::List(vec)
1069    }
1070}
1071
1072impl TryFrom<Vec<(Self, Self)>> for Value {
1073    type Error = SchemaInvariantError;
1074
1075    fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
1076        Self::from_map(entries).map_err(Self::Error::from)
1077    }
1078}
1079
1080impl From<()> for Value {
1081    fn from((): ()) -> Self {
1082        Self::Unit
1083    }
1084}
1085
1086// NOTE:
1087// Value::partial_cmp is NOT the canonical ordering for database semantics.
1088// Some orderable scalar types (e.g. Account, Unit) intentionally do not
1089// participate here. Use canonical_cmp / strict ordering for ORDER BY,
1090// planning, and key-range validation.
1091impl PartialOrd for Value {
1092    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1093        match (self, other) {
1094            (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
1095            (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
1096            (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
1097            (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
1098            (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
1099            (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
1100            (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
1101            (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
1102            (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
1103            (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
1104            (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
1105            (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
1106            (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
1107            (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
1108            (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
1109            (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
1110            (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
1111            (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
1112            (Self::Map(a), Self::Map(b)) => {
1113                for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
1114                    let key_cmp = Self::canonical_cmp_key(left_key, right_key);
1115                    if key_cmp != Ordering::Equal {
1116                        return Some(key_cmp);
1117                    }
1118
1119                    match left_value.partial_cmp(right_value) {
1120                        Some(Ordering::Equal) => {}
1121                        non_eq => return non_eq,
1122                    }
1123                }
1124                a.len().partial_cmp(&b.len())
1125            }
1126
1127            // Cross-type comparisons: no ordering
1128            _ => None,
1129        }
1130    }
1131}
1132
1133//
1134// ValueEnum
1135// handles the Enum case; `path` is optional to allow strict (typed) or loose matching.
1136//
1137
1138#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
1139pub struct ValueEnum {
1140    variant: String,
1141    path: Option<String>,
1142    payload: Option<Box<Value>>,
1143}
1144
1145impl ValueEnum {
1146    /// Build a strict enum value matching the provided variant and path.
1147    #[must_use]
1148    pub fn new(variant: &str, path: Option<&str>) -> Self {
1149        Self {
1150            variant: variant.to_string(),
1151            path: path.map(ToString::to_string),
1152            payload: None,
1153        }
1154    }
1155
1156    /// Build a strict enum value using the canonical path of `E`.
1157    #[must_use]
1158    pub fn strict<E: Path>(variant: &str) -> Self {
1159        Self::new(variant, Some(E::PATH))
1160    }
1161
1162    /// Build a strict enum value from a domain enum using its explicit mapping.
1163    #[must_use]
1164    pub fn from_enum<E: EnumValue>(value: E) -> Self {
1165        value.to_value_enum()
1166    }
1167
1168    /// Build an enum value with an unresolved path for filter construction.
1169    /// Query normalization resolves this to the schema enum path before validation.
1170    #[must_use]
1171    pub fn loose(variant: &str) -> Self {
1172        Self::new(variant, None)
1173    }
1174
1175    /// Attach an enum payload (used for data-carrying variants).
1176    #[must_use]
1177    pub fn with_payload(mut self, payload: Value) -> Self {
1178        self.payload = Some(Box::new(payload));
1179        self
1180    }
1181
1182    #[must_use]
1183    pub fn variant(&self) -> &str {
1184        &self.variant
1185    }
1186
1187    #[must_use]
1188    pub fn path(&self) -> Option<&str> {
1189        self.path.as_deref()
1190    }
1191
1192    #[must_use]
1193    pub fn payload(&self) -> Option<&Value> {
1194        self.payload.as_deref()
1195    }
1196
1197    pub(crate) fn set_path(&mut self, path: Option<String>) {
1198        self.path = path;
1199    }
1200}