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