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