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