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, named_schema::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        match (link.definition)().body {
78            crate::TypeBody::Wrapped(inner) => return inner,
79            crate::TypeBody::Checked(rule) => return rule.primitive(),
80            _ => {}
81        }
82    }
83    field
84}
85impl<'a> IndexValue<'a> {
86    // Planner operands have passed admission, including the complete enum definition.
87    pub(crate) fn discrete_successor(self) -> Option<Self> {
88        match self {
89            Self::Date(date) => date.checked_add_days(1).map(Self::Date),
90            Self::Timestamp(time) => Some(Self::Timestamp(Timestamp::from_millis(
91                time.as_millis().checked_add(1)?,
92            ))),
93            Self::Duration(duration) => Some(Self::Duration(Duration::from_millis(
94                duration.as_millis().checked_add(1)?,
95            ))),
96            Self::UnitEnum {
97                definition,
98                ordinal,
99            } => {
100                let crate::TypeBody::Enum(variants) = &definition.body else {
101                    return None;
102                };
103                let next = ordinal.checked_add(1)?;
104                (usize::from(next) < variants.len()).then_some(Self::UnitEnum {
105                    definition,
106                    ordinal: next,
107                })
108            }
109            _ => self.integer_successor(),
110        }
111    }
112
113    pub(crate) fn admit(self, field: FieldType, optional: bool) -> Result<(), Error> {
114        if self == Self::Absent {
115            return if optional {
116                Ok(())
117            } else {
118                Err(Error::InvalidOperand)
119            };
120        }
121
122        if let Some(rule) = field.newtype_rule() {
123            return match (rule, self) {
124                (crate::NewtypeRule::Text { .. }, Self::Text(value)) => rule.check_text(value),
125                (crate::NewtypeRule::NonAnonymous, Self::Principal(value)) => {
126                    crate::NonAnonymousPrincipal::try_from(value).map(|_| ())
127                }
128                _ => Err(Error::InvalidOperand),
129            };
130        }
131        match (self, operand_type(field)) {
132            (
133                Self::UnitEnum {
134                    definition,
135                    ordinal,
136                },
137                FieldType::Named(link),
138            ) => {
139                let expected = (link.definition)();
140
141                // Exact equality transfers the operand's whole-definition check to the field.
142                if unit_enum_len(definition).is_some_and(|len| usize::from(ordinal) < len)
143                    && link.name == definition.name
144                    && definition == expected
145                {
146                    Ok(())
147                } else {
148                    Err(Error::InvalidOperand)
149                }
150            }
151            (Self::Nat8(_), FieldType::Nat8)
152            | (Self::Nat16(_), FieldType::Nat16)
153            | (Self::Nat32(_), FieldType::Nat32)
154            | (Self::Nat64(_), FieldType::Nat64)
155            | (Self::Nat128(_), FieldType::Nat128)
156            | (Self::Float32(_), FieldType::Float32)
157            | (Self::Float64(_), FieldType::Float64)
158            | (Self::Subaccount(_), FieldType::Subaccount)
159            | (Self::U256(_), FieldType::U256)
160            | (Self::Ulid(_), FieldType::Ulid)
161            | (Self::Date(_), FieldType::Date)
162            | (Self::Duration(_), FieldType::Duration)
163            | (Self::Timestamp(_), FieldType::Timestamp)
164            | (Self::Int8(_), FieldType::Int8)
165            | (Self::Int16(_), FieldType::Int16)
166            | (Self::Int32(_), FieldType::Int32)
167            | (Self::Int64(_), FieldType::Int64)
168            | (Self::Int128(_), FieldType::Int128)
169            | (Self::Bool(_), FieldType::Bool) => Ok(()),
170            (Self::Decimal(value), FieldType::Decimal { scale }) => value
171                .coefficient_at_scale(scale)
172                .map(|_| ())
173                .ok_or(Error::InvalidOperand),
174            (Self::Account(value), FieldType::Account) => {
175                Self::Principal(value.owner).admit(FieldType::Principal, false)
176            }
177            (Self::Principal(value), FieldType::Principal) => {
178                if value.as_slice().len() <= crate::codec::MAX_PRINCIPAL_BYTES {
179                    Ok(())
180                } else {
181                    Err(Error::Limit)
182                }
183            }
184            (Self::Text(value), FieldType::Text { max_bytes }) => {
185                if value.len() <= max_bytes as usize {
186                    Ok(())
187                } else {
188                    Err(Error::Limit)
189                }
190            }
191            (Self::Blob(value), FieldType::Blob { max_bytes }) => {
192                if value.len() <= max_bytes as usize {
193                    Ok(())
194                } else {
195                    Err(Error::Limit)
196                }
197            }
198            _ => Err(Error::InvalidOperand),
199        }
200    }
201
202    // Append a scalar payload after optional membership has been decided.
203    fn append_to(self, out: &mut Vec<u8>) {
204        match self {
205            Self::Absent => {}
206            Self::UnitEnum { ordinal, .. } => out.push(ordinal),
207            Self::Nat8(value) => out.extend(value.to_be_bytes()),
208            Self::Nat16(value) => out.extend(value.to_be_bytes()),
209            Self::Nat32(value) => out.extend(value.to_be_bytes()),
210            Self::Nat64(value) => out.extend(value.to_be_bytes()),
211            Self::Nat128(value) => out.extend(value.to_be_bytes()),
212            Self::Float32(value) => out.extend(value.ordered_bytes()),
213            Self::Float64(value) => out.extend(value.ordered_bytes()),
214            Self::Subaccount(value) => out.extend(value),
215            Self::Account(value) => {
216                Self::Principal(value.owner).append_to(out);
217                out.extend(value.effective_subaccount());
218            }
219            Self::U256(value) => out.extend(value.to_be_bytes()),
220            Self::Ulid(value) => out.extend(value.to_bytes()),
221            Self::Timestamp(value) => Self::Int64(value.as_millis()).append_to(out),
222            Self::Decimal(value) => value.append_ordered(out),
223            Self::Duration(value) => Self::Nat64(value.as_millis()).append_to(out),
224            Self::Date(value) => Self::Int32(value.as_days_since_epoch()).append_to(out),
225            Self::Int8(value) => {
226                let mut bytes = value.to_be_bytes();
227                bytes[0] ^= 0x80;
228                out.extend(bytes);
229            }
230            Self::Int16(value) => {
231                let mut bytes = value.to_be_bytes();
232                bytes[0] ^= 0x80;
233                out.extend(bytes);
234            }
235            Self::Int32(value) => out.extend(ordered_i32(value)),
236            Self::Int64(value) => {
237                let mut bytes = value.to_be_bytes();
238                bytes[0] ^= 0x80;
239                out.extend(bytes);
240            }
241            Self::Int128(value) => {
242                let mut bytes = value.to_be_bytes();
243                bytes[0] ^= 0x80;
244                out.extend(bytes);
245            }
246            Self::Principal(value) => {
247                // Row/query admission enforces the durable 29-byte bound.
248                out.push(value.as_slice().len() as u8);
249                out.extend(value.as_slice());
250            }
251            Self::Bool(value) => out.push(u8::from(value)),
252            Self::Text(value) => append_bytes(value.as_bytes(), out),
253            Self::Blob(value) => append_bytes(value, out),
254        }
255    }
256
257    pub(crate) fn append_component(self, optional: bool, out: &mut Vec<u8>) {
258        if optional {
259            out.push(u8::from(self != Self::Absent));
260        }
261        self.append_to(out);
262    }
263
264    pub(crate) fn read(reader: &mut Decoder<'a>, field: FieldType) -> Result<Self, Error> {
265        if let Some(rule) = field.newtype_rule() {
266            return match rule {
267                crate::NewtypeRule::Text { .. } => Ok(Self::Text(reader.checked_text(rule)?)),
268                crate::NewtypeRule::NonAnonymous => {
269                    Ok(reader.named::<crate::NonAnonymousPrincipal>()?.into())
270                }
271            };
272        }
273        Ok(match operand_type(field) {
274            FieldType::Named(link) => {
275                let definition = (link.definition)();
276                let len = unit_enum_len(definition).ok_or(Error::Corrupt)?;
277                let ordinal = reader.unit_enum(len)?;
278
279                Self::UnitEnum {
280                    definition,
281                    ordinal,
282                }
283            }
284            FieldType::Nat8 => Self::Nat8(reader.nat8()?),
285            FieldType::Nat16 => Self::Nat16(reader.nat16()?),
286            FieldType::Nat32 => Self::Nat32(reader.nat32()?),
287            FieldType::Nat64 => Self::Nat64(reader.nat64()?),
288            FieldType::Nat128 => Self::Nat128(reader.nat128()?),
289            FieldType::Float32 => Self::Float32(reader.float32()?),
290            FieldType::Float64 => Self::Float64(reader.float64()?),
291            FieldType::Subaccount => Self::Subaccount(reader.subaccount()?),
292            FieldType::Account => Self::Account(reader.account()?),
293            FieldType::U256 => Self::U256(reader.u256()?),
294            FieldType::Ulid => Self::Ulid(reader.ulid()?),
295            FieldType::Date => Self::Date(reader.date()?),
296            FieldType::Decimal { scale } => Self::Decimal(reader.decimal(scale)?),
297            FieldType::Duration => Self::Duration(reader.duration()?),
298            FieldType::Timestamp => Self::Timestamp(reader.timestamp()?),
299            FieldType::Int8 => Self::Int8(reader.int8()?),
300            FieldType::Int16 => Self::Int16(reader.int16()?),
301            FieldType::Int32 => Self::Int32(reader.int32()?),
302            FieldType::Int64 => Self::Int64(reader.int64()?),
303            FieldType::Int128 => Self::Int128(reader.int128()?),
304            FieldType::Principal => Self::Principal(reader.principal()?),
305            FieldType::Bool => Self::Bool(reader.boolean()?),
306            FieldType::Text { max_bytes } => Self::Text(reader.text_ref(max_bytes as usize)?),
307            FieldType::Blob { max_bytes } => Self::Blob(reader.blob_ref(max_bytes as usize)?),
308            _ => return Err(Error::Corrupt),
309        })
310    }
311}
312
313// Minimum completion of a query prefix, including unknown trailing components.
314// Variable-width identities reserve their shortest valid frame, not their maximum.
315pub(crate) fn minimum_bytes(field: FieldType) -> Result<usize, Error> {
316    Ok(match operand_type(field) {
317        FieldType::Named(link) if unit_enum_len((link.definition)()).is_some() => 1,
318        FieldType::Bool
319        | FieldType::Nat8
320        | FieldType::Int8
321        | FieldType::Principal
322        | FieldType::Decimal { .. } => 1,
323        FieldType::Nat16 | FieldType::Int16 | FieldType::Text { .. } | FieldType::Blob { .. } => 2,
324        FieldType::Nat32 | FieldType::Int32 | FieldType::Float32 | FieldType::Date => 4,
325        FieldType::Nat64
326        | FieldType::Int64
327        | FieldType::Float64
328        | FieldType::Timestamp
329        | FieldType::Duration => 8,
330        FieldType::Nat128 | FieldType::Int128 | FieldType::Ulid => 16,
331        FieldType::U256 | FieldType::Subaccount => 32,
332        FieldType::Account => 33,
333        _ => return Err(Error::InvalidOperand),
334    })
335}
336
337/// Shared generated/stored-row membership and component encoding.
338#[doc(hidden)]
339#[must_use]
340pub fn encode_index(values: &[(IndexValue<'_>, bool)], present_only: bool) -> Option<Vec<u8>> {
341    let mut bytes = None;
342    encode_index_into(values, present_only, &mut bytes);
343
344    bytes
345}
346
347pub(crate) fn encode_index_into(
348    values: &[(IndexValue<'_>, bool)],
349    present_only: bool,
350    slot: &mut Option<Vec<u8>>,
351) {
352    if present_only && values.iter().any(|(value, _)| *value == IndexValue::Absent) {
353        *slot = None;
354        return;
355    }
356    let bytes = slot.get_or_insert_with(Vec::new);
357    bytes.clear();
358    for &(value, optional) in values {
359        value.append_component(optional, bytes);
360    }
361}
362
363// The entity macro can name a record field across crates, but its declaration
364// belongs to the record. Borrow an optional field directly, or autoref once
365// for a required field. Both paths retain the scalar's own operand type.
366#[doc(hidden)]
367pub trait MemberPresence<'a> {
368    type Scalar: 'a;
369    fn __ic_db_member_presence(self) -> (Option<&'a Self::Scalar>, bool);
370}
371
372impl<'a, T> MemberPresence<'a> for &'a Option<T> {
373    type Scalar = T;
374    fn __ic_db_member_presence(self) -> (Option<&'a T>, bool) {
375        (self.as_ref(), true)
376    }
377}
378
379impl<'a, T> MemberPresence<'a> for &&'a T {
380    type Scalar = T;
381    fn __ic_db_member_presence(self) -> (Option<&'a T>, bool) {
382        (Some(*self), false)
383    }
384}
385
386// Method dispatch at the generated field access copies scalar operands and
387// auto-borrows String/Vec. A Subaccount by value keeps its own key encoding.
388#[doc(hidden)]
389pub trait MemberOperand<'a> {
390    fn __ic_db_member_operand(self) -> IndexValue<'a>;
391}
392
393impl<'a, T: Into<IndexValue<'a>>> MemberOperand<'a> for T {
394    fn __ic_db_member_operand(self) -> IndexValue<'a> {
395        self.into()
396    }
397}
398
399impl<'a, T: Into<IndexValue<'a>>> From<Option<T>> for IndexValue<'a> {
400    fn from(value: Option<T>) -> Self {
401        value.map_or(Self::Absent, Into::into)
402    }
403}
404
405// Integer operands preserve their exact width in both conversion and range proofs.
406macro_rules! integer_operands {
407    ($($variant:ident($integer:ty)),+ $(,)?) => {
408        $(
409            impl From<$integer> for IndexValue<'_> {
410                fn from(value: $integer) -> Self {
411                    Self::$variant(value)
412                }
413            }
414        )+
415
416        impl IndexValue<'_> {
417            fn integer_successor(self) -> Option<Self> {
418                match self {
419                    $(Self::$variant(n) => n.checked_add(<$integer>::from(true)).map(Self::$variant),)+
420                    _ => None,
421                }
422            }
423
424            pub(crate) fn is_integer_extreme(self, upper: bool) -> bool {
425                match self {
426                    $(Self::$variant(n) => n == if upper { <$integer>::MAX } else { <$integer>::MIN },)+
427                    _ => false,
428                }
429            }
430        }
431    };
432}
433
434integer_operands!(
435    Nat8(u8),
436    Nat16(u16),
437    Nat32(u32),
438    Nat64(u64),
439    Nat128(u128),
440    U256(U256),
441    Int8(i8),
442    Int16(i16),
443    Int32(i32),
444    Int64(i64),
445    Int128(i128),
446);
447
448impl From<Principal> for IndexValue<'_> {
449    fn from(value: Principal) -> Self {
450        Self::Principal(value)
451    }
452}
453
454impl From<Ulid> for IndexValue<'_> {
455    fn from(value: Ulid) -> Self {
456        Self::Ulid(value)
457    }
458}
459
460impl From<Timestamp> for IndexValue<'_> {
461    fn from(value: Timestamp) -> Self {
462        Self::Timestamp(value)
463    }
464}
465
466impl From<Decimal> for IndexValue<'_> {
467    fn from(value: Decimal) -> Self {
468        Self::Decimal(value)
469    }
470}
471
472impl From<Duration> for IndexValue<'_> {
473    fn from(value: Duration) -> Self {
474        Self::Duration(value)
475    }
476}
477
478impl From<Date> for IndexValue<'_> {
479    fn from(value: Date) -> Self {
480        Self::Date(value)
481    }
482}
483
484impl From<Float32> for IndexValue<'_> {
485    fn from(value: Float32) -> Self {
486        Self::Float32(value)
487    }
488}
489
490impl From<Float64> for IndexValue<'_> {
491    fn from(value: Float64) -> Self {
492        Self::Float64(value)
493    }
494}
495
496impl From<Subaccount> for IndexValue<'_> {
497    fn from(value: Subaccount) -> Self {
498        Self::Subaccount(value)
499    }
500}
501
502impl From<Account> for IndexValue<'_> {
503    fn from(value: Account) -> Self {
504        Self::Account(value)
505    }
506}
507
508// Schema admission and byte framing share the fixed-width contract here.
509pub(crate) fn fixed_width(field: FieldType) -> Option<usize> {
510    match field {
511        FieldType::Named(link) if unit_enum_len((link.definition)()).is_some() => Some(1),
512        FieldType::Nat8 | FieldType::Int8 | FieldType::Bool => Some(1),
513        FieldType::Nat16 | FieldType::Int16 => Some(2),
514        FieldType::Nat32 | FieldType::Int32 | FieldType::Float32 | FieldType::Date => Some(4),
515        FieldType::Nat64
516        | FieldType::Int64
517        | FieldType::Float64
518        | FieldType::Timestamp
519        | FieldType::Duration => Some(8),
520        FieldType::Nat128 | FieldType::Int128 | FieldType::Ulid => Some(16),
521        FieldType::U256 | FieldType::Subaccount => Some(32),
522        _ => None,
523    }
524}
525
526fn ordered_i32(value: i32) -> [u8; 4] {
527    (value ^ i32::MIN).to_be_bytes()
528}
529
530// Recognize proven extrema of present fixed-width keys when ranking index ranges.
531pub(crate) fn is_fixed_extreme(field: FieldType, bytes: &[u8], upper: bool) -> bool {
532    match operand_type(field) {
533        FieldType::Bool => bytes == [u8::from(upper)],
534        FieldType::Date => {
535            let date = if upper { Date::MAX } else { Date::MIN };
536            bytes == ordered_i32(date.as_days_since_epoch())
537        }
538        FieldType::Named(link) => unit_enum_len((link.definition)())
539            .is_some_and(|len| bytes == [if upper { (len - 1) as u8 } else { 0 }]),
540        scalar => {
541            fixed_width(scalar) == Some(bytes.len())
542                && bytes.iter().all(|&b| b == if upper { u8::MAX } else { 0 })
543        }
544    }
545}
546
547pub(crate) fn supports(field: FieldType) -> bool {
548    let field = operand_type(field);
549
550    fixed_width(field).is_some()
551        || matches!(
552            field,
553            FieldType::Principal
554                | FieldType::Account
555                | FieldType::Text { .. }
556                | FieldType::Blob { .. }
557                | FieldType::Decimal { .. }
558        )
559}
560
561// Stored entries and cursor positions share the same optional-component framing.
562pub(crate) fn consume_component(
563    bytes: &mut &[u8],
564    field: crate::ValueSchema,
565    present_only: bool,
566    invalid_presence: Error,
567) -> Result<(), Error> {
568    if field.optional {
569        match *bytes {
570            [0, rest @ ..] if !present_only => {
571                *bytes = rest;
572
573                return Ok(());
574            }
575            [1, rest @ ..] => *bytes = rest,
576            _ => return Err(invalid_presence),
577        }
578    }
579
580    consume(bytes, field.value)
581}
582
583// Consume exactly one self-delimiting component at the key integrity boundary.
584pub(crate) fn consume(bytes: &mut &[u8], field: FieldType) -> Result<(), Error> {
585    let rule = field.newtype_rule();
586    let field = operand_type(field);
587    if let FieldType::Named(link) = field {
588        let len = unit_enum_len((link.definition)()).ok_or(Error::Corrupt)?;
589        let (&ordinal, rest) = bytes.split_first().ok_or(Error::Corrupt)?;
590        if usize::from(ordinal) >= len {
591            return Err(Error::Corrupt);
592        }
593        *bytes = rest;
594
595        return Ok(());
596    }
597    if let FieldType::Decimal { scale } = field {
598        let (value, width) = Decimal::read_ordered(bytes).ok_or(Error::Corrupt)?;
599        value.coefficient_at_scale(scale).ok_or(Error::Corrupt)?;
600        *bytes = &bytes[width..];
601
602        return Ok(());
603    }
604    if let FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } = field {
605        let mut decoded = 0;
606        let mut checked = rule.and_then(crate::NewtypeRule::text_check);
607
608        loop {
609            let end = bytes
610                .iter()
611                .position(|&byte| byte == 0)
612                .ok_or(Error::Corrupt)?;
613            if matches!(field, FieldType::Text { .. }) {
614                let segment = std::str::from_utf8(&bytes[..end]).map_err(|_| Error::Corrupt)?;
615                if let Some(check) = &mut checked {
616                    check.segment(segment).map_err(|_| Error::Corrupt)?;
617                }
618            }
619            decoded += end;
620            let escaped = *bytes.get(end + 1).ok_or(Error::Corrupt)?;
621            *bytes = &bytes[end + 2..];
622            match escaped {
623                0 if decoded <= max_bytes as usize => {
624                    if let Some(check) = checked {
625                        check.finish().map_err(|_| Error::Corrupt)?;
626                    }
627                    return Ok(());
628                }
629                255 => {
630                    decoded += 1;
631                    if let Some(check) = &mut checked {
632                        check.segment("\0").map_err(|_| Error::Corrupt)?;
633                    }
634                }
635                _ => return Err(Error::Corrupt),
636            }
637            if decoded > max_bytes as usize {
638                return Err(Error::Corrupt);
639            }
640        }
641    }
642    if field == FieldType::Bool && !matches!(bytes.first(), Some(0 | 1)) {
643        return Err(Error::Corrupt);
644    }
645    let width = if matches!(field, FieldType::Principal | FieldType::Account) {
646        let (&len, _) = bytes.split_first().ok_or(Error::Corrupt)?;
647        if usize::from(len) > crate::codec::MAX_PRINCIPAL_BYTES {
648            return Err(Error::Corrupt);
649        }
650
651        usize::from(len) + 1 + if field == FieldType::Account { 32 } else { 0 }
652    } else {
653        fixed_width(field).ok_or(Error::Corrupt)?
654    };
655    let component = bytes.get(..width).ok_or(Error::Corrupt)?;
656    if let Some(crate::NewtypeRule::NonAnonymous) = rule {
657        let principal = Principal::try_from_slice(&component[1..]).map_err(|_| Error::Corrupt)?;
658        crate::NonAnonymousPrincipal::try_from(principal).map_err(|_| Error::Corrupt)?;
659    }
660    match field {
661        FieldType::Date => {
662            let mut encoded: [u8; 4] = component.try_into().map_err(|_| Error::Corrupt)?;
663            encoded[0] ^= 0x80;
664            Date::try_from_days_since_epoch(i32::from_be_bytes(encoded)).ok_or(Error::Corrupt)?;
665        }
666        FieldType::Float32 => {
667            Float32::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
668                .ok_or(Error::Corrupt)?;
669        }
670        FieldType::Float64 => {
671            Float64::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
672                .ok_or(Error::Corrupt)?;
673        }
674        _ => {}
675    }
676    *bytes = &bytes[width..];
677
678    Ok(())
679}
680
681impl From<bool> for IndexValue<'_> {
682    fn from(value: bool) -> Self {
683        Self::Bool(value)
684    }
685}
686impl<'a> From<&'a str> for IndexValue<'a> {
687    fn from(value: &'a str) -> Self {
688        Self::Text(value)
689    }
690}
691
692impl<'a> From<&'a String> for IndexValue<'a> {
693    fn from(value: &'a String) -> Self {
694        Self::Text(value)
695    }
696}
697
698impl<'a> From<&'a Vec<u8>> for IndexValue<'a> {
699    fn from(value: &'a Vec<u8>) -> Self {
700        Self::Blob(value)
701    }
702}
703
704impl<'a, const N: usize> From<&'a [u8; N]> for IndexValue<'a> {
705    fn from(value: &'a [u8; N]) -> Self {
706        Self::Blob(value)
707    }
708}
709
710impl<'a> From<&'a [u8]> for IndexValue<'a> {
711    fn from(value: &'a [u8]) -> Self {
712        Self::Blob(value)
713    }
714}
715
716// Empty Text and Blob components share the terminator. Optional present values
717// include the presence tag before the payload.
718pub(crate) fn empty_bytes_component(optional: bool) -> &'static [u8] {
719    const PRESENT_EMPTY: &[u8] = &[1, 0, 0];
720    if optional {
721        PRESENT_EMPTY
722    } else {
723        &PRESENT_EMPTY[1..]
724    }
725}
726
727// Keep any optional tag and escaped payload for a physical prefix seek.
728pub(crate) fn bytes_prefix(component: &[u8]) -> Option<&[u8]> {
729    component.strip_suffix(empty_bytes_component(false))
730}
731
732// IcyDB's terminated-byte rule, also used for raw bytes: preserve lexical order
733// and component boundaries, including empty values and embedded zeroes.
734fn append_bytes(value: &[u8], out: &mut Vec<u8>) {
735    for &byte in value {
736        out.push(byte);
737        if byte == 0 {
738            out.push(255);
739        }
740    }
741    out.extend_from_slice(empty_bytes_component(false));
742}