Skip to main content

icydb_core/value/
mod.rs

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