icydb_core/value/
mod.rs

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