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