Skip to main content

icydb_core/value/
mod.rs

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