Skip to main content

icydb_core/value/
mod.rs

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