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