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