Skip to main content

icydb_core/value/
mod.rs

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