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    /// Strict comparator for identical orderable variants.
459    ///
460    /// Returns `None` for mismatched or non-orderable variants.
461    #[must_use]
462    pub(crate) fn strict_order_cmp(left: &Self, right: &Self) -> Option<Ordering> {
463        compare::strict_order_cmp(left, right)
464    }
465
466    fn numeric_repr(&self) -> NumericRepr {
467        // Numeric comparison eligibility is registry-authoritative.
468        if !self.supports_numeric_coercion() {
469            return NumericRepr::None;
470        }
471
472        if let Some(d) = self.to_decimal() {
473            return NumericRepr::Decimal(d);
474        }
475        if let Some(f) = self.to_f64_lossless() {
476            return NumericRepr::F64(f);
477        }
478        NumericRepr::None
479    }
480
481    ///
482    /// CONVERSION
483    ///
484
485    /// NOTE:
486    /// `Unit` is intentionally treated as a valid storage key and indexable,
487    /// used for singleton tables and synthetic identity entities.
488    /// Only `Null` is non-indexable.
489    #[must_use]
490    pub const fn as_storage_key(&self) -> Option<StorageKey> {
491        scalar_registry!(value_storage_key_from_registry, self)
492    }
493
494    #[must_use]
495    pub const fn as_text(&self) -> Option<&str> {
496        if let Self::Text(s) = self {
497            Some(s.as_str())
498        } else {
499            None
500        }
501    }
502
503    #[must_use]
504    pub const fn as_list(&self) -> Option<&[Self]> {
505        if let Self::List(xs) = self {
506            Some(xs.as_slice())
507        } else {
508            None
509        }
510    }
511
512    #[must_use]
513    pub const fn as_map(&self) -> Option<&[(Self, Self)]> {
514        if let Self::Map(entries) = self {
515            Some(entries.as_slice())
516        } else {
517            None
518        }
519    }
520
521    fn to_decimal(&self) -> Option<Decimal> {
522        match self {
523            Self::Decimal(d) => Some(*d),
524            Self::Duration(d) => Decimal::from_u64(d.repr()),
525            Self::Float64(f) => Decimal::from_f64(f.get()),
526            Self::Float32(f) => Decimal::from_f32(f.get()),
527            Self::Int(i) => Decimal::from_i64(*i),
528            Self::Int128(i) => Decimal::from_i128(i.get()),
529            Self::IntBig(i) => i.to_i128().and_then(Decimal::from_i128),
530            Self::Timestamp(t) => Decimal::from_i64(t.repr()),
531            Self::Uint(u) => Decimal::from_u64(*u),
532            Self::Uint128(u) => Decimal::from_u128(u.get()),
533            Self::UintBig(u) => u.to_u128().and_then(Decimal::from_u128),
534
535            _ => None,
536        }
537    }
538
539    // Internal numeric coercion helper for aggregate arithmetic.
540    pub(crate) fn to_numeric_decimal(&self) -> Option<Decimal> {
541        self.to_decimal()
542    }
543
544    // it's lossless, trust me bro
545    #[expect(clippy::cast_precision_loss)]
546    fn to_f64_lossless(&self) -> Option<f64> {
547        match self {
548            Self::Duration(d) if d.repr() <= F64_SAFE_U64 => Some(d.repr() as f64),
549            Self::Float64(f) => Some(f.get()),
550            Self::Float32(f) => Some(f64::from(f.get())),
551            Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
552            Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
553                Some(i.get() as f64)
554            }
555            Self::IntBig(i) => i.to_i128().and_then(|v| {
556                (-F64_SAFE_I128..=F64_SAFE_I128)
557                    .contains(&v)
558                    .then_some(v as f64)
559            }),
560            Self::Timestamp(t) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(&t.repr()) => {
561                Some(t.repr() as f64)
562            }
563            Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
564            Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
565            Self::UintBig(u) => u
566                .to_u128()
567                .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
568
569            _ => None,
570        }
571    }
572
573    /// Cross-type numeric comparison; returns None if non-numeric.
574    #[must_use]
575    pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
576        if !self.supports_numeric_coercion() || !other.supports_numeric_coercion() {
577            return None;
578        }
579
580        match (self.numeric_repr(), other.numeric_repr()) {
581            (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
582            (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
583            _ => None,
584        }
585    }
586
587    ///
588    /// TEXT COMPARISON
589    ///
590
591    fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
592        if s.is_ascii() {
593            return std::borrow::Cow::Owned(s.to_ascii_lowercase());
594        }
595        // NOTE: Unicode fallback — temporary to_lowercase for non‑ASCII.
596        // Future: replace with proper NFKC + full casefold when available.
597        std::borrow::Cow::Owned(s.to_lowercase())
598    }
599
600    fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
601        match mode {
602            TextMode::Cs => std::borrow::Cow::Borrowed(s),
603            TextMode::Ci => Self::fold_ci(s),
604        }
605    }
606
607    fn text_op(
608        &self,
609        other: &Self,
610        mode: TextMode,
611        f: impl Fn(&str, &str) -> bool,
612    ) -> Option<bool> {
613        let (a, b) = (self.as_text()?, other.as_text()?);
614        let a = Self::text_with_mode(a, mode);
615        let b = Self::text_with_mode(b, mode);
616        Some(f(&a, &b))
617    }
618
619    fn ci_key(&self) -> Option<String> {
620        match self {
621            Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
622            Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
623            Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
624            Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
625            _ => None,
626        }
627    }
628
629    fn eq_ci(a: &Self, b: &Self) -> bool {
630        if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
631            return ak == bk;
632        }
633
634        a == b
635    }
636
637    fn normalize_list_ref(v: &Self) -> Vec<&Self> {
638        match v {
639            Self::List(vs) => vs.iter().collect(),
640            v => vec![v],
641        }
642    }
643
644    fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
645    where
646        F: Fn(&Self, &Self) -> bool,
647    {
648        self.as_list()
649            .map(|items| items.iter().any(|v| eq(v, needle)))
650    }
651
652    #[expect(clippy::unnecessary_wraps)]
653    fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
654    where
655        F: Fn(&Self, &Self) -> bool,
656    {
657        let needles = Self::normalize_list_ref(needles);
658        match self {
659            Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
660            scalar => Some(needles.iter().any(|n| eq(scalar, n))),
661        }
662    }
663
664    #[expect(clippy::unnecessary_wraps)]
665    fn contains_all_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().all(|n| items.iter().any(|v| eq(v, n)))),
672            scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
673        }
674    }
675
676    fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
677    where
678        F: Fn(&Self, &Self) -> bool,
679    {
680        if let Self::List(items) = haystack {
681            Some(items.iter().any(|h| eq(h, self)))
682        } else {
683            None
684        }
685    }
686
687    /// Case-sensitive/insensitive equality check for text-like values.
688    #[must_use]
689    pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
690        self.text_op(other, mode, |a, b| a == b)
691    }
692
693    /// Check whether `other` is a substring of `self` under the given text mode.
694    #[must_use]
695    pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
696        self.text_op(needle, mode, |a, b| a.contains(b))
697    }
698
699    /// Check whether `self` starts with `other` under the given text mode.
700    #[must_use]
701    pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
702        self.text_op(needle, mode, |a, b| a.starts_with(b))
703    }
704
705    /// Check whether `self` ends with `other` under the given text mode.
706    #[must_use]
707    pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
708        self.text_op(needle, mode, |a, b| a.ends_with(b))
709    }
710
711    ///
712    /// EMPTY
713    ///
714
715    #[must_use]
716    pub const fn is_empty(&self) -> Option<bool> {
717        match self {
718            Self::List(xs) => Some(xs.is_empty()),
719            Self::Map(entries) => Some(entries.is_empty()),
720            Self::Text(s) => Some(s.is_empty()),
721            Self::Blob(b) => Some(b.is_empty()),
722
723            //  fields represented as Value::Null:
724            Self::Null => Some(true),
725
726            _ => None,
727        }
728    }
729
730    /// Logical negation of [`is_empty`](Self::is_empty).
731    #[must_use]
732    pub fn is_not_empty(&self) -> Option<bool> {
733        self.is_empty().map(|b| !b)
734    }
735
736    ///
737    /// COLLECTIONS
738    ///
739
740    /// Returns true if `self` contains `needle` (or equals it for scalars).
741    #[must_use]
742    pub fn contains(&self, needle: &Self) -> Option<bool> {
743        self.contains_by(needle, |a, b| a == b)
744    }
745
746    /// Returns true if any item in `needles` matches a member of `self`.
747    #[must_use]
748    pub fn contains_any(&self, needles: &Self) -> Option<bool> {
749        self.contains_any_by(needles, |a, b| a == b)
750    }
751
752    /// Returns true if every item in `needles` matches a member of `self`.
753    #[must_use]
754    pub fn contains_all(&self, needles: &Self) -> Option<bool> {
755        self.contains_all_by(needles, |a, b| a == b)
756    }
757
758    /// Returns true if `self` exists inside the provided list.
759    #[must_use]
760    pub fn in_list(&self, haystack: &Self) -> Option<bool> {
761        self.in_list_by(haystack, |a, b| a == b)
762    }
763
764    /// Case-insensitive `contains` supporting text and identifier variants.
765    #[must_use]
766    pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
767        match self {
768            Self::List(_) => self.contains_by(needle, Self::eq_ci),
769            _ => Some(Self::eq_ci(self, needle)),
770        }
771    }
772
773    /// Case-insensitive variant of [`contains_any`](Self::contains_any).
774    #[must_use]
775    pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
776        self.contains_any_by(needles, Self::eq_ci)
777    }
778
779    /// Case-insensitive variant of [`contains_all`](Self::contains_all).
780    #[must_use]
781    pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
782        self.contains_all_by(needles, Self::eq_ci)
783    }
784
785    /// Case-insensitive variant of [`in_list`](Self::in_list).
786    #[must_use]
787    pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
788        self.in_list_by(haystack, Self::eq_ci)
789    }
790}
791
792impl FieldValue for Value {
793    fn kind() -> crate::traits::FieldValueKind {
794        crate::traits::FieldValueKind::Atomic
795    }
796
797    fn to_value(&self) -> Value {
798        self.clone()
799    }
800
801    fn from_value(value: &Value) -> Option<Self> {
802        Some(value.clone())
803    }
804}
805
806#[macro_export]
807macro_rules! impl_from_for {
808    ( $( $type:ty => $variant:ident ),* $(,)? ) => {
809        $(
810            impl From<$type> for Value {
811                fn from(v: $type) -> Self {
812                    Self::$variant(v.into())
813                }
814            }
815        )*
816    };
817}
818
819impl_from_for! {
820    Account    => Account,
821    Date       => Date,
822    Decimal    => Decimal,
823    Duration   => Duration,
824    bool       => Bool,
825    i8         => Int,
826    i16        => Int,
827    i32        => Int,
828    i64        => Int,
829    i128       => Int128,
830    Int        => IntBig,
831    Principal  => Principal,
832    Subaccount => Subaccount,
833    &str       => Text,
834    String     => Text,
835    Timestamp  => Timestamp,
836    u8         => Uint,
837    u16        => Uint,
838    u32        => Uint,
839    u64        => Uint,
840    u128       => Uint128,
841    Nat        => UintBig,
842    Ulid       => Ulid,
843}
844
845impl CoercionFamilyExt for Value {
846    /// Returns the coercion-routing family for this value.
847    ///
848    /// NOTE:
849    /// This does NOT imply numeric, arithmetic, ordering, or keyability support.
850    /// All scalar capabilities are registry-driven.
851    fn coercion_family(&self) -> CoercionFamily {
852        scalar_registry!(value_coercion_family_from_registry, self)
853    }
854}
855
856impl From<Vec<Self>> for Value {
857    fn from(vec: Vec<Self>) -> Self {
858        Self::List(vec)
859    }
860}
861
862impl TryFrom<Vec<(Self, Self)>> for Value {
863    type Error = SchemaInvariantError;
864
865    fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
866        Self::from_map(entries).map_err(Self::Error::from)
867    }
868}
869
870impl From<()> for Value {
871    fn from((): ()) -> Self {
872        Self::Unit
873    }
874}
875
876// NOTE:
877// Value::partial_cmp is NOT the canonical ordering for database semantics.
878// Some orderable scalar types (e.g. Account, Unit) intentionally do not
879// participate here. Use canonical_cmp / strict ordering for ORDER BY,
880// planning, and key-range validation.
881impl PartialOrd for Value {
882    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
883        match (self, other) {
884            (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
885            (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
886            (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
887            (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
888            (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
889            (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
890            (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
891            (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
892            (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
893            (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
894            (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
895            (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
896            (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
897            (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
898            (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
899            (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
900            (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
901            (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
902            (Self::Map(a), Self::Map(b)) => {
903                for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
904                    let key_cmp = Self::canonical_cmp_key(left_key, right_key);
905                    if key_cmp != Ordering::Equal {
906                        return Some(key_cmp);
907                    }
908
909                    match left_value.partial_cmp(right_value) {
910                        Some(Ordering::Equal) => {}
911                        non_eq => return non_eq,
912                    }
913                }
914                a.len().partial_cmp(&b.len())
915            }
916
917            // Cross-type comparisons: no ordering
918            _ => None,
919        }
920    }
921}
922
923///
924/// ValueEnum
925/// handles the Enum case; `path` is optional to allow strict (typed) or loose matching.
926///
927
928#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
929pub struct ValueEnum {
930    variant: String,
931    path: Option<String>,
932    payload: Option<Box<Value>>,
933}
934
935impl ValueEnum {
936    /// Build a strict enum value matching the provided variant and path.
937    #[must_use]
938    pub fn new(variant: &str, path: Option<&str>) -> Self {
939        Self {
940            variant: variant.to_string(),
941            path: path.map(ToString::to_string),
942            payload: None,
943        }
944    }
945
946    /// Build a strict enum value using the canonical path of `E`.
947    #[must_use]
948    pub fn strict<E: Path>(variant: &str) -> Self {
949        Self::new(variant, Some(E::PATH))
950    }
951
952    /// Build a strict enum value from a domain enum using its explicit mapping.
953    #[must_use]
954    pub fn from_enum<E: EnumValue>(value: E) -> Self {
955        value.to_value_enum()
956    }
957
958    /// Build an enum value with an unresolved path for filter construction.
959    /// Query normalization resolves this to the schema enum path before validation.
960    #[must_use]
961    pub fn loose(variant: &str) -> Self {
962        Self::new(variant, None)
963    }
964
965    /// Attach an enum payload (used for data-carrying variants).
966    #[must_use]
967    pub fn with_payload(mut self, payload: Value) -> Self {
968        self.payload = Some(Box::new(payload));
969        self
970    }
971
972    #[must_use]
973    pub fn variant(&self) -> &str {
974        &self.variant
975    }
976
977    #[must_use]
978    pub fn path(&self) -> Option<&str> {
979        self.path.as_deref()
980    }
981
982    #[must_use]
983    pub fn payload(&self) -> Option<&Value> {
984        self.payload.as_deref()
985    }
986
987    pub(crate) fn set_path(&mut self, path: Option<String>) {
988        self.path = path;
989    }
990}