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    pub(crate) fn admit(self, field: FieldType, optional: bool) -> Result<(), Error> {
86        if self == Self::Absent {
87            return if optional {
88                Ok(())
89            } else {
90                Err(Error::InvalidOperand)
91            };
92        }
93
94        match (self, operand_type(field)) {
95            (
96                Self::UnitEnum {
97                    definition,
98                    ordinal,
99                },
100                FieldType::Named(link),
101            ) => {
102                let expected = (link.definition)();
103
104                if unit_enum_len(definition).is_some_and(|len| usize::from(ordinal) < len)
105                    && unit_enum_len(expected).is_some()
106                    && link.name == definition.name
107                    && definition == expected
108                {
109                    Ok(())
110                } else {
111                    Err(Error::InvalidOperand)
112                }
113            }
114            (Self::Nat8(_), FieldType::Nat8)
115            | (Self::Nat16(_), FieldType::Nat16)
116            | (Self::Nat32(_), FieldType::Nat32)
117            | (Self::Nat64(_), FieldType::Nat64)
118            | (Self::Nat128(_), FieldType::Nat128)
119            | (Self::Float32(_), FieldType::Float32)
120            | (Self::Float64(_), FieldType::Float64)
121            | (Self::Subaccount(_), FieldType::Subaccount)
122            | (Self::U256(_), FieldType::U256)
123            | (Self::Ulid(_), FieldType::Ulid)
124            | (Self::Date(_), FieldType::Date)
125            | (Self::Duration(_), FieldType::Duration)
126            | (Self::Timestamp(_), FieldType::Timestamp)
127            | (Self::Int8(_), FieldType::Int8)
128            | (Self::Int16(_), FieldType::Int16)
129            | (Self::Int32(_), FieldType::Int32)
130            | (Self::Int64(_), FieldType::Int64)
131            | (Self::Int128(_), FieldType::Int128)
132            | (Self::Bool(_), FieldType::Bool) => Ok(()),
133            (Self::Decimal(value), FieldType::Decimal { scale }) => value
134                .coefficient_at_scale(scale)
135                .map(|_| ())
136                .ok_or(Error::InvalidOperand),
137            (Self::Account(value), FieldType::Account) => {
138                Self::Principal(value.owner).admit(FieldType::Principal, false)
139            }
140            (Self::Principal(value), FieldType::Principal) => {
141                if value.as_slice().len() <= crate::codec::MAX_PRINCIPAL_BYTES {
142                    Ok(())
143                } else {
144                    Err(Error::Limit)
145                }
146            }
147            (Self::Text(value), FieldType::Text { max_bytes }) => {
148                if value.len() <= max_bytes as usize {
149                    Ok(())
150                } else {
151                    Err(Error::Limit)
152                }
153            }
154            (Self::Blob(value), FieldType::Blob { max_bytes }) => {
155                if value.len() <= max_bytes as usize {
156                    Ok(())
157                } else {
158                    Err(Error::Limit)
159                }
160            }
161            _ => Err(Error::InvalidOperand),
162        }
163    }
164
165    // Append a scalar payload after optional membership has been decided.
166    fn append_to(self, out: &mut Vec<u8>) {
167        match self {
168            Self::Absent => {}
169            Self::UnitEnum { ordinal, .. } => out.push(ordinal),
170            Self::Nat8(value) => out.extend(value.to_be_bytes()),
171            Self::Nat16(value) => out.extend(value.to_be_bytes()),
172            Self::Nat32(value) => out.extend(value.to_be_bytes()),
173            Self::Nat64(value) => out.extend(value.to_be_bytes()),
174            Self::Nat128(value) => out.extend(value.to_be_bytes()),
175            Self::Float32(value) => out.extend(value.ordered_bytes()),
176            Self::Float64(value) => out.extend(value.ordered_bytes()),
177            Self::Subaccount(value) => out.extend(value),
178            Self::Account(value) => {
179                Self::Principal(value.owner).append_to(out);
180                out.extend(value.effective_subaccount());
181            }
182            Self::U256(value) => out.extend(value.to_be_bytes()),
183            Self::Ulid(value) => out.extend(value.to_bytes()),
184            Self::Timestamp(value) => Self::Int64(value.as_millis()).append_to(out),
185            Self::Decimal(value) => value.append_ordered(out),
186            Self::Duration(value) => Self::Nat64(value.as_millis()).append_to(out),
187            Self::Date(value) => Self::Int32(value.as_days_since_epoch()).append_to(out),
188            Self::Int8(value) => {
189                let mut bytes = value.to_be_bytes();
190                bytes[0] ^= 0x80;
191                out.extend(bytes);
192            }
193            Self::Int16(value) => {
194                let mut bytes = value.to_be_bytes();
195                bytes[0] ^= 0x80;
196                out.extend(bytes);
197            }
198            Self::Int32(value) => {
199                let mut bytes = value.to_be_bytes();
200                bytes[0] ^= 0x80;
201                out.extend(bytes);
202            }
203            Self::Int64(value) => {
204                let mut bytes = value.to_be_bytes();
205                bytes[0] ^= 0x80;
206                out.extend(bytes);
207            }
208            Self::Int128(value) => {
209                let mut bytes = value.to_be_bytes();
210                bytes[0] ^= 0x80;
211                out.extend(bytes);
212            }
213            Self::Principal(value) => {
214                // Row/query admission enforces the durable 29-byte bound.
215                out.push(value.as_slice().len() as u8);
216                out.extend(value.as_slice());
217            }
218            Self::Bool(value) => out.push(u8::from(value)),
219            Self::Text(value) => append_bytes(value.as_bytes(), out),
220            Self::Blob(value) => append_bytes(value, out),
221        }
222    }
223
224    pub(crate) fn append_component(self, optional: bool, out: &mut Vec<u8>) {
225        if optional {
226            out.push(u8::from(self != Self::Absent));
227        }
228        self.append_to(out);
229    }
230
231    pub(crate) fn read(reader: &mut Decoder<'a>, field: FieldType) -> Result<Self, Error> {
232        Ok(match operand_type(field) {
233            FieldType::Named(link) => {
234                let definition = (link.definition)();
235                let len = unit_enum_len(definition).ok_or(Error::Corrupt)?;
236                let ordinal = reader.unit_enum(len)?;
237
238                Self::UnitEnum {
239                    definition,
240                    ordinal,
241                }
242            }
243            FieldType::Nat8 => Self::Nat8(reader.nat8()?),
244            FieldType::Nat16 => Self::Nat16(reader.nat16()?),
245            FieldType::Nat32 => Self::Nat32(reader.nat32()?),
246            FieldType::Nat64 => Self::Nat64(reader.nat64()?),
247            FieldType::Nat128 => Self::Nat128(reader.nat128()?),
248            FieldType::Float32 => Self::Float32(reader.float32()?),
249            FieldType::Float64 => Self::Float64(reader.float64()?),
250            FieldType::Subaccount => Self::Subaccount(reader.subaccount()?),
251            FieldType::Account => Self::Account(reader.account()?),
252            FieldType::U256 => Self::U256(reader.u256()?),
253            FieldType::Ulid => Self::Ulid(reader.ulid()?),
254            FieldType::Date => Self::Date(reader.date()?),
255            FieldType::Decimal { scale } => Self::Decimal(reader.decimal(scale)?),
256            FieldType::Duration => Self::Duration(reader.duration()?),
257            FieldType::Timestamp => Self::Timestamp(reader.timestamp()?),
258            FieldType::Int8 => Self::Int8(reader.int8()?),
259            FieldType::Int16 => Self::Int16(reader.int16()?),
260            FieldType::Int32 => Self::Int32(reader.int32()?),
261            FieldType::Int64 => Self::Int64(reader.int64()?),
262            FieldType::Int128 => Self::Int128(reader.int128()?),
263            FieldType::Principal => Self::Principal(reader.principal()?),
264            FieldType::Bool => Self::Bool(reader.boolean()?),
265            FieldType::Text { max_bytes } => Self::Text(reader.text_ref(max_bytes as usize)?),
266            FieldType::Blob { max_bytes } => Self::Blob(reader.blob_ref(max_bytes as usize)?),
267            _ => return Err(Error::Corrupt),
268        })
269    }
270}
271
272// Minimum completion of a query prefix, including unknown trailing components.
273// Variable-width identities reserve their shortest valid frame, not their maximum.
274pub(crate) fn minimum_bytes(field: FieldType) -> Result<usize, Error> {
275    Ok(match operand_type(field) {
276        FieldType::Named(link) if unit_enum_len((link.definition)()).is_some() => 1,
277        FieldType::Bool
278        | FieldType::Nat8
279        | FieldType::Int8
280        | FieldType::Principal
281        | FieldType::Decimal { .. } => 1,
282        FieldType::Nat16 | FieldType::Int16 | FieldType::Text { .. } | FieldType::Blob { .. } => 2,
283        FieldType::Nat32 | FieldType::Int32 | FieldType::Float32 | FieldType::Date => 4,
284        FieldType::Nat64
285        | FieldType::Int64
286        | FieldType::Float64
287        | FieldType::Timestamp
288        | FieldType::Duration => 8,
289        FieldType::Nat128 | FieldType::Int128 | FieldType::Ulid => 16,
290        FieldType::U256 | FieldType::Subaccount => 32,
291        FieldType::Account => 33,
292        _ => return Err(Error::InvalidOperand),
293    })
294}
295
296/// Shared generated/stored-row membership and component encoding.
297#[doc(hidden)]
298#[must_use]
299pub fn encode_index(values: &[(IndexValue<'_>, bool)], present_only: bool) -> Option<Vec<u8>> {
300    if present_only && values.iter().any(|(value, _)| *value == IndexValue::Absent) {
301        return None;
302    }
303    let mut bytes = Vec::new();
304    for &(value, optional) in values {
305        value.append_component(optional, &mut bytes);
306    }
307
308    Some(bytes)
309}
310
311impl<'a, T: Into<IndexValue<'a>>> From<Option<T>> for IndexValue<'a> {
312    fn from(value: Option<T>) -> Self {
313        value.map_or(Self::Absent, Into::into)
314    }
315}
316
317impl From<u8> for IndexValue<'_> {
318    fn from(value: u8) -> Self {
319        Self::Nat8(value)
320    }
321}
322impl From<u16> for IndexValue<'_> {
323    fn from(value: u16) -> Self {
324        Self::Nat16(value)
325    }
326}
327impl From<u32> for IndexValue<'_> {
328    fn from(value: u32) -> Self {
329        Self::Nat32(value)
330    }
331}
332impl From<u64> for IndexValue<'_> {
333    fn from(value: u64) -> Self {
334        Self::Nat64(value)
335    }
336}
337impl From<u128> for IndexValue<'_> {
338    fn from(value: u128) -> Self {
339        Self::Nat128(value)
340    }
341}
342impl From<i8> for IndexValue<'_> {
343    fn from(value: i8) -> Self {
344        Self::Int8(value)
345    }
346}
347impl From<i16> for IndexValue<'_> {
348    fn from(value: i16) -> Self {
349        Self::Int16(value)
350    }
351}
352impl From<i32> for IndexValue<'_> {
353    fn from(value: i32) -> Self {
354        Self::Int32(value)
355    }
356}
357impl From<i64> for IndexValue<'_> {
358    fn from(value: i64) -> Self {
359        Self::Int64(value)
360    }
361}
362impl From<i128> for IndexValue<'_> {
363    fn from(value: i128) -> Self {
364        Self::Int128(value)
365    }
366}
367impl From<Principal> for IndexValue<'_> {
368    fn from(value: Principal) -> Self {
369        Self::Principal(value)
370    }
371}
372
373impl From<U256> for IndexValue<'_> {
374    fn from(value: U256) -> Self {
375        Self::U256(value)
376    }
377}
378
379impl From<Ulid> for IndexValue<'_> {
380    fn from(value: Ulid) -> Self {
381        Self::Ulid(value)
382    }
383}
384
385impl From<Timestamp> for IndexValue<'_> {
386    fn from(value: Timestamp) -> Self {
387        Self::Timestamp(value)
388    }
389}
390
391impl From<Decimal> for IndexValue<'_> {
392    fn from(value: Decimal) -> Self {
393        Self::Decimal(value)
394    }
395}
396
397impl From<Duration> for IndexValue<'_> {
398    fn from(value: Duration) -> Self {
399        Self::Duration(value)
400    }
401}
402
403impl From<Date> for IndexValue<'_> {
404    fn from(value: Date) -> Self {
405        Self::Date(value)
406    }
407}
408
409impl From<Float32> for IndexValue<'_> {
410    fn from(value: Float32) -> Self {
411        Self::Float32(value)
412    }
413}
414
415impl From<Float64> for IndexValue<'_> {
416    fn from(value: Float64) -> Self {
417        Self::Float64(value)
418    }
419}
420
421impl From<Subaccount> for IndexValue<'_> {
422    fn from(value: Subaccount) -> Self {
423        Self::Subaccount(value)
424    }
425}
426
427impl From<Account> for IndexValue<'_> {
428    fn from(value: Account) -> Self {
429        Self::Account(value)
430    }
431}
432
433// Schema admission and byte framing share the fixed-width contract here.
434fn fixed_width(field: FieldType) -> Option<usize> {
435    match field {
436        FieldType::Named(link) if unit_enum_len((link.definition)()).is_some() => Some(1),
437        FieldType::Nat8 | FieldType::Int8 | FieldType::Bool => Some(1),
438        FieldType::Nat16 | FieldType::Int16 => Some(2),
439        FieldType::Nat32 | FieldType::Int32 | FieldType::Float32 | FieldType::Date => Some(4),
440        FieldType::Nat64
441        | FieldType::Int64
442        | FieldType::Float64
443        | FieldType::Timestamp
444        | FieldType::Duration => Some(8),
445        FieldType::Nat128 | FieldType::Int128 | FieldType::Ulid => Some(16),
446        FieldType::U256 | FieldType::Subaccount => Some(32),
447        _ => None,
448    }
449}
450
451pub(crate) fn supports(field: FieldType) -> bool {
452    let field = operand_type(field);
453
454    fixed_width(field).is_some()
455        || matches!(
456            field,
457            FieldType::Principal
458                | FieldType::Account
459                | FieldType::Text { .. }
460                | FieldType::Blob { .. }
461                | FieldType::Decimal { .. }
462        )
463}
464
465// Stored entries and cursor positions share the same optional-component framing.
466pub(crate) fn consume_component(
467    bytes: &mut &[u8],
468    field: &crate::FieldSchema,
469    present_only: bool,
470    invalid_presence: Error,
471) -> Result<(), Error> {
472    if field.optional {
473        match *bytes {
474            [0, rest @ ..] if !present_only => {
475                *bytes = rest;
476
477                return Ok(());
478            }
479            [1, rest @ ..] => *bytes = rest,
480            _ => return Err(invalid_presence),
481        }
482    }
483
484    consume(bytes, field.value)
485}
486
487// Consume exactly one self-delimiting component at the key integrity boundary.
488pub(crate) fn consume(bytes: &mut &[u8], field: FieldType) -> Result<(), Error> {
489    let field = operand_type(field);
490    if let FieldType::Named(link) = field {
491        let len = unit_enum_len((link.definition)()).ok_or(Error::Corrupt)?;
492        let (&ordinal, rest) = bytes.split_first().ok_or(Error::Corrupt)?;
493        if usize::from(ordinal) >= len {
494            return Err(Error::Corrupt);
495        }
496        *bytes = rest;
497
498        return Ok(());
499    }
500    if let FieldType::Decimal { scale } = field {
501        let (value, width) = Decimal::read_ordered(bytes).ok_or(Error::Corrupt)?;
502        value.coefficient_at_scale(scale).ok_or(Error::Corrupt)?;
503        *bytes = &bytes[width..];
504
505        return Ok(());
506    }
507    if let FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } = field {
508        let mut decoded = 0;
509
510        loop {
511            let end = bytes
512                .iter()
513                .position(|&byte| byte == 0)
514                .ok_or(Error::Corrupt)?;
515            if matches!(field, FieldType::Text { .. }) {
516                std::str::from_utf8(&bytes[..end]).map_err(|_| Error::Corrupt)?;
517            }
518            decoded += end;
519            let escaped = *bytes.get(end + 1).ok_or(Error::Corrupt)?;
520            *bytes = &bytes[end + 2..];
521            match escaped {
522                0 if decoded <= max_bytes as usize => return Ok(()),
523                255 => decoded += 1,
524                _ => return Err(Error::Corrupt),
525            }
526            if decoded > max_bytes as usize {
527                return Err(Error::Corrupt);
528            }
529        }
530    }
531    if field == FieldType::Bool && !matches!(bytes.first(), Some(0 | 1)) {
532        return Err(Error::Corrupt);
533    }
534    let width = if matches!(field, FieldType::Principal | FieldType::Account) {
535        let (&len, _) = bytes.split_first().ok_or(Error::Corrupt)?;
536        if usize::from(len) > crate::codec::MAX_PRINCIPAL_BYTES {
537            return Err(Error::Corrupt);
538        }
539
540        usize::from(len) + 1 + if field == FieldType::Account { 32 } else { 0 }
541    } else {
542        fixed_width(field).ok_or(Error::Corrupt)?
543    };
544    let component = bytes.get(..width).ok_or(Error::Corrupt)?;
545    match field {
546        FieldType::Date => {
547            let mut encoded: [u8; 4] = component.try_into().map_err(|_| Error::Corrupt)?;
548            encoded[0] ^= 0x80;
549            Date::try_from_days_since_epoch(i32::from_be_bytes(encoded)).ok_or(Error::Corrupt)?;
550        }
551        FieldType::Float32 => {
552            Float32::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
553                .ok_or(Error::Corrupt)?;
554        }
555        FieldType::Float64 => {
556            Float64::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
557                .ok_or(Error::Corrupt)?;
558        }
559        _ => {}
560    }
561    *bytes = &bytes[width..];
562
563    Ok(())
564}
565
566impl From<bool> for IndexValue<'_> {
567    fn from(value: bool) -> Self {
568        Self::Bool(value)
569    }
570}
571impl<'a> From<&'a str> for IndexValue<'a> {
572    fn from(value: &'a str) -> Self {
573        Self::Text(value)
574    }
575}
576
577impl<'a> From<&'a String> for IndexValue<'a> {
578    fn from(value: &'a String) -> Self {
579        Self::Text(value)
580    }
581}
582
583impl<'a> From<&'a Vec<u8>> for IndexValue<'a> {
584    fn from(value: &'a Vec<u8>) -> Self {
585        Self::Blob(value)
586    }
587}
588
589impl<'a, const N: usize> From<&'a [u8; N]> for IndexValue<'a> {
590    fn from(value: &'a [u8; N]) -> Self {
591        Self::Blob(value)
592    }
593}
594
595impl<'a> From<&'a [u8]> for IndexValue<'a> {
596    fn from(value: &'a [u8]) -> Self {
597        Self::Blob(value)
598    }
599}
600
601// IcyDB's terminated-byte rule, also used for raw bytes: preserve lexical order
602// and component boundaries, including empty values and embedded zeroes.
603fn append_bytes(value: &[u8], out: &mut Vec<u8>) {
604    for &byte in value {
605        out.push(byte);
606        if byte == 0 {
607            out.push(255);
608        }
609    }
610    out.extend([0, 0]);
611}