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 must be scalar/ref-like (no collections)
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            if !value.is_scalar() {
317                return Err(MapValueError::NonScalarValue {
318                    index,
319                    value: value.clone(),
320                });
321            }
322        }
323
324        Ok(())
325    }
326
327    // Compare two map entries by canonical key order.
328    pub(crate) fn compare_map_entry_keys(left: &(Self, Self), right: &(Self, Self)) -> Ordering {
329        Self::canonical_cmp_key(&left.0, &right.0)
330    }
331
332    // Sort map entries in canonical key order without changing ownership.
333    pub(crate) fn sort_map_entries_in_place(entries: &mut [(Self, Self)]) {
334        entries.sort_by(Self::compare_map_entry_keys);
335    }
336
337    // Return `true` when map entries are already in strict canonical order and
338    // therefore contain no duplicate canonical keys.
339    pub(crate) fn map_entries_are_strictly_canonical(entries: &[(Self, Self)]) -> bool {
340        entries.windows(2).all(|pair| {
341            let [left, right] = pair else {
342                return true;
343            };
344
345            Self::compare_map_entry_keys(left, right) == Ordering::Less
346        })
347    }
348
349    /// Normalize map entries into canonical deterministic order.
350    pub fn normalize_map_entries(
351        mut entries: Vec<(Self, Self)>,
352    ) -> Result<Vec<(Self, Self)>, MapValueError> {
353        Self::validate_map_entries(&entries)?;
354        Self::sort_map_entries_in_place(entries.as_mut_slice());
355
356        for i in 1..entries.len() {
357            let (left_key, _) = &entries[i - 1];
358            let (right_key, _) = &entries[i];
359            if Self::canonical_cmp_key(left_key, right_key) == Ordering::Equal {
360                return Err(MapValueError::DuplicateKey {
361                    left_index: i - 1,
362                    right_index: i,
363                });
364            }
365        }
366
367        Ok(entries)
368    }
369
370    /// Build a `Value::Enum` from a domain enum using its explicit mapping.
371    pub fn from_enum<E: EnumValue>(value: E) -> Self {
372        Self::Enum(value.to_value_enum())
373    }
374
375    /// Build a strict enum value using the canonical path of `E`.
376    #[must_use]
377    pub fn enum_strict<E: Path>(variant: &str) -> Self {
378        Self::Enum(ValueEnum::strict::<E>(variant))
379    }
380
381    ///
382    /// TYPES
383    ///
384
385    /// Returns true if the value is one of the numeric-like variants
386    /// supported by numeric comparison/ordering.
387    #[must_use]
388    pub const fn is_numeric(&self) -> bool {
389        scalar_registry!(value_is_numeric_from_registry, self)
390    }
391
392    /// Returns true when numeric coercion/comparison is explicitly allowed.
393    #[must_use]
394    pub const fn supports_numeric_coercion(&self) -> bool {
395        scalar_registry!(value_supports_numeric_coercion_from_registry, self)
396    }
397
398    /// Returns true if the value is Text.
399    #[must_use]
400    pub const fn is_text(&self) -> bool {
401        matches!(self, Self::Text(_))
402    }
403
404    /// Returns true if the value is Unit (used for presence/null comparators).
405    #[must_use]
406    pub const fn is_unit(&self) -> bool {
407        matches!(self, Self::Unit)
408    }
409
410    #[must_use]
411    pub const fn is_scalar(&self) -> bool {
412        match self {
413            // definitely not scalar:
414            Self::List(_) | Self::Map(_) | Self::Unit => false,
415            _ => true,
416        }
417    }
418
419    /// Stable canonical variant tag used by hash/fingerprint encodings.
420    #[must_use]
421    pub(crate) const fn canonical_tag(&self) -> ValueTag {
422        tag::canonical_tag(self)
423    }
424
425    /// Stable canonical rank used by all cross-variant ordering surfaces.
426    #[must_use]
427    pub(crate) const fn canonical_rank(&self) -> u8 {
428        rank::canonical_rank(self)
429    }
430
431    /// Total canonical comparator used by planner/predicate/fingerprint surfaces.
432    #[must_use]
433    pub(crate) fn canonical_cmp(left: &Self, right: &Self) -> Ordering {
434        compare::canonical_cmp(left, right)
435    }
436
437    /// Total canonical comparator used for map-key normalization.
438    #[must_use]
439    pub fn canonical_cmp_key(left: &Self, right: &Self) -> Ordering {
440        compare::canonical_cmp_key(left, right)
441    }
442
443    /// Total canonical comparator for one map entry `(key, value)`.
444    ///
445    /// This keeps map-entry ordering aligned across normalization, hashing,
446    /// and fingerprint-adjacent surfaces.
447    #[must_use]
448    pub(crate) fn canonical_cmp_map_entry(
449        left_key: &Self,
450        left_value: &Self,
451        right_key: &Self,
452        right_value: &Self,
453    ) -> Ordering {
454        Self::canonical_cmp_key(left_key, right_key)
455            .then_with(|| Self::canonical_cmp(left_value, right_value))
456    }
457
458    /// Build one borrowed canonical map-entry order for hashing and
459    /// fingerprint-adjacent encoding surfaces.
460    #[must_use]
461    pub(crate) fn ordered_map_entries(entries: &[(Self, Self)]) -> Vec<&(Self, Self)> {
462        let mut ordered = entries.iter().collect::<Vec<_>>();
463        ordered.sort_by(|left, right| {
464            Self::canonical_cmp_map_entry(&left.0, &left.1, &right.0, &right.1)
465        });
466
467        ordered
468    }
469
470    /// Strict comparator for identical orderable variants.
471    ///
472    /// Returns `None` for mismatched or non-orderable variants.
473    #[must_use]
474    pub(crate) fn strict_order_cmp(left: &Self, right: &Self) -> Option<Ordering> {
475        compare::strict_order_cmp(left, right)
476    }
477
478    fn numeric_repr(&self) -> NumericRepr {
479        // Numeric comparison eligibility is registry-authoritative.
480        if !self.supports_numeric_coercion() {
481            return NumericRepr::None;
482        }
483
484        if let Some(d) = self.to_decimal() {
485            return NumericRepr::Decimal(d);
486        }
487        if let Some(f) = self.to_f64_lossless() {
488            return NumericRepr::F64(f);
489        }
490        NumericRepr::None
491    }
492
493    ///
494    /// CONVERSION
495    ///
496
497    /// NOTE:
498    /// `Unit` is intentionally treated as a valid storage key and indexable,
499    /// used for singleton tables and synthetic identity entities.
500    /// Only `Null` is non-indexable.
501    #[must_use]
502    pub const fn as_storage_key(&self) -> Option<StorageKey> {
503        scalar_registry!(value_storage_key_from_registry, self)
504    }
505
506    #[must_use]
507    pub const fn as_text(&self) -> Option<&str> {
508        if let Self::Text(s) = self {
509            Some(s.as_str())
510        } else {
511            None
512        }
513    }
514
515    #[must_use]
516    pub const fn as_list(&self) -> Option<&[Self]> {
517        if let Self::List(xs) = self {
518            Some(xs.as_slice())
519        } else {
520            None
521        }
522    }
523
524    #[must_use]
525    pub const fn as_map(&self) -> Option<&[(Self, Self)]> {
526        if let Self::Map(entries) = self {
527            Some(entries.as_slice())
528        } else {
529            None
530        }
531    }
532
533    fn to_decimal(&self) -> Option<Decimal> {
534        match self {
535            Self::Decimal(d) => Some(*d),
536            Self::Duration(d) => Decimal::from_u64(d.repr()),
537            Self::Float64(f) => Decimal::from_f64(f.get()),
538            Self::Float32(f) => Decimal::from_f32(f.get()),
539            Self::Int(i) => Decimal::from_i64(*i),
540            Self::Int128(i) => Decimal::from_i128(i.get()),
541            Self::IntBig(i) => i.to_i128().and_then(Decimal::from_i128),
542            Self::Timestamp(t) => Decimal::from_i64(t.repr()),
543            Self::Uint(u) => Decimal::from_u64(*u),
544            Self::Uint128(u) => Decimal::from_u128(u.get()),
545            Self::UintBig(u) => u.to_u128().and_then(Decimal::from_u128),
546
547            _ => None,
548        }
549    }
550
551    // Internal numeric coercion helper for aggregate arithmetic.
552    pub(crate) fn to_numeric_decimal(&self) -> Option<Decimal> {
553        self.to_decimal()
554    }
555
556    // it's lossless, trust me bro
557    #[expect(clippy::cast_precision_loss)]
558    fn to_f64_lossless(&self) -> Option<f64> {
559        match self {
560            Self::Duration(d) if d.repr() <= F64_SAFE_U64 => Some(d.repr() as f64),
561            Self::Float64(f) => Some(f.get()),
562            Self::Float32(f) => Some(f64::from(f.get())),
563            Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
564            Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
565                Some(i.get() as f64)
566            }
567            Self::IntBig(i) => i.to_i128().and_then(|v| {
568                (-F64_SAFE_I128..=F64_SAFE_I128)
569                    .contains(&v)
570                    .then_some(v as f64)
571            }),
572            Self::Timestamp(t) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(&t.repr()) => {
573                Some(t.repr() as f64)
574            }
575            Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
576            Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
577            Self::UintBig(u) => u
578                .to_u128()
579                .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
580
581            _ => None,
582        }
583    }
584
585    /// Cross-type numeric comparison; returns None if non-numeric.
586    #[must_use]
587    pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
588        if !self.supports_numeric_coercion() || !other.supports_numeric_coercion() {
589            return None;
590        }
591
592        match (self.numeric_repr(), other.numeric_repr()) {
593            (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
594            (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
595            _ => None,
596        }
597    }
598
599    ///
600    /// TEXT COMPARISON
601    ///
602
603    fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
604        if s.is_ascii() {
605            return std::borrow::Cow::Owned(s.to_ascii_lowercase());
606        }
607        // NOTE: Unicode fallback — temporary to_lowercase for non‑ASCII.
608        // Future: replace with proper NFKC + full casefold when available.
609        std::borrow::Cow::Owned(s.to_lowercase())
610    }
611
612    fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
613        match mode {
614            TextMode::Cs => std::borrow::Cow::Borrowed(s),
615            TextMode::Ci => Self::fold_ci(s),
616        }
617    }
618
619    fn text_op(
620        &self,
621        other: &Self,
622        mode: TextMode,
623        f: impl Fn(&str, &str) -> bool,
624    ) -> Option<bool> {
625        let (a, b) = (self.as_text()?, other.as_text()?);
626        let a = Self::text_with_mode(a, mode);
627        let b = Self::text_with_mode(b, mode);
628        Some(f(&a, &b))
629    }
630
631    fn ci_key(&self) -> Option<String> {
632        match self {
633            Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
634            Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
635            Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
636            Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
637            _ => None,
638        }
639    }
640
641    fn eq_ci(a: &Self, b: &Self) -> bool {
642        if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
643            return ak == bk;
644        }
645
646        a == b
647    }
648
649    fn normalize_list_ref(v: &Self) -> Vec<&Self> {
650        match v {
651            Self::List(vs) => vs.iter().collect(),
652            v => vec![v],
653        }
654    }
655
656    fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
657    where
658        F: Fn(&Self, &Self) -> bool,
659    {
660        self.as_list()
661            .map(|items| items.iter().any(|v| eq(v, needle)))
662    }
663
664    #[expect(clippy::unnecessary_wraps)]
665    fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
666    where
667        F: Fn(&Self, &Self) -> bool,
668    {
669        let needles = Self::normalize_list_ref(needles);
670        match self {
671            Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
672            scalar => Some(needles.iter().any(|n| eq(scalar, n))),
673        }
674    }
675
676    #[expect(clippy::unnecessary_wraps)]
677    fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
678    where
679        F: Fn(&Self, &Self) -> bool,
680    {
681        let needles = Self::normalize_list_ref(needles);
682        match self {
683            Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
684            scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
685        }
686    }
687
688    fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
689    where
690        F: Fn(&Self, &Self) -> bool,
691    {
692        if let Self::List(items) = haystack {
693            Some(items.iter().any(|h| eq(h, self)))
694        } else {
695            None
696        }
697    }
698
699    /// Case-sensitive/insensitive equality check for text-like values.
700    #[must_use]
701    pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
702        self.text_op(other, mode, |a, b| a == b)
703    }
704
705    /// Check whether `other` is a substring of `self` under the given text mode.
706    #[must_use]
707    pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
708        self.text_op(needle, mode, |a, b| a.contains(b))
709    }
710
711    /// Check whether `self` starts with `other` under the given text mode.
712    #[must_use]
713    pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
714        self.text_op(needle, mode, |a, b| a.starts_with(b))
715    }
716
717    /// Check whether `self` ends with `other` under the given text mode.
718    #[must_use]
719    pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
720        self.text_op(needle, mode, |a, b| a.ends_with(b))
721    }
722
723    ///
724    /// EMPTY
725    ///
726
727    #[must_use]
728    pub const fn is_empty(&self) -> Option<bool> {
729        match self {
730            Self::List(xs) => Some(xs.is_empty()),
731            Self::Map(entries) => Some(entries.is_empty()),
732            Self::Text(s) => Some(s.is_empty()),
733            Self::Blob(b) => Some(b.is_empty()),
734
735            //  fields represented as Value::Null:
736            Self::Null => Some(true),
737
738            _ => None,
739        }
740    }
741
742    /// Logical negation of [`is_empty`](Self::is_empty).
743    #[must_use]
744    pub fn is_not_empty(&self) -> Option<bool> {
745        self.is_empty().map(|b| !b)
746    }
747
748    ///
749    /// COLLECTIONS
750    ///
751
752    /// Returns true if `self` contains `needle` (or equals it for scalars).
753    #[must_use]
754    pub fn contains(&self, needle: &Self) -> Option<bool> {
755        self.contains_by(needle, |a, b| a == b)
756    }
757
758    /// Returns true if any item in `needles` matches a member of `self`.
759    #[must_use]
760    pub fn contains_any(&self, needles: &Self) -> Option<bool> {
761        self.contains_any_by(needles, |a, b| a == b)
762    }
763
764    /// Returns true if every item in `needles` matches a member of `self`.
765    #[must_use]
766    pub fn contains_all(&self, needles: &Self) -> Option<bool> {
767        self.contains_all_by(needles, |a, b| a == b)
768    }
769
770    /// Returns true if `self` exists inside the provided list.
771    #[must_use]
772    pub fn in_list(&self, haystack: &Self) -> Option<bool> {
773        self.in_list_by(haystack, |a, b| a == b)
774    }
775
776    /// Case-insensitive `contains` supporting text and identifier variants.
777    #[must_use]
778    pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
779        match self {
780            Self::List(_) => self.contains_by(needle, Self::eq_ci),
781            _ => Some(Self::eq_ci(self, needle)),
782        }
783    }
784
785    /// Case-insensitive variant of [`contains_any`](Self::contains_any).
786    #[must_use]
787    pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
788        self.contains_any_by(needles, Self::eq_ci)
789    }
790
791    /// Case-insensitive variant of [`contains_all`](Self::contains_all).
792    #[must_use]
793    pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
794        self.contains_all_by(needles, Self::eq_ci)
795    }
796
797    /// Case-insensitive variant of [`in_list`](Self::in_list).
798    #[must_use]
799    pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
800        self.in_list_by(haystack, Self::eq_ci)
801    }
802}
803
804impl FieldValue for Value {
805    fn kind() -> crate::traits::FieldValueKind {
806        crate::traits::FieldValueKind::Atomic
807    }
808
809    fn to_value(&self) -> Value {
810        self.clone()
811    }
812
813    fn from_value(value: &Value) -> Option<Self> {
814        Some(value.clone())
815    }
816}
817
818#[macro_export]
819macro_rules! impl_from_for {
820    ( $( $type:ty => $variant:ident ),* $(,)? ) => {
821        $(
822            impl From<$type> for Value {
823                fn from(v: $type) -> Self {
824                    Self::$variant(v.into())
825                }
826            }
827        )*
828    };
829}
830
831impl_from_for! {
832    Account    => Account,
833    Date       => Date,
834    Decimal    => Decimal,
835    Duration   => Duration,
836    bool       => Bool,
837    i8         => Int,
838    i16        => Int,
839    i32        => Int,
840    i64        => Int,
841    i128       => Int128,
842    Int        => IntBig,
843    Principal  => Principal,
844    Subaccount => Subaccount,
845    &str       => Text,
846    String     => Text,
847    Timestamp  => Timestamp,
848    u8         => Uint,
849    u16        => Uint,
850    u32        => Uint,
851    u64        => Uint,
852    u128       => Uint128,
853    Nat        => UintBig,
854    Ulid       => Ulid,
855}
856
857impl CoercionFamilyExt for Value {
858    /// Returns the coercion-routing family for this value.
859    ///
860    /// NOTE:
861    /// This does NOT imply numeric, arithmetic, ordering, or keyability support.
862    /// All scalar capabilities are registry-driven.
863    fn coercion_family(&self) -> CoercionFamily {
864        scalar_registry!(value_coercion_family_from_registry, self)
865    }
866}
867
868impl From<Vec<Self>> for Value {
869    fn from(vec: Vec<Self>) -> Self {
870        Self::List(vec)
871    }
872}
873
874impl TryFrom<Vec<(Self, Self)>> for Value {
875    type Error = SchemaInvariantError;
876
877    fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
878        Self::from_map(entries).map_err(Self::Error::from)
879    }
880}
881
882impl From<()> for Value {
883    fn from((): ()) -> Self {
884        Self::Unit
885    }
886}
887
888// NOTE:
889// Value::partial_cmp is NOT the canonical ordering for database semantics.
890// Some orderable scalar types (e.g. Account, Unit) intentionally do not
891// participate here. Use canonical_cmp / strict ordering for ORDER BY,
892// planning, and key-range validation.
893impl PartialOrd for Value {
894    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
895        match (self, other) {
896            (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
897            (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
898            (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
899            (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
900            (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
901            (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
902            (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
903            (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
904            (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
905            (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
906            (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
907            (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
908            (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
909            (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
910            (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
911            (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
912            (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
913            (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
914            (Self::Map(a), Self::Map(b)) => {
915                for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
916                    let key_cmp = Self::canonical_cmp_key(left_key, right_key);
917                    if key_cmp != Ordering::Equal {
918                        return Some(key_cmp);
919                    }
920
921                    match left_value.partial_cmp(right_value) {
922                        Some(Ordering::Equal) => {}
923                        non_eq => return non_eq,
924                    }
925                }
926                a.len().partial_cmp(&b.len())
927            }
928
929            // Cross-type comparisons: no ordering
930            _ => None,
931        }
932    }
933}
934
935///
936/// ValueEnum
937/// handles the Enum case; `path` is optional to allow strict (typed) or loose matching.
938///
939
940#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
941pub struct ValueEnum {
942    variant: String,
943    path: Option<String>,
944    payload: Option<Box<Value>>,
945}
946
947impl ValueEnum {
948    /// Build a strict enum value matching the provided variant and path.
949    #[must_use]
950    pub fn new(variant: &str, path: Option<&str>) -> Self {
951        Self {
952            variant: variant.to_string(),
953            path: path.map(ToString::to_string),
954            payload: None,
955        }
956    }
957
958    /// Build a strict enum value using the canonical path of `E`.
959    #[must_use]
960    pub fn strict<E: Path>(variant: &str) -> Self {
961        Self::new(variant, Some(E::PATH))
962    }
963
964    /// Build a strict enum value from a domain enum using its explicit mapping.
965    #[must_use]
966    pub fn from_enum<E: EnumValue>(value: E) -> Self {
967        value.to_value_enum()
968    }
969
970    /// Build an enum value with an unresolved path for filter construction.
971    /// Query normalization resolves this to the schema enum path before validation.
972    #[must_use]
973    pub fn loose(variant: &str) -> Self {
974        Self::new(variant, None)
975    }
976
977    /// Attach an enum payload (used for data-carrying variants).
978    #[must_use]
979    pub fn with_payload(mut self, payload: Value) -> Self {
980        self.payload = Some(Box::new(payload));
981        self
982    }
983
984    #[must_use]
985    pub fn variant(&self) -> &str {
986        &self.variant
987    }
988
989    #[must_use]
990    pub fn path(&self) -> Option<&str> {
991        self.path.as_deref()
992    }
993
994    #[must_use]
995    pub fn payload(&self) -> Option<&Value> {
996        self.payload.as_deref()
997    }
998
999    pub(crate) fn set_path(&mut self, path: Option<String>) {
1000        self.path = path;
1001    }
1002}