icydb_core/value/
mod.rs

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