Skip to main content

icydb_core/value/
mod.rs

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