Skip to main content

icydb_core/value/
mod.rs

1//! Module: value
2//!
3//! Responsibility: canonical dynamic value representation plus primary-key helpers.
4//! Does not own: planner semantics or db-level decode policy.
5//! Boundary: shared value/domain surface used by query, executor, and storage layers.
6//!
7//! `Value` is the runtime canonical value model. Public canister/query boundaries
8//! should prefer `InputValue` for caller-supplied literals and `OutputValue` for
9//! result payloads, so API surfaces do not depend on runtime execution internals.
10
11mod canonical;
12mod canonical_enum;
13mod coercion;
14mod compare;
15mod hash;
16mod input;
17mod map;
18pub(crate) mod ops;
19mod output;
20mod rank;
21mod semantics;
22mod tag;
23mod wire;
24
25#[cfg(test)]
26mod tests;
27
28use crate::{
29    traits::{RuntimeValueDecode, RuntimeValueEncode, RuntimeValueMeta},
30    types::*,
31};
32use serde::{Deserialize, Deserializer, de};
33use std::{cmp::Ordering, fmt};
34
35// re-exports
36pub(crate) use canonical::canonicalize_value_set;
37pub(crate) use canonical_enum::{CanonicalEnumBody, CanonicalEnumValue, EnumTypeId, EnumVariantId};
38pub use coercion::{CoercionFamily, CoercionFamilyExt};
39#[cfg(test)]
40pub(crate) use hash::with_test_hash_override;
41pub(crate) use hash::{ValueHashWriter, hash_single_list_identity_canonical_value, hash_value};
42pub use input::{InputValue, InputValueEnum};
43pub use map::{MapValueError, SchemaInvariantError};
44pub use output::{OutputValue, OutputValueEnum, render_output_value_text};
45pub use tag::ValueTag;
46
47//
48// CONSTANTS
49//
50
51const VALUE_WIRE_TYPE_NAME: &str = "Value";
52const VALUE_WIRE_VARIANT_LABELS: &[&str] = &[
53    "Account",
54    "Blob",
55    "Bool",
56    "Date",
57    "Decimal",
58    "Duration",
59    "Enum",
60    "Float32",
61    "Float64",
62    "Int",
63    "Int128",
64    "IntBig",
65    "List",
66    "Map",
67    "Null",
68    "Principal",
69    "Subaccount",
70    "Text",
71    "Timestamp",
72    "Nat",
73    "Nat128",
74    "NatBig",
75    "Ulid",
76    "Unit",
77];
78
79// Name and discriminant owner for the stable `Value` serde wire shape.
80#[derive(Clone, Copy)]
81enum ValueWireVariant {
82    Account,
83    Blob,
84    Bool,
85    Date,
86    Decimal,
87    Duration,
88    Enum,
89    Float32,
90    Float64,
91    Int64,
92    Int128,
93    IntBig,
94    List,
95    Map,
96    Null,
97    Principal,
98    Subaccount,
99    Text,
100    Timestamp,
101    Nat64,
102    Nat128,
103    NatBig,
104    Ulid,
105    Unit,
106}
107
108impl ValueWireVariant {
109    // Resolve one stable serde variant label back to its runtime discriminant.
110    fn from_label(label: &str) -> Option<Self> {
111        match label {
112            "Account" => Some(Self::Account),
113            "Blob" => Some(Self::Blob),
114            "Bool" => Some(Self::Bool),
115            "Date" => Some(Self::Date),
116            "Decimal" => Some(Self::Decimal),
117            "Duration" => Some(Self::Duration),
118            "Enum" => Some(Self::Enum),
119            "Float32" => Some(Self::Float32),
120            "Float64" => Some(Self::Float64),
121            "Int" => Some(Self::Int64),
122            "Int128" => Some(Self::Int128),
123            "IntBig" => Some(Self::IntBig),
124            "List" => Some(Self::List),
125            "Map" => Some(Self::Map),
126            "Null" => Some(Self::Null),
127            "Principal" => Some(Self::Principal),
128            "Subaccount" => Some(Self::Subaccount),
129            "Text" => Some(Self::Text),
130            "Timestamp" => Some(Self::Timestamp),
131            "Nat" => Some(Self::Nat64),
132            "Nat128" => Some(Self::Nat128),
133            "NatBig" => Some(Self::NatBig),
134            "Ulid" => Some(Self::Ulid),
135            "Unit" => Some(Self::Unit),
136            _ => None,
137        }
138    }
139}
140
141//
142// TextMode
143//
144
145#[derive(Clone, Copy, Debug, Eq, PartialEq)]
146pub enum TextMode {
147    Cs, // case-sensitive
148    Ci, // case-insensitive
149}
150
151//
152// Value
153//
154// Runtime-only dynamic value used by query evaluation, SQL expressions,
155// projection materialization, predicates, cursor payloads, and intermediate
156// execution state.
157//
158// Value is intentionally not a persisted field type. Schema persistence must
159// admit it through an accepted field contract before selecting a storage codec.
160//
161// Null        → the field’s value is Option::None (i.e., SQL NULL).
162// Unit        → internal placeholder for RHS; not a real value.
163//
164#[derive(Clone, Eq, PartialEq)]
165pub enum Value {
166    Account(Account),
167    Blob(Vec<u8>),
168    Bool(bool),
169    Date(Date),
170    Decimal(Decimal),
171    Duration(Duration),
172    Enum(ValueEnum),
173    Float32(Float32),
174    Float64(Float64),
175    Int64(i64),
176    Int128(i128),
177    IntBig(IntBig),
178    /// Ordered list of values.
179    /// Used for many-cardinality transport.
180    /// List order is preserved for normalization and fingerprints.
181    List(Vec<Self>),
182    /// Canonical deterministic map representation.
183    ///
184    /// - Maps are unordered values; insertion order is discarded.
185    /// - Entries are always sorted by canonical key order and keys are unique.
186    /// - Map fields remain non-queryable and persist as atomic value replacements.
187    /// - Persistence treats map fields as atomic value replacements per row save.
188    Map(Vec<(Self, Self)>),
189    Null,
190    Principal(Principal),
191    Subaccount(Subaccount),
192    Text(String),
193    Timestamp(Timestamp),
194    Nat64(u64),
195    Nat128(u128),
196    NatBig(NatBig),
197    Ulid(Ulid),
198    Unit,
199}
200
201impl fmt::Debug for Value {
202    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203        match self {
204            Self::Account(value) => f.debug_tuple("Account").field(value).finish(),
205            Self::Blob(value) => write!(f, "Blob({} bytes)", value.len()),
206            Self::Bool(value) => f.debug_tuple("Bool").field(value).finish(),
207            Self::Date(value) => f.debug_tuple("Date").field(value).finish(),
208            Self::Decimal(value) => f.debug_tuple("Decimal").field(value).finish(),
209            Self::Duration(value) => f.debug_tuple("Duration").field(value).finish(),
210            Self::Enum(value) => f.debug_tuple("Enum").field(value).finish(),
211            Self::Float32(value) => f.debug_tuple("Float32").field(value).finish(),
212            Self::Float64(value) => f.debug_tuple("Float64").field(value).finish(),
213            Self::Int64(value) => f.debug_tuple("Int64").field(value).finish(),
214            Self::Int128(value) => f.debug_tuple("Int128").field(value).finish(),
215            Self::IntBig(value) => f.debug_tuple("IntBig").field(value).finish(),
216            Self::List(value) => f.debug_tuple("List").field(value).finish(),
217            Self::Map(value) => f.debug_tuple("Map").field(value).finish(),
218            Self::Null => f.write_str("Null"),
219            Self::Principal(value) => f.debug_tuple("Principal").field(value).finish(),
220            Self::Subaccount(value) => f.debug_tuple("Subaccount").field(value).finish(),
221            Self::Text(value) => f.debug_tuple("Text").field(value).finish(),
222            Self::Timestamp(value) => f.debug_tuple("Timestamp").field(value).finish(),
223            Self::Nat64(value) => f.debug_tuple("Nat64").field(value).finish(),
224            Self::Nat128(value) => f.debug_tuple("Nat128").field(value).finish(),
225            Self::NatBig(value) => f.debug_tuple("NatBig").field(value).finish(),
226            Self::Ulid(value) => f.debug_tuple("Ulid").field(value).finish(),
227            Self::Unit => f.write_str("Unit"),
228        }
229    }
230}
231
232impl Value {
233    ///
234    /// CONSTRUCTION
235    ///
236
237    /// Build a `Value::List` from a list literal.
238    ///
239    /// Intended for tests and inline construction.
240    /// Requires `Clone` because items are borrowed.
241    pub fn from_slice<T>(items: &[T]) -> Self
242    where
243        T: Into<Self> + Clone,
244    {
245        Self::List(items.iter().cloned().map(Into::into).collect())
246    }
247
248    /// Build a `Value::List` from owned items.
249    ///
250    /// This is the canonical constructor for query / DTO boundaries.
251    pub fn from_list<T>(items: Vec<T>) -> Self
252    where
253        T: Into<Self>,
254    {
255        Self::List(items.into_iter().map(Into::into).collect())
256    }
257
258    /// Build a canonical `Value::Map` from owned key/value entries.
259    ///
260    /// Invariants are validated and entries are normalized:
261    /// - keys must be scalar and non-null
262    /// - values may be scalar or structured
263    /// - entries are sorted by canonical key order
264    /// - duplicate keys are rejected
265    pub fn from_map(entries: Vec<(Self, Self)>) -> Result<Self, MapValueError> {
266        let normalized = map::normalize_map_entries(entries)?;
267        Ok(Self::Map(normalized))
268    }
269
270    ///
271    /// TYPES
272    ///
273
274    /// Returns true if the value is Text.
275    #[must_use]
276    pub const fn is_text(&self) -> bool {
277        matches!(self, Self::Text(_))
278    }
279
280    /// Returns true if the value is Unit (used for presence/null comparators).
281    #[must_use]
282    pub const fn is_unit(&self) -> bool {
283        matches!(self, Self::Unit)
284    }
285
286    #[must_use]
287    pub const fn is_scalar(&self) -> bool {
288        match self {
289            // definitely not scalar:
290            Self::List(_) | Self::Map(_) | Self::Unit => false,
291            _ => true,
292        }
293    }
294
295    /// Return whether this runtime value contains canonical enum identity.
296    #[must_use]
297    pub(crate) fn contains_enum(&self) -> bool {
298        match self {
299            Self::Enum(_) => true,
300            Self::List(values) => values.iter().any(Self::contains_enum),
301            Self::Map(entries) => entries
302                .iter()
303                .any(|(key, value)| key.contains_enum() || value.contains_enum()),
304            _ => false,
305        }
306    }
307
308    /// Stable canonical variant tag used by hash/fingerprint encodings.
309    #[must_use]
310    pub(crate) const fn canonical_tag(&self) -> ValueTag {
311        tag::canonical_tag(self)
312    }
313
314    /// Stable canonical rank used by all cross-variant ordering surfaces.
315    #[must_use]
316    pub(crate) const fn canonical_rank(&self) -> u8 {
317        rank::canonical_rank(self)
318    }
319
320    /// Total canonical comparator used by planner/predicate/fingerprint surfaces.
321    #[must_use]
322    pub(crate) fn canonical_cmp(left: &Self, right: &Self) -> Ordering {
323        compare::canonical_cmp(left, right)
324    }
325
326    /// Total canonical comparator used for map-key normalization.
327    #[must_use]
328    pub(crate) fn canonical_cmp_key(left: &Self, right: &Self) -> Ordering {
329        compare::canonical_cmp_key(left, right)
330    }
331
332    ///
333    /// CONVERSION
334    ///
335
336    #[must_use]
337    pub const fn as_text(&self) -> Option<&str> {
338        if let Self::Text(s) = self {
339            Some(s.as_str())
340        } else {
341            None
342        }
343    }
344
345    #[must_use]
346    pub const fn as_list(&self) -> Option<&[Self]> {
347        if let Self::List(xs) = self {
348            Some(xs.as_slice())
349        } else {
350            None
351        }
352    }
353
354    #[must_use]
355    pub const fn as_map(&self) -> Option<&[(Self, Self)]> {
356        if let Self::Map(entries) = self {
357            Some(entries.as_slice())
358        } else {
359            None
360        }
361    }
362}
363
364impl RuntimeValueMeta for Value {
365    fn kind() -> crate::traits::RuntimeValueKind {
366        crate::traits::RuntimeValueKind::Atomic
367    }
368}
369
370impl RuntimeValueEncode for Value {
371    fn to_value(&self) -> Value {
372        self.clone()
373    }
374}
375
376impl RuntimeValueDecode for Value {
377    fn from_value(value: &Value) -> Option<Self> {
378        Some(value.clone())
379    }
380}
381
382macro_rules! impl_from_for {
383    ( $( $type:ty => $variant:ident ),* $(,)? ) => {
384        $(
385            impl From<$type> for Value {
386                fn from(v: $type) -> Self {
387                    Self::$variant(v.into())
388                }
389            }
390        )*
391    };
392}
393
394impl_from_for! {
395    Account    => Account,
396    Date       => Date,
397    Decimal    => Decimal,
398    Duration   => Duration,
399    bool       => Bool,
400    i8         => Int64,
401    i16        => Int64,
402    i32        => Int64,
403    i64        => Int64,
404    i128       => Int128,
405    IntBig     => IntBig,
406    Principal  => Principal,
407    Subaccount => Subaccount,
408    &str       => Text,
409    String     => Text,
410    Timestamp  => Timestamp,
411    u8         => Nat64,
412    u16        => Nat64,
413    u32        => Nat64,
414    u64        => Nat64,
415    u128       => Nat128,
416    NatBig     => NatBig,
417    Ulid       => Ulid,
418}
419
420impl From<Vec<Self>> for Value {
421    fn from(vec: Vec<Self>) -> Self {
422        Self::List(vec)
423    }
424}
425
426impl TryFrom<Vec<(Self, Self)>> for Value {
427    type Error = SchemaInvariantError;
428
429    fn try_from(entries: Vec<(Self, Self)>) -> Result<Self, Self::Error> {
430        Self::from_map(entries).map_err(Self::Error::from)
431    }
432}
433
434impl From<()> for Value {
435    fn from((): ()) -> Self {
436        Self::Unit
437    }
438}
439
440//
441// ValueEnum
442// Canonical store-local enum identity. Names exist only at input/output boundaries.
443//
444
445#[derive(Clone, Debug, Eq, PartialEq, PartialOrd)]
446pub struct ValueEnum(CanonicalEnumValue<Value>);
447
448impl ValueEnum {
449    #[cfg(test)]
450    pub(crate) const fn test_unit(type_id: u32, variant_id: u32) -> Self {
451        Self::new(
452            EnumTypeId::new(type_id).expect("test enum type ID must be non-zero"),
453            EnumVariantId::new(variant_id).expect("test enum variant ID must be non-zero"),
454            CanonicalEnumBody::Unit,
455        )
456    }
457
458    #[cfg(test)]
459    pub(crate) fn test_payload(type_id: u32, variant_id: u32, payload: Value) -> Self {
460        Self::new(
461            EnumTypeId::new(type_id).expect("test enum type ID must be non-zero"),
462            EnumVariantId::new(variant_id).expect("test enum variant ID must be non-zero"),
463            CanonicalEnumBody::Payload(Box::new(payload)),
464        )
465    }
466
467    #[cfg(test)]
468    pub(crate) fn test_with_payload(self, payload: Value) -> Self {
469        Self::new(
470            self.type_id(),
471            self.variant_id(),
472            CanonicalEnumBody::Payload(Box::new(payload)),
473        )
474    }
475
476    #[must_use]
477    pub(crate) const fn from_canonical(value: CanonicalEnumValue<Value>) -> Self {
478        Self(value)
479    }
480
481    #[must_use]
482    pub(crate) const fn new(
483        type_id: EnumTypeId,
484        variant_id: EnumVariantId,
485        body: CanonicalEnumBody<Value>,
486    ) -> Self {
487        Self(CanonicalEnumValue::new(type_id, variant_id, body))
488    }
489
490    #[must_use]
491    pub(crate) const fn canonical(&self) -> &CanonicalEnumValue<Value> {
492        &self.0
493    }
494
495    #[must_use]
496    pub(crate) const fn type_id(&self) -> EnumTypeId {
497        self.0.type_id()
498    }
499
500    #[must_use]
501    pub(crate) const fn variant_id(&self) -> EnumVariantId {
502        self.0.variant_id()
503    }
504
505    #[must_use]
506    pub(crate) const fn body(&self) -> &CanonicalEnumBody<Value> {
507        self.0.body()
508    }
509
510    #[must_use]
511    pub(crate) fn payload(&self) -> Option<&Value> {
512        match self.body() {
513            CanonicalEnumBody::Unit => None,
514            CanonicalEnumBody::Payload(payload) => Some(payload.as_ref()),
515        }
516    }
517}
518
519impl<'de> Deserialize<'de> for ValueEnum {
520    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
521    where
522        D: Deserializer<'de>,
523    {
524        let (type_id, variant_id, payload): (u32, u32, Option<Box<Value>>) =
525            Deserialize::deserialize(deserializer)?;
526        let type_id = EnumTypeId::new(type_id)
527            .ok_or_else(|| de::Error::custom("enum type ID must be non-zero"))?;
528        let variant_id = EnumVariantId::new(variant_id)
529            .ok_or_else(|| de::Error::custom("enum variant ID must be non-zero"))?;
530        let body = payload.map_or(CanonicalEnumBody::Unit, CanonicalEnumBody::Payload);
531        Ok(Self::new(type_id, variant_id, body))
532    }
533}