Skip to main content

icydb_core/value/
mod.rs

1mod family;
2
3#[cfg(test)]
4mod tests;
5
6use crate::{
7    db::store::StorageKey,
8    prelude::*,
9    traits::{EnumValue, FieldValue, NumFromPrimitive},
10    types::*,
11};
12use candid::CandidType;
13use serde::{Deserialize, Serialize};
14use std::cmp::Ordering;
15
16// re-exports
17pub use family::{ValueFamily, ValueFamilyExt};
18
19///
20/// CONSTANTS
21///
22
23const F64_SAFE_I64: i64 = 1i64 << 53;
24const F64_SAFE_U64: u64 = 1u64 << 53;
25const F64_SAFE_I128: i128 = 1i128 << 53;
26const F64_SAFE_U128: u128 = 1u128 << 53;
27
28///
29/// NumericRepr
30///
31
32enum NumericRepr {
33    Decimal(Decimal),
34    F64(f64),
35    None,
36}
37
38///
39/// TextMode
40///
41
42#[derive(Clone, Copy, Debug, Eq, PartialEq)]
43pub enum TextMode {
44    Cs, // case-sensitive
45    Ci, // case-insensitive
46}
47
48///
49/// Value
50/// can be used in WHERE statements
51///
52/// None        → the field’s value is Option::None (i.e., SQL NULL).
53/// Unit        → internal placeholder for RHS; not a real value.
54/// Unsupported → the field exists but isn’t filterable/indexable.
55///
56
57#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
58pub enum Value {
59    Account(Account),
60    Blob(Vec<u8>),
61    Bool(bool),
62    Date(Date),
63    Decimal(Decimal),
64    Duration(Duration),
65    Enum(ValueEnum),
66    E8s(E8s),
67    E18s(E18s),
68    Float32(Float32),
69    Float64(Float64),
70    Int(i64),
71    Int128(Int128),
72    IntBig(Int),
73    /// Ordered list of values.
74    /// Used for many-cardinality transport and map-like encodings (`[key, value]` pairs).
75    /// List order is preserved for normalization and fingerprints.
76    List(Vec<Self>),
77    None,
78    Principal(Principal),
79    Subaccount(Subaccount),
80    Text(String),
81    Timestamp(Timestamp),
82    Uint(u64),
83    Uint128(Nat128),
84    UintBig(Nat),
85    Ulid(Ulid),
86    Unit,
87    Unsupported,
88}
89
90impl Value {
91    ///
92    /// CONSTRUCTION
93    ///
94
95    /// Build a `Value::List` from a slice of items convertible into `Value`.
96    pub fn from_list<T: Into<Self> + Clone>(items: &[T]) -> Self {
97        Self::List(items.iter().cloned().map(Into::into).collect())
98    }
99
100    /// Build a `Value::List` from an iterator of items convertible into `Value`
101    pub fn from_list_iter<T>(items: impl IntoIterator<Item = T>) -> Self
102    where
103        T: Into<Self>,
104    {
105        Self::List(items.into_iter().map(Into::into).collect())
106    }
107
108    /// Build a `Value::Enum` from a domain enum using its explicit mapping.
109    pub fn from_enum<E: EnumValue>(value: E) -> Self {
110        Self::Enum(value.to_value_enum())
111    }
112
113    /// Build a strict enum value using the canonical path of `E`.
114    #[must_use]
115    pub fn enum_strict<E: Path>(variant: &str) -> Self {
116        Self::Enum(ValueEnum::strict::<E>(variant))
117    }
118
119    ///
120    /// TYPES
121    ///
122
123    /// Returns true if the value is one of the numeric-like variants
124    /// supported by numeric comparison/ordering.
125    #[must_use]
126    pub const fn is_numeric(&self) -> bool {
127        matches!(
128            self,
129            Self::Decimal(_)
130                | Self::Duration(_)
131                | Self::E8s(_)
132                | Self::E18s(_)
133                | Self::Float32(_)
134                | Self::Float64(_)
135                | Self::Int(_)
136                | Self::Int128(_)
137                | Self::Timestamp(_)
138                | Self::Uint(_)
139                | Self::Uint128(_)
140        )
141    }
142
143    /// Returns true if the value is Text.
144    #[must_use]
145    pub const fn is_text(&self) -> bool {
146        matches!(self, Self::Text(_))
147    }
148
149    /// Returns true if the value is Unit (used for presence/null comparators).
150    #[must_use]
151    pub const fn is_unit(&self) -> bool {
152        matches!(self, Self::Unit)
153    }
154
155    #[must_use]
156    pub const fn is_scalar(&self) -> bool {
157        match self {
158            // definitely not scalar:
159            Self::List(_) | Self::Unit => false,
160            _ => true,
161        }
162    }
163
164    fn numeric_repr(&self) -> NumericRepr {
165        if let Some(d) = self.to_decimal() {
166            return NumericRepr::Decimal(d);
167        }
168        if let Some(f) = self.to_f64_lossless() {
169            return NumericRepr::F64(f);
170        }
171        NumericRepr::None
172    }
173
174    ///
175    /// CONVERSION
176    ///
177
178    /// NOTE:
179    /// `Unit` is intentionally treated as a valid storage key and indexable,
180    /// used for singleton tables and synthetic identity entities.
181    /// Only `None` and `Unsupported` are non-indexable.
182    #[must_use]
183    pub const fn as_storage_key(&self) -> Option<StorageKey> {
184        match self {
185            Self::Account(v) => Some(StorageKey::Account(*v)),
186            Self::Int(v) => Some(StorageKey::Int(*v)),
187            Self::Uint(v) => Some(StorageKey::Uint(*v)),
188            Self::Principal(v) => Some(StorageKey::Principal(*v)),
189            Self::Subaccount(v) => Some(StorageKey::Subaccount(*v)),
190            Self::Timestamp(v) => Some(StorageKey::Timestamp(*v)),
191            Self::Ulid(v) => Some(StorageKey::Ulid(*v)),
192            Self::Unit => Some(StorageKey::Unit),
193            _ => None,
194        }
195    }
196
197    #[must_use]
198    pub const fn as_text(&self) -> Option<&str> {
199        if let Self::Text(s) = self {
200            Some(s.as_str())
201        } else {
202            None
203        }
204    }
205
206    #[must_use]
207    pub const fn as_list(&self) -> Option<&[Self]> {
208        if let Self::List(xs) = self {
209            Some(xs.as_slice())
210        } else {
211            None
212        }
213    }
214
215    fn to_decimal(&self) -> Option<Decimal> {
216        match self {
217            Self::Decimal(d) => Some(*d),
218            Self::Duration(d) => Decimal::from_u64(d.get()),
219            Self::E8s(v) => Some(v.to_decimal()),
220            Self::E18s(v) => v.to_decimal(),
221            Self::Float64(f) => Decimal::from_f64(f.get()),
222            Self::Float32(f) => Decimal::from_f32(f.get()),
223            Self::Int(i) => Decimal::from_i64(*i),
224            Self::Int128(i) => Decimal::from_i128(i.get()),
225            Self::IntBig(i) => i.to_i128().and_then(Decimal::from_i128),
226            Self::Timestamp(t) => Decimal::from_u64(t.get()),
227            Self::Uint(u) => Decimal::from_u64(*u),
228            Self::Uint128(u) => Decimal::from_u128(u.get()),
229            Self::UintBig(u) => u.to_u128().and_then(Decimal::from_u128),
230
231            _ => None,
232        }
233    }
234
235    // it's lossless, trust me bro
236    #[allow(clippy::cast_precision_loss)]
237    fn to_f64_lossless(&self) -> Option<f64> {
238        match self {
239            Self::Duration(d) if d.get() <= F64_SAFE_U64 => Some(d.get() as f64),
240            Self::Float64(f) => Some(f.get()),
241            Self::Float32(f) => Some(f64::from(f.get())),
242            Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
243            Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
244                Some(i.get() as f64)
245            }
246            Self::IntBig(i) => i.to_i128().and_then(|v| {
247                (-F64_SAFE_I128..=F64_SAFE_I128)
248                    .contains(&v)
249                    .then_some(v as f64)
250            }),
251            Self::Timestamp(t) if t.get() <= F64_SAFE_U64 => Some(t.get() as f64),
252            Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
253            Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
254            Self::UintBig(u) => u
255                .to_u128()
256                .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
257
258            _ => None,
259        }
260    }
261
262    /// Cross-type numeric comparison; returns None if non-numeric.
263    #[must_use]
264    pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
265        match (self.numeric_repr(), other.numeric_repr()) {
266            (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
267            (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
268            _ => None,
269        }
270    }
271
272    ///
273    /// TEXT COMPARISON
274    ///
275
276    fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
277        if s.is_ascii() {
278            return std::borrow::Cow::Owned(s.to_ascii_lowercase());
279        }
280        // NOTE: Unicode fallback — temporary to_lowercase for non‑ASCII.
281        // Future: replace with proper NFKC + full casefold when available.
282        std::borrow::Cow::Owned(s.to_lowercase())
283    }
284
285    fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
286        match mode {
287            TextMode::Cs => std::borrow::Cow::Borrowed(s),
288            TextMode::Ci => Self::fold_ci(s),
289        }
290    }
291
292    fn text_op(
293        &self,
294        other: &Self,
295        mode: TextMode,
296        f: impl Fn(&str, &str) -> bool,
297    ) -> Option<bool> {
298        let (a, b) = (self.as_text()?, other.as_text()?);
299        let a = Self::text_with_mode(a, mode);
300        let b = Self::text_with_mode(b, mode);
301        Some(f(&a, &b))
302    }
303
304    fn ci_key(&self) -> Option<String> {
305        match self {
306            Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
307            Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
308            Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
309            Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
310            _ => None,
311        }
312    }
313
314    fn eq_ci(a: &Self, b: &Self) -> bool {
315        if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
316            return ak == bk;
317        }
318
319        a == b
320    }
321
322    fn normalize_list_ref(v: &Self) -> Vec<&Self> {
323        match v {
324            Self::List(vs) => vs.iter().collect(),
325            v => vec![v],
326        }
327    }
328
329    fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
330    where
331        F: Fn(&Self, &Self) -> bool,
332    {
333        self.as_list()
334            .map(|items| items.iter().any(|v| eq(v, needle)))
335    }
336
337    #[allow(clippy::unnecessary_wraps)]
338    fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
339    where
340        F: Fn(&Self, &Self) -> bool,
341    {
342        let needles = Self::normalize_list_ref(needles);
343        match self {
344            Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
345            scalar => Some(needles.iter().any(|n| eq(scalar, n))),
346        }
347    }
348
349    #[allow(clippy::unnecessary_wraps)]
350    fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
351    where
352        F: Fn(&Self, &Self) -> bool,
353    {
354        let needles = Self::normalize_list_ref(needles);
355        match self {
356            Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
357            scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
358        }
359    }
360
361    fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
362    where
363        F: Fn(&Self, &Self) -> bool,
364    {
365        if let Self::List(items) = haystack {
366            Some(items.iter().any(|h| eq(h, self)))
367        } else {
368            None
369        }
370    }
371
372    #[must_use]
373    /// Case-sensitive/insensitive equality check for text-like values.
374    pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
375        self.text_op(other, mode, |a, b| a == b)
376    }
377
378    #[must_use]
379    /// Check whether `other` is a substring of `self` under the given text mode.
380    pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
381        self.text_op(needle, mode, |a, b| a.contains(b))
382    }
383
384    #[must_use]
385    /// Check whether `self` starts with `other` under the given text mode.
386    pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
387        self.text_op(needle, mode, |a, b| a.starts_with(b))
388    }
389
390    #[must_use]
391    /// Check whether `self` ends with `other` under the given text mode.
392    pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
393        self.text_op(needle, mode, |a, b| a.ends_with(b))
394    }
395
396    ///
397    /// EMPTY
398    ///
399
400    #[must_use]
401    pub const fn is_empty(&self) -> Option<bool> {
402        match self {
403            Self::List(xs) => Some(xs.is_empty()),
404            Self::Text(s) => Some(s.is_empty()),
405            Self::Blob(b) => Some(b.is_empty()),
406
407            //  fields represented as Value::None:
408            Self::None => Some(true),
409
410            _ => None,
411        }
412    }
413
414    #[must_use]
415    /// Logical negation of [`is_empty`](Self::is_empty).
416    pub fn is_not_empty(&self) -> Option<bool> {
417        self.is_empty().map(|b| !b)
418    }
419
420    ///
421    /// COLLECTIONS
422    ///
423
424    #[must_use]
425    /// Returns true if `self` contains `needle` (or equals it for scalars).
426    pub fn contains(&self, needle: &Self) -> Option<bool> {
427        self.contains_by(needle, |a, b| a == b)
428    }
429
430    #[must_use]
431    /// Returns true if any item in `needles` matches a member of `self`.
432    pub fn contains_any(&self, needles: &Self) -> Option<bool> {
433        self.contains_any_by(needles, |a, b| a == b)
434    }
435
436    #[must_use]
437    /// Returns true if every item in `needles` matches a member of `self`.
438    pub fn contains_all(&self, needles: &Self) -> Option<bool> {
439        self.contains_all_by(needles, |a, b| a == b)
440    }
441
442    #[must_use]
443    /// Returns true if `self` exists inside the provided list.
444    pub fn in_list(&self, haystack: &Self) -> Option<bool> {
445        self.in_list_by(haystack, |a, b| a == b)
446    }
447
448    #[must_use]
449    /// Case-insensitive `contains` supporting text and identifier variants.
450    pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
451        match self {
452            Self::List(_) => self.contains_by(needle, Self::eq_ci),
453            _ => Some(Self::eq_ci(self, needle)),
454        }
455    }
456
457    #[must_use]
458    /// Case-insensitive variant of [`contains_any`](Self::contains_any).
459    pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
460        self.contains_any_by(needles, Self::eq_ci)
461    }
462
463    #[must_use]
464    /// Case-insensitive variant of [`contains_all`](Self::contains_all).
465    pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
466        self.contains_all_by(needles, Self::eq_ci)
467    }
468
469    #[must_use]
470    /// Case-insensitive variant of [`in_list`](Self::in_list).
471    pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
472        self.in_list_by(haystack, Self::eq_ci)
473    }
474}
475
476#[macro_export]
477macro_rules! impl_from_for {
478    ( $( $type:ty => $variant:ident ),* $(,)? ) => {
479        $(
480            impl From<$type> for Value {
481                fn from(v: $type) -> Self {
482                    Self::$variant(v.into())
483                }
484            }
485        )*
486    };
487}
488
489impl_from_for! {
490    Account    => Account,
491    Date       => Date,
492    Decimal    => Decimal,
493    Duration   => Duration,
494    E8s        => E8s,
495    E18s       => E18s,
496    bool       => Bool,
497    i8         => Int,
498    i16        => Int,
499    i32        => Int,
500    i64        => Int,
501    i128       => Int128,
502    Int        => IntBig,
503    Principal  => Principal,
504    Subaccount => Subaccount,
505    &str       => Text,
506    String     => Text,
507    Timestamp  => Timestamp,
508    u8         => Uint,
509    u16        => Uint,
510    u32        => Uint,
511    u64        => Uint,
512    u128       => Uint128,
513    Nat        => UintBig,
514    Ulid       => Ulid,
515}
516
517impl ValueFamilyExt for Value {
518    fn family(&self) -> ValueFamily {
519        match self {
520            // Numeric
521            Self::Date(_)
522            | Self::Decimal(_)
523            | Self::Duration(_)
524            | Self::E8s(_)
525            | Self::E18s(_)
526            | Self::Float32(_)
527            | Self::Float64(_)
528            | Self::Int(_)
529            | Self::Int128(_)
530            | Self::Timestamp(_)
531            | Self::Uint(_)
532            | Self::Uint128(_)
533            | Self::IntBig(_)
534            | Self::UintBig(_) => ValueFamily::Numeric,
535
536            // Text
537            Self::Text(_) => ValueFamily::Textual,
538
539            // Identifiers
540            Self::Ulid(_) | Self::Principal(_) | Self::Account(_) => ValueFamily::Identifier,
541
542            // Enum
543            Self::Enum(_) => ValueFamily::Enum,
544
545            // Collections
546            Self::List(_) => ValueFamily::Collection,
547
548            // Blobs
549            Self::Blob(_) | Self::Subaccount(_) => ValueFamily::Blob,
550
551            // Bool
552            Self::Bool(_) => ValueFamily::Bool,
553
554            // Null / Unit
555            Self::None => ValueFamily::Null,
556            Self::Unit => ValueFamily::Unit,
557
558            // Everything else
559            Self::Unsupported => ValueFamily::Unsupported,
560        }
561    }
562}
563
564impl FieldValue for Value {
565    fn to_value(&self) -> Value {
566        self.clone()
567    }
568}
569
570impl<E: EntityIdentity> From<Ref<E>> for Value {
571    fn from(r: Ref<E>) -> Self {
572        r.to_value() // via FieldValue
573    }
574}
575
576impl From<Vec<Self>> for Value {
577    fn from(vec: Vec<Self>) -> Self {
578        Self::List(vec)
579    }
580}
581
582impl From<()> for Value {
583    fn from((): ()) -> Self {
584        Self::Unit
585    }
586}
587
588impl PartialOrd for Value {
589    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
590        match (self, other) {
591            (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
592            (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
593            (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
594            (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
595            (Self::E8s(a), Self::E8s(b)) => a.partial_cmp(b),
596            (Self::E18s(a), Self::E18s(b)) => a.partial_cmp(b),
597            (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
598            (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
599            (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
600            (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
601            (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
602            (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
603            (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
604            (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
605            (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
606            (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
607            (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
608            (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
609            (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
610            (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
611
612            // Cross-type comparisons: no ordering
613            _ => None,
614        }
615    }
616}
617
618///
619/// ValueEnum
620/// handles the Enum case; `path` is optional to allow strict (typed) or loose matching.
621///
622
623#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
624pub struct ValueEnum {
625    pub variant: String,
626    pub path: Option<String>,
627    pub payload: Option<Box<Value>>,
628}
629
630impl ValueEnum {
631    #[must_use]
632    /// Build a strict enum value matching the provided variant and path.
633    pub fn new(variant: &str, path: Option<&str>) -> Self {
634        Self {
635            variant: variant.to_string(),
636            path: path.map(ToString::to_string),
637            payload: None,
638        }
639    }
640
641    #[must_use]
642    /// Build a strict enum value using the canonical path of `E`.
643    pub fn strict<E: Path>(variant: &str) -> Self {
644        Self::new(variant, Some(E::PATH))
645    }
646
647    #[must_use]
648    /// Build a strict enum value from a domain enum using its explicit mapping.
649    pub fn from_enum<E: EnumValue>(value: E) -> Self {
650        value.to_value_enum()
651    }
652
653    #[must_use]
654    /// Build an enum value that ignores the path for loose matching.
655    pub fn loose(variant: &str) -> Self {
656        Self::new(variant, None)
657    }
658
659    #[must_use]
660    /// Attach an enum payload (used for data-carrying variants).
661    pub fn with_payload(mut self, payload: Value) -> Self {
662        self.payload = Some(Box::new(payload));
663        self
664    }
665}