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, fmt};
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, 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 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        // Keep `Value` serialization aligned with the structural value-storage
358        // decoder so persisted `FieldStorageDecode::Value` slots can roundtrip
359        // every nested variant through fresh write + immediate readback.
360        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
435// Local helpers to expand the scalar registry into match arms.
436macro_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    ///
504    /// CONSTRUCTION
505    ///
506
507    /// Build a `Value::List` from a list literal.
508    ///
509    /// Intended for tests and inline construction.
510    /// Requires `Clone` because items are borrowed.
511    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    /// Build a `Value::List` from owned items.
519    ///
520    /// This is the canonical constructor for query / DTO boundaries.
521    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    /// Build a canonical `Value::Map` from owned key/value entries.
529    ///
530    /// Invariants are validated and entries are normalized:
531    /// - keys must be scalar and non-null
532    /// - values may be scalar or structured
533    /// - entries are sorted by canonical key order
534    /// - duplicate keys are rejected
535    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    /// Validate map entry invariants without changing order.
541    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    // Compare two map entries by canonical key order.
558    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    // Sort map entries in canonical key order without changing ownership.
563    pub(crate) fn sort_map_entries_in_place(entries: &mut [(Self, Self)]) {
564        entries.sort_by(Self::compare_map_entry_keys);
565    }
566
567    // Return `true` when map entries are already in strict canonical order and
568    // therefore contain no duplicate canonical keys.
569    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    /// Normalize map entries into canonical deterministic order.
580    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    /// Build a `Value::Enum` from a domain enum using its explicit mapping.
601    pub fn from_enum<E: EnumValue>(value: E) -> Self {
602        Self::Enum(value.to_value_enum())
603    }
604
605    /// Build a strict enum value using the canonical path of `E`.
606    #[must_use]
607    pub fn enum_strict<E: Path>(variant: &str) -> Self {
608        Self::Enum(ValueEnum::strict::<E>(variant))
609    }
610
611    ///
612    /// TYPES
613    ///
614
615    /// Returns true if the value is one of the numeric-like variants
616    /// supported by numeric comparison/ordering.
617    #[must_use]
618    pub const fn is_numeric(&self) -> bool {
619        scalar_registry!(value_is_numeric_from_registry, self)
620    }
621
622    /// Returns true when numeric coercion/comparison is explicitly allowed.
623    #[must_use]
624    pub const fn supports_numeric_coercion(&self) -> bool {
625        scalar_registry!(value_supports_numeric_coercion_from_registry, self)
626    }
627
628    /// Returns true if the value is Text.
629    #[must_use]
630    pub const fn is_text(&self) -> bool {
631        matches!(self, Self::Text(_))
632    }
633
634    /// Returns true if the value is Unit (used for presence/null comparators).
635    #[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            // definitely not scalar:
644            Self::List(_) | Self::Map(_) | Self::Unit => false,
645            _ => true,
646        }
647    }
648
649    /// Stable canonical variant tag used by hash/fingerprint encodings.
650    #[must_use]
651    pub(crate) const fn canonical_tag(&self) -> ValueTag {
652        tag::canonical_tag(self)
653    }
654
655    /// Stable canonical rank used by all cross-variant ordering surfaces.
656    #[must_use]
657    pub(crate) const fn canonical_rank(&self) -> u8 {
658        rank::canonical_rank(self)
659    }
660
661    /// Total canonical comparator used by planner/predicate/fingerprint surfaces.
662    #[must_use]
663    pub(crate) fn canonical_cmp(left: &Self, right: &Self) -> Ordering {
664        compare::canonical_cmp(left, right)
665    }
666
667    /// Total canonical comparator used for map-key normalization.
668    #[must_use]
669    pub fn canonical_cmp_key(left: &Self, right: &Self) -> Ordering {
670        compare::canonical_cmp_key(left, right)
671    }
672
673    /// Total canonical comparator for one map entry `(key, value)`.
674    ///
675    /// This keeps map-entry ordering aligned across normalization, hashing,
676    /// and fingerprint-adjacent surfaces.
677    #[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    /// Build one borrowed canonical map-entry order for hashing and
689    /// fingerprint-adjacent encoding surfaces.
690    #[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    /// Strict comparator for identical orderable variants.
701    ///
702    /// Returns `None` for mismatched or non-orderable variants.
703    #[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        // Numeric comparison eligibility is registry-authoritative.
710        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    ///
724    /// CONVERSION
725    ///
726
727    /// NOTE:
728    /// `Unit` is intentionally treated as a valid storage key and indexable,
729    /// used for singleton tables and synthetic identity entities.
730    /// Only `Null` is non-indexable.
731    #[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    // Internal numeric coercion helper for aggregate arithmetic.
782    pub(crate) fn to_numeric_decimal(&self) -> Option<Decimal> {
783        self.to_decimal()
784    }
785
786    // it's lossless, trust me bro
787    #[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    /// Cross-type numeric comparison; returns None if non-numeric.
816    #[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    ///
830    /// TEXT COMPARISON
831    ///
832
833    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        // NOTE: Unicode fallback — temporary to_lowercase for non‑ASCII.
838        // Future: replace with proper NFKC + full casefold when available.
839        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    /// Case-sensitive/insensitive equality check for text-like values.
930    #[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    /// Check whether `other` is a substring of `self` under the given text mode.
936    #[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    /// Check whether `self` starts with `other` under the given text mode.
942    #[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    /// Check whether `self` ends with `other` under the given text mode.
948    #[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    ///
954    /// EMPTY
955    ///
956
957    #[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            //  fields represented as Value::Null:
966            Self::Null => Some(true),
967
968            _ => None,
969        }
970    }
971
972    /// Logical negation of [`is_empty`](Self::is_empty).
973    #[must_use]
974    pub fn is_not_empty(&self) -> Option<bool> {
975        self.is_empty().map(|b| !b)
976    }
977
978    ///
979    /// COLLECTIONS
980    ///
981
982    /// Returns true if `self` contains `needle` (or equals it for scalars).
983    #[must_use]
984    pub fn contains(&self, needle: &Self) -> Option<bool> {
985        self.contains_by(needle, |a, b| a == b)
986    }
987
988    /// Returns true if any item in `needles` matches a member of `self`.
989    #[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    /// Returns true if every item in `needles` matches a member of `self`.
995    #[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    /// Returns true if `self` exists inside the provided list.
1001    #[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    /// Case-insensitive `contains` supporting text and identifier variants.
1007    #[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    /// Case-insensitive variant of [`contains_any`](Self::contains_any).
1016    #[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    /// Case-insensitive variant of [`contains_all`](Self::contains_all).
1022    #[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    /// Case-insensitive variant of [`in_list`](Self::in_list).
1028    #[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    /// Returns the coercion-routing family for this value.
1089    ///
1090    /// NOTE:
1091    /// This does NOT imply numeric, arithmetic, ordering, or keyability support.
1092    /// All scalar capabilities are registry-driven.
1093    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
1118// NOTE:
1119// Value::partial_cmp is NOT the canonical ordering for database semantics.
1120// Some orderable scalar types (e.g. Account, Unit) intentionally do not
1121// participate here. Use canonical_cmp / strict ordering for ORDER BY,
1122// planning, and key-range validation.
1123impl 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            // Cross-type comparisons: no ordering
1160            _ => None,
1161        }
1162    }
1163}
1164
1165//
1166// ValueEnum
1167// handles the Enum case; `path` is optional to allow strict (typed) or loose matching.
1168//
1169
1170#[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    /// Build a strict enum value matching the provided variant and path.
1179    #[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    /// Build a strict enum value using the canonical path of `E`.
1189    #[must_use]
1190    pub fn strict<E: Path>(variant: &str) -> Self {
1191        Self::new(variant, Some(E::PATH))
1192    }
1193
1194    /// Build a strict enum value from a domain enum using its explicit mapping.
1195    #[must_use]
1196    pub fn from_enum<E: EnumValue>(value: E) -> Self {
1197        value.to_value_enum()
1198    }
1199
1200    /// Build an enum value with an unresolved path for filter construction.
1201    /// Query normalization resolves this to the schema enum path before validation.
1202    #[must_use]
1203    pub fn loose(variant: &str) -> Self {
1204        Self::new(variant, None)
1205    }
1206
1207    /// Attach an enum payload (used for data-carrying variants).
1208    #[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}