Skip to main content

ic_db/
key.rs

1//! Exact typed index operands and ordered component bytes; no query execution.
2
3use crate::{
4    Account, Date, Decimal, Duration, Error, FieldType, Float32, Float64, Principal, Subaccount,
5    Timestamp, TypeSchema, U256, Ulid, codec::Decoder, types::unit_enum_len,
6};
7
8/// One exact ordered scalar operand for index prefixes and fluent comparisons.
9/// Operand types must match declared fields;
10/// integers are never implicitly widened, narrowed or coerced across signedness.
11/// This is a bounded scalar boundary, not a general expression/value representation.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum IndexValue<'a> {
14    /// An absent optional component, ordered before present values.
15    Absent,
16    /// Exact u8 component.
17    Nat8(u8),
18    /// Exact u16 component.
19    Nat16(u16),
20    /// Exact u32 component.
21    Nat32(u32),
22    /// Exact u64 component.
23    Nat64(u64),
24    /// Exact u128 component.
25    Nat128(u128),
26    /// Exact unsigned 256-bit component, without narrower-integer coercion.
27    U256(U256),
28    /// Exact ULID identity, without integer or text coercion.
29    Ulid(Ulid),
30    /// Exact bounded calendar date; no integer or text coercion.
31    Date(Date),
32    /// Exact millisecond duration; no integer coercion.
33    Duration(Duration),
34    /// Exact decimal; the declared field scale must represent it without rounding.
35    Decimal(Decimal),
36    /// Exact millisecond timestamp; no integer coercion.
37    Timestamp(Timestamp),
38    /// Exact account identity; no coercion from another key type.
39    Account(Account),
40    /// Exact subaccount identity; no coercion from another key type.
41    Subaccount(Subaccount),
42    /// Finite canonical 64-bit float; no cross-width or integer coercion.
43    Float64(Float64),
44    /// Finite canonical 32-bit float; no cross-width or integer coercion.
45    Float32(Float32),
46    /// Exact i8 component.
47    Int8(i8),
48    /// Exact i16 component.
49    Int16(i16),
50    /// Exact i32 component.
51    Int32(i32),
52    /// Exact i64 component.
53    Int64(i64),
54    /// Exact i128 component.
55    Int128(i128),
56    /// Canonical identity, ordered by length then significant bytes.
57    Principal(Principal),
58    /// False sorts before true; no numeric coercion.
59    Bool(bool),
60    /// Exact UTF-8 bytes, without case folding or normalization.
61    Text(&'a str),
62    /// Exact raw bytes in lexicographic order; shorter byte prefixes sort first.
63    Blob(&'a [u8]),
64    /// Unit enum in canonical variant-name order, bound to its complete definition.
65    UnitEnum {
66        /// Declared enum identity and alternatives.
67        definition: &'static TypeSchema,
68        /// Zero-based ordinal in canonical variant-name order.
69        ordinal: u8,
70    },
71}
72
73// Scalar wrappers preserve their schema name during admission and projection.
74// Key encoding and fluent operands use the existing primitive semantics.
75pub(crate) fn operand_type(field: FieldType) -> FieldType {
76    if let FieldType::Named(link) = field
77        && let crate::TypeBody::Wrapped(inner) = (link.definition)().body
78    {
79        return inner;
80    }
81
82    field
83}
84impl<'a> IndexValue<'a> {
85    // Planner operands have passed admission, including the complete enum definition.
86    pub(crate) fn discrete_successor(self) -> Option<Self> {
87        if let Self::UnitEnum {
88            definition,
89            ordinal,
90        } = self
91        {
92            let crate::TypeBody::Enum(variants) = &definition.body else {
93                return None;
94            };
95            let next = ordinal.checked_add(1)?;
96
97            return (usize::from(next) < variants.len()).then_some(Self::UnitEnum {
98                definition,
99                ordinal: next,
100            });
101        }
102
103        self.integer_successor()
104    }
105
106    pub(crate) fn admit(self, field: FieldType, optional: bool) -> Result<(), Error> {
107        if self == Self::Absent {
108            return if optional {
109                Ok(())
110            } else {
111                Err(Error::InvalidOperand)
112            };
113        }
114
115        match (self, operand_type(field)) {
116            (
117                Self::UnitEnum {
118                    definition,
119                    ordinal,
120                },
121                FieldType::Named(link),
122            ) => {
123                let expected = (link.definition)();
124
125                // Exact equality transfers the operand's whole-definition check to the field.
126                if unit_enum_len(definition).is_some_and(|len| usize::from(ordinal) < len)
127                    && link.name == definition.name
128                    && definition == expected
129                {
130                    Ok(())
131                } else {
132                    Err(Error::InvalidOperand)
133                }
134            }
135            (Self::Nat8(_), FieldType::Nat8)
136            | (Self::Nat16(_), FieldType::Nat16)
137            | (Self::Nat32(_), FieldType::Nat32)
138            | (Self::Nat64(_), FieldType::Nat64)
139            | (Self::Nat128(_), FieldType::Nat128)
140            | (Self::Float32(_), FieldType::Float32)
141            | (Self::Float64(_), FieldType::Float64)
142            | (Self::Subaccount(_), FieldType::Subaccount)
143            | (Self::U256(_), FieldType::U256)
144            | (Self::Ulid(_), FieldType::Ulid)
145            | (Self::Date(_), FieldType::Date)
146            | (Self::Duration(_), FieldType::Duration)
147            | (Self::Timestamp(_), FieldType::Timestamp)
148            | (Self::Int8(_), FieldType::Int8)
149            | (Self::Int16(_), FieldType::Int16)
150            | (Self::Int32(_), FieldType::Int32)
151            | (Self::Int64(_), FieldType::Int64)
152            | (Self::Int128(_), FieldType::Int128)
153            | (Self::Bool(_), FieldType::Bool) => Ok(()),
154            (Self::Decimal(value), FieldType::Decimal { scale }) => value
155                .coefficient_at_scale(scale)
156                .map(|_| ())
157                .ok_or(Error::InvalidOperand),
158            (Self::Account(value), FieldType::Account) => {
159                Self::Principal(value.owner).admit(FieldType::Principal, false)
160            }
161            (Self::Principal(value), FieldType::Principal) => {
162                if value.as_slice().len() <= crate::codec::MAX_PRINCIPAL_BYTES {
163                    Ok(())
164                } else {
165                    Err(Error::Limit)
166                }
167            }
168            (Self::Text(value), FieldType::Text { max_bytes }) => {
169                if value.len() <= max_bytes as usize {
170                    Ok(())
171                } else {
172                    Err(Error::Limit)
173                }
174            }
175            (Self::Blob(value), FieldType::Blob { max_bytes }) => {
176                if value.len() <= max_bytes as usize {
177                    Ok(())
178                } else {
179                    Err(Error::Limit)
180                }
181            }
182            _ => Err(Error::InvalidOperand),
183        }
184    }
185
186    // Append a scalar payload after optional membership has been decided.
187    fn append_to(self, out: &mut Vec<u8>) {
188        match self {
189            Self::Absent => {}
190            Self::UnitEnum { ordinal, .. } => out.push(ordinal),
191            Self::Nat8(value) => out.extend(value.to_be_bytes()),
192            Self::Nat16(value) => out.extend(value.to_be_bytes()),
193            Self::Nat32(value) => out.extend(value.to_be_bytes()),
194            Self::Nat64(value) => out.extend(value.to_be_bytes()),
195            Self::Nat128(value) => out.extend(value.to_be_bytes()),
196            Self::Float32(value) => out.extend(value.ordered_bytes()),
197            Self::Float64(value) => out.extend(value.ordered_bytes()),
198            Self::Subaccount(value) => out.extend(value),
199            Self::Account(value) => {
200                Self::Principal(value.owner).append_to(out);
201                out.extend(value.effective_subaccount());
202            }
203            Self::U256(value) => out.extend(value.to_be_bytes()),
204            Self::Ulid(value) => out.extend(value.to_bytes()),
205            Self::Timestamp(value) => Self::Int64(value.as_millis()).append_to(out),
206            Self::Decimal(value) => value.append_ordered(out),
207            Self::Duration(value) => Self::Nat64(value.as_millis()).append_to(out),
208            Self::Date(value) => Self::Int32(value.as_days_since_epoch()).append_to(out),
209            Self::Int8(value) => {
210                let mut bytes = value.to_be_bytes();
211                bytes[0] ^= 0x80;
212                out.extend(bytes);
213            }
214            Self::Int16(value) => {
215                let mut bytes = value.to_be_bytes();
216                bytes[0] ^= 0x80;
217                out.extend(bytes);
218            }
219            Self::Int32(value) => {
220                let mut bytes = value.to_be_bytes();
221                bytes[0] ^= 0x80;
222                out.extend(bytes);
223            }
224            Self::Int64(value) => {
225                let mut bytes = value.to_be_bytes();
226                bytes[0] ^= 0x80;
227                out.extend(bytes);
228            }
229            Self::Int128(value) => {
230                let mut bytes = value.to_be_bytes();
231                bytes[0] ^= 0x80;
232                out.extend(bytes);
233            }
234            Self::Principal(value) => {
235                // Row/query admission enforces the durable 29-byte bound.
236                out.push(value.as_slice().len() as u8);
237                out.extend(value.as_slice());
238            }
239            Self::Bool(value) => out.push(u8::from(value)),
240            Self::Text(value) => append_bytes(value.as_bytes(), out),
241            Self::Blob(value) => append_bytes(value, out),
242        }
243    }
244
245    pub(crate) fn append_component(self, optional: bool, out: &mut Vec<u8>) {
246        if optional {
247            out.push(u8::from(self != Self::Absent));
248        }
249        self.append_to(out);
250    }
251
252    pub(crate) fn read(reader: &mut Decoder<'a>, field: FieldType) -> Result<Self, Error> {
253        Ok(match operand_type(field) {
254            FieldType::Named(link) => {
255                let definition = (link.definition)();
256                let len = unit_enum_len(definition).ok_or(Error::Corrupt)?;
257                let ordinal = reader.unit_enum(len)?;
258
259                Self::UnitEnum {
260                    definition,
261                    ordinal,
262                }
263            }
264            FieldType::Nat8 => Self::Nat8(reader.nat8()?),
265            FieldType::Nat16 => Self::Nat16(reader.nat16()?),
266            FieldType::Nat32 => Self::Nat32(reader.nat32()?),
267            FieldType::Nat64 => Self::Nat64(reader.nat64()?),
268            FieldType::Nat128 => Self::Nat128(reader.nat128()?),
269            FieldType::Float32 => Self::Float32(reader.float32()?),
270            FieldType::Float64 => Self::Float64(reader.float64()?),
271            FieldType::Subaccount => Self::Subaccount(reader.subaccount()?),
272            FieldType::Account => Self::Account(reader.account()?),
273            FieldType::U256 => Self::U256(reader.u256()?),
274            FieldType::Ulid => Self::Ulid(reader.ulid()?),
275            FieldType::Date => Self::Date(reader.date()?),
276            FieldType::Decimal { scale } => Self::Decimal(reader.decimal(scale)?),
277            FieldType::Duration => Self::Duration(reader.duration()?),
278            FieldType::Timestamp => Self::Timestamp(reader.timestamp()?),
279            FieldType::Int8 => Self::Int8(reader.int8()?),
280            FieldType::Int16 => Self::Int16(reader.int16()?),
281            FieldType::Int32 => Self::Int32(reader.int32()?),
282            FieldType::Int64 => Self::Int64(reader.int64()?),
283            FieldType::Int128 => Self::Int128(reader.int128()?),
284            FieldType::Principal => Self::Principal(reader.principal()?),
285            FieldType::Bool => Self::Bool(reader.boolean()?),
286            FieldType::Text { max_bytes } => Self::Text(reader.text_ref(max_bytes as usize)?),
287            FieldType::Blob { max_bytes } => Self::Blob(reader.blob_ref(max_bytes as usize)?),
288            _ => return Err(Error::Corrupt),
289        })
290    }
291}
292
293// Minimum completion of a query prefix, including unknown trailing components.
294// Variable-width identities reserve their shortest valid frame, not their maximum.
295pub(crate) fn minimum_bytes(field: FieldType) -> Result<usize, Error> {
296    Ok(match operand_type(field) {
297        FieldType::Named(link) if unit_enum_len((link.definition)()).is_some() => 1,
298        FieldType::Bool
299        | FieldType::Nat8
300        | FieldType::Int8
301        | FieldType::Principal
302        | FieldType::Decimal { .. } => 1,
303        FieldType::Nat16 | FieldType::Int16 | FieldType::Text { .. } | FieldType::Blob { .. } => 2,
304        FieldType::Nat32 | FieldType::Int32 | FieldType::Float32 | FieldType::Date => 4,
305        FieldType::Nat64
306        | FieldType::Int64
307        | FieldType::Float64
308        | FieldType::Timestamp
309        | FieldType::Duration => 8,
310        FieldType::Nat128 | FieldType::Int128 | FieldType::Ulid => 16,
311        FieldType::U256 | FieldType::Subaccount => 32,
312        FieldType::Account => 33,
313        _ => return Err(Error::InvalidOperand),
314    })
315}
316
317/// Shared generated/stored-row membership and component encoding.
318#[doc(hidden)]
319#[must_use]
320pub fn encode_index(values: &[(IndexValue<'_>, bool)], present_only: bool) -> Option<Vec<u8>> {
321    if present_only && values.iter().any(|(value, _)| *value == IndexValue::Absent) {
322        return None;
323    }
324    let mut bytes = Vec::new();
325    for &(value, optional) in values {
326        value.append_component(optional, &mut bytes);
327    }
328
329    Some(bytes)
330}
331
332// Method dispatch at the generated field access copies scalar operands and
333// auto-borrows String/Vec. A Subaccount by value keeps its own key encoding.
334#[doc(hidden)]
335pub trait MemberOperand<'a> {
336    fn __ic_db_member_operand(self) -> IndexValue<'a>;
337}
338
339impl<'a, T: Into<IndexValue<'a>>> MemberOperand<'a> for T {
340    fn __ic_db_member_operand(self) -> IndexValue<'a> {
341        self.into()
342    }
343}
344
345impl<'a, T: Into<IndexValue<'a>>> From<Option<T>> for IndexValue<'a> {
346    fn from(value: Option<T>) -> Self {
347        value.map_or(Self::Absent, Into::into)
348    }
349}
350
351// Integer operands preserve their exact width in both conversion and range proofs.
352macro_rules! integer_operands {
353    ($($variant:ident($integer:ty)),+ $(,)?) => {
354        $(
355            impl From<$integer> for IndexValue<'_> {
356                fn from(value: $integer) -> Self {
357                    Self::$variant(value)
358                }
359            }
360        )+
361
362        impl IndexValue<'_> {
363            fn integer_successor(self) -> Option<Self> {
364                match self {
365                    $(Self::$variant(n) => n.checked_add(<$integer>::from(true)).map(Self::$variant),)+
366                    _ => None,
367                }
368            }
369
370            pub(crate) fn is_integer_extreme(self, upper: bool) -> bool {
371                match self {
372                    $(Self::$variant(n) => n == if upper { <$integer>::MAX } else { <$integer>::MIN },)+
373                    _ => false,
374                }
375            }
376        }
377    };
378}
379
380integer_operands!(
381    Nat8(u8),
382    Nat16(u16),
383    Nat32(u32),
384    Nat64(u64),
385    Nat128(u128),
386    U256(U256),
387    Int8(i8),
388    Int16(i16),
389    Int32(i32),
390    Int64(i64),
391    Int128(i128),
392);
393
394impl From<Principal> for IndexValue<'_> {
395    fn from(value: Principal) -> Self {
396        Self::Principal(value)
397    }
398}
399
400impl From<Ulid> for IndexValue<'_> {
401    fn from(value: Ulid) -> Self {
402        Self::Ulid(value)
403    }
404}
405
406impl From<Timestamp> for IndexValue<'_> {
407    fn from(value: Timestamp) -> Self {
408        Self::Timestamp(value)
409    }
410}
411
412impl From<Decimal> for IndexValue<'_> {
413    fn from(value: Decimal) -> Self {
414        Self::Decimal(value)
415    }
416}
417
418impl From<Duration> for IndexValue<'_> {
419    fn from(value: Duration) -> Self {
420        Self::Duration(value)
421    }
422}
423
424impl From<Date> for IndexValue<'_> {
425    fn from(value: Date) -> Self {
426        Self::Date(value)
427    }
428}
429
430impl From<Float32> for IndexValue<'_> {
431    fn from(value: Float32) -> Self {
432        Self::Float32(value)
433    }
434}
435
436impl From<Float64> for IndexValue<'_> {
437    fn from(value: Float64) -> Self {
438        Self::Float64(value)
439    }
440}
441
442impl From<Subaccount> for IndexValue<'_> {
443    fn from(value: Subaccount) -> Self {
444        Self::Subaccount(value)
445    }
446}
447
448impl From<Account> for IndexValue<'_> {
449    fn from(value: Account) -> Self {
450        Self::Account(value)
451    }
452}
453
454// Schema admission and byte framing share the fixed-width contract here.
455pub(crate) fn fixed_width(field: FieldType) -> Option<usize> {
456    match field {
457        FieldType::Named(link) if unit_enum_len((link.definition)()).is_some() => Some(1),
458        FieldType::Nat8 | FieldType::Int8 | FieldType::Bool => Some(1),
459        FieldType::Nat16 | FieldType::Int16 => Some(2),
460        FieldType::Nat32 | FieldType::Int32 | FieldType::Float32 | FieldType::Date => Some(4),
461        FieldType::Nat64
462        | FieldType::Int64
463        | FieldType::Float64
464        | FieldType::Timestamp
465        | FieldType::Duration => Some(8),
466        FieldType::Nat128 | FieldType::Int128 | FieldType::Ulid => Some(16),
467        FieldType::U256 | FieldType::Subaccount => Some(32),
468        _ => None,
469    }
470}
471
472// Recognize proven extrema of present fixed-width keys when ranking index ranges.
473pub(crate) fn is_fixed_extreme(field: FieldType, bytes: &[u8], upper: bool) -> bool {
474    match operand_type(field) {
475        FieldType::Bool => bytes == [u8::from(upper)],
476        FieldType::Named(link) => unit_enum_len((link.definition)())
477            .is_some_and(|len| bytes == [if upper { (len - 1) as u8 } else { 0 }]),
478        scalar => {
479            fixed_width(scalar) == Some(bytes.len())
480                && bytes.iter().all(|&b| b == if upper { u8::MAX } else { 0 })
481        }
482    }
483}
484
485pub(crate) fn supports(field: FieldType) -> bool {
486    let field = operand_type(field);
487
488    fixed_width(field).is_some()
489        || matches!(
490            field,
491            FieldType::Principal
492                | FieldType::Account
493                | FieldType::Text { .. }
494                | FieldType::Blob { .. }
495                | FieldType::Decimal { .. }
496        )
497}
498
499// Stored entries and cursor positions share the same optional-component framing.
500pub(crate) fn consume_component(
501    bytes: &mut &[u8],
502    field: &crate::FieldSchema,
503    present_only: bool,
504    invalid_presence: Error,
505) -> Result<(), Error> {
506    if field.optional {
507        match *bytes {
508            [0, rest @ ..] if !present_only => {
509                *bytes = rest;
510
511                return Ok(());
512            }
513            [1, rest @ ..] => *bytes = rest,
514            _ => return Err(invalid_presence),
515        }
516    }
517
518    consume(bytes, field.value)
519}
520
521// Consume exactly one self-delimiting component at the key integrity boundary.
522pub(crate) fn consume(bytes: &mut &[u8], field: FieldType) -> Result<(), Error> {
523    let field = operand_type(field);
524    if let FieldType::Named(link) = field {
525        let len = unit_enum_len((link.definition)()).ok_or(Error::Corrupt)?;
526        let (&ordinal, rest) = bytes.split_first().ok_or(Error::Corrupt)?;
527        if usize::from(ordinal) >= len {
528            return Err(Error::Corrupt);
529        }
530        *bytes = rest;
531
532        return Ok(());
533    }
534    if let FieldType::Decimal { scale } = field {
535        let (value, width) = Decimal::read_ordered(bytes).ok_or(Error::Corrupt)?;
536        value.coefficient_at_scale(scale).ok_or(Error::Corrupt)?;
537        *bytes = &bytes[width..];
538
539        return Ok(());
540    }
541    if let FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } = field {
542        let mut decoded = 0;
543
544        loop {
545            let end = bytes
546                .iter()
547                .position(|&byte| byte == 0)
548                .ok_or(Error::Corrupt)?;
549            if matches!(field, FieldType::Text { .. }) {
550                std::str::from_utf8(&bytes[..end]).map_err(|_| Error::Corrupt)?;
551            }
552            decoded += end;
553            let escaped = *bytes.get(end + 1).ok_or(Error::Corrupt)?;
554            *bytes = &bytes[end + 2..];
555            match escaped {
556                0 if decoded <= max_bytes as usize => return Ok(()),
557                255 => decoded += 1,
558                _ => return Err(Error::Corrupt),
559            }
560            if decoded > max_bytes as usize {
561                return Err(Error::Corrupt);
562            }
563        }
564    }
565    if field == FieldType::Bool && !matches!(bytes.first(), Some(0 | 1)) {
566        return Err(Error::Corrupt);
567    }
568    let width = if matches!(field, FieldType::Principal | FieldType::Account) {
569        let (&len, _) = bytes.split_first().ok_or(Error::Corrupt)?;
570        if usize::from(len) > crate::codec::MAX_PRINCIPAL_BYTES {
571            return Err(Error::Corrupt);
572        }
573
574        usize::from(len) + 1 + if field == FieldType::Account { 32 } else { 0 }
575    } else {
576        fixed_width(field).ok_or(Error::Corrupt)?
577    };
578    let component = bytes.get(..width).ok_or(Error::Corrupt)?;
579    match field {
580        FieldType::Date => {
581            let mut encoded: [u8; 4] = component.try_into().map_err(|_| Error::Corrupt)?;
582            encoded[0] ^= 0x80;
583            Date::try_from_days_since_epoch(i32::from_be_bytes(encoded)).ok_or(Error::Corrupt)?;
584        }
585        FieldType::Float32 => {
586            Float32::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
587                .ok_or(Error::Corrupt)?;
588        }
589        FieldType::Float64 => {
590            Float64::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
591                .ok_or(Error::Corrupt)?;
592        }
593        _ => {}
594    }
595    *bytes = &bytes[width..];
596
597    Ok(())
598}
599
600impl From<bool> for IndexValue<'_> {
601    fn from(value: bool) -> Self {
602        Self::Bool(value)
603    }
604}
605impl<'a> From<&'a str> for IndexValue<'a> {
606    fn from(value: &'a str) -> Self {
607        Self::Text(value)
608    }
609}
610
611impl<'a> From<&'a String> for IndexValue<'a> {
612    fn from(value: &'a String) -> Self {
613        Self::Text(value)
614    }
615}
616
617impl<'a> From<&'a Vec<u8>> for IndexValue<'a> {
618    fn from(value: &'a Vec<u8>) -> Self {
619        Self::Blob(value)
620    }
621}
622
623impl<'a, const N: usize> From<&'a [u8; N]> for IndexValue<'a> {
624    fn from(value: &'a [u8; N]) -> Self {
625        Self::Blob(value)
626    }
627}
628
629impl<'a> From<&'a [u8]> for IndexValue<'a> {
630    fn from(value: &'a [u8]) -> Self {
631        Self::Blob(value)
632    }
633}
634
635// Empty Text and Blob components share the terminator. Optional present values
636// include the presence tag before the payload.
637pub(crate) fn empty_bytes_component(optional: bool) -> &'static [u8] {
638    const PRESENT_EMPTY: &[u8] = &[1, 0, 0];
639    if optional {
640        PRESENT_EMPTY
641    } else {
642        &PRESENT_EMPTY[1..]
643    }
644}
645
646// Keep any optional tag and escaped payload for a physical prefix seek.
647pub(crate) fn bytes_prefix(component: &[u8]) -> Option<&[u8]> {
648    component.strip_suffix(empty_bytes_component(false))
649}
650
651// IcyDB's terminated-byte rule, also used for raw bytes: preserve lexical order
652// and component boundaries, including empty values and embedded zeroes.
653fn append_bytes(value: &[u8], out: &mut Vec<u8>) {
654    for &byte in value {
655        out.push(byte);
656        if byte == 0 {
657            out.push(255);
658        }
659    }
660    out.extend_from_slice(empty_bytes_component(false));
661}