Skip to main content

ic_db/
primary.rs

1//! Small typed identity boundary over shared commit/traversal execution.
2//! Primary and secondary keys share their ordered component encoding.
3use crate::{Account, Error, FieldType, IndexValue, Principal, Subaccount, U256, Ulid, key};
4
5mod sealed {
6    pub trait Sealed {}
7}
8/// Supported supplied primary key: integers, U256, Ulid, Principal, Account or Subaccount.
9/// This sealed boundary keeps lookup/delete/page arguments typed to their entity.
10pub trait PrimaryKey: sealed::Sealed + Copy + Eq {
11    /// Convert at the generated entity boundary.
12    #[doc(hidden)]
13    fn into_row_key(self) -> RowKey;
14
15    /// Restore the exact key type after shared storage validation.
16    #[doc(hidden)]
17    fn from_row_key(key: RowKey) -> Result<Self, Error>;
18}
19macro_rules! primary_keys {
20    ($( $variant:ident($ty:ty) ),* $(,)?) => {
21        /// Internal identity used by shared mutation and reference preparation.
22        #[doc(hidden)]
23        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
24        pub enum RowKey { $( $variant($ty), )* }
25        $(
26            impl sealed::Sealed for $ty {}
27            impl PrimaryKey for $ty {
28                fn into_row_key(self) -> RowKey { RowKey::$variant(self) }
29
30                fn from_row_key(key: RowKey) -> Result<Self, Error> {
31                    match key { RowKey::$variant(value) => Ok(value), _ => Err(Error::Corrupt) }
32                }
33            }
34        )*
35        impl RowKey {
36            pub(crate) fn supports(field: FieldType) -> bool {
37                matches!(field, $( FieldType::$variant )|*)
38            }
39
40            pub(crate) fn from_index(value: IndexValue<'_>) -> Result<Self, Error> {
41                match value { $( IndexValue::$variant(value) => Ok(Self::$variant(value)), )* _ => Err(Error::Corrupt) }
42            }
43
44            pub(crate) fn index_value(self) -> IndexValue<'static> {
45                match self { $( Self::$variant(value) => value.into(), )* }
46            }
47        }
48    };
49}
50primary_keys!(
51    Nat8(u8),
52    Nat16(u16),
53    Nat32(u32),
54    Nat64(u64),
55    Nat128(u128),
56    Int8(i8),
57    Int16(i16),
58    Int32(i32),
59    Int64(i64),
60    Int128(i128),
61    U256(U256),
62    Ulid(Ulid),
63    Principal(Principal),
64    Subaccount(Subaccount),
65    Account(Account)
66);
67impl RowKey {
68    pub(crate) fn decode(bytes: &[u8], field: FieldType) -> Result<Self, Error> {
69        match field {
70            FieldType::Nat8 => Ok(Self::Nat8(u8::from_be_bytes(
71                bytes.try_into().map_err(|_| Error::Corrupt)?,
72            ))),
73            FieldType::Nat16 => Ok(Self::Nat16(u16::from_be_bytes(
74                bytes.try_into().map_err(|_| Error::Corrupt)?,
75            ))),
76            FieldType::Nat32 => Ok(Self::Nat32(u32::from_be_bytes(
77                bytes.try_into().map_err(|_| Error::Corrupt)?,
78            ))),
79            FieldType::Nat64 => Ok(Self::Nat64(u64::from_be_bytes(
80                bytes.try_into().map_err(|_| Error::Corrupt)?,
81            ))),
82            FieldType::Nat128 => Ok(Self::Nat128(u128::from_be_bytes(
83                bytes.try_into().map_err(|_| Error::Corrupt)?,
84            ))),
85            FieldType::Int8 => {
86                let mut bytes: [u8; 1] = bytes.try_into().map_err(|_| Error::Corrupt)?;
87                bytes[0] ^= 0x80;
88                Ok(Self::Int8(i8::from_be_bytes(bytes)))
89            }
90            FieldType::Int16 => {
91                let mut bytes: [u8; 2] = bytes.try_into().map_err(|_| Error::Corrupt)?;
92                bytes[0] ^= 0x80;
93                Ok(Self::Int16(i16::from_be_bytes(bytes)))
94            }
95            FieldType::Int32 => {
96                let mut bytes: [u8; 4] = bytes.try_into().map_err(|_| Error::Corrupt)?;
97                bytes[0] ^= 0x80;
98                Ok(Self::Int32(i32::from_be_bytes(bytes)))
99            }
100            FieldType::Int64 => {
101                let mut bytes: [u8; 8] = bytes.try_into().map_err(|_| Error::Corrupt)?;
102                bytes[0] ^= 0x80;
103                Ok(Self::Int64(i64::from_be_bytes(bytes)))
104            }
105            FieldType::Int128 => {
106                let mut bytes: [u8; 16] = bytes.try_into().map_err(|_| Error::Corrupt)?;
107                bytes[0] ^= 0x80;
108                Ok(Self::Int128(i128::from_be_bytes(bytes)))
109            }
110            FieldType::U256 => Ok(Self::U256(U256::from_be_bytes(
111                bytes.try_into().map_err(|_| Error::Corrupt)?,
112            ))),
113            FieldType::Ulid => Ok(Self::Ulid(Ulid::from_bytes(
114                bytes.try_into().map_err(|_| Error::Corrupt)?,
115            ))),
116            FieldType::Subaccount => Ok(Self::Subaccount(
117                bytes.try_into().map_err(|_| Error::Corrupt)?,
118            )),
119            FieldType::Principal | FieldType::Account => {
120                let mut remaining = bytes;
121                key::consume(&mut remaining, field)?;
122                if !remaining.is_empty() {
123                    return Err(Error::Corrupt);
124                }
125                // Component admission proves the owner length and, for an
126                // account, the complete effective-subaccount suffix.
127                let owner_end = 1 + usize::from(bytes[0]);
128                let owner =
129                    Principal::try_from_slice(&bytes[1..owner_end]).map_err(|_| Error::Corrupt)?;
130                if field == FieldType::Principal {
131                    Ok(Self::Principal(owner))
132                } else {
133                    let subaccount: Subaccount =
134                        bytes[owner_end..].try_into().map_err(|_| Error::Corrupt)?;
135                    Ok(Self::Account(Account {
136                        owner,
137                        subaccount: (subaccount != [0; 32]).then_some(subaccount),
138                    }))
139                }
140            }
141            _ => Err(Error::Corrupt),
142        }
143    }
144
145    pub(crate) fn append_to(self, bytes: &mut Vec<u8>) {
146        self.index_value().append_component(false, bytes);
147    }
148
149    pub(crate) fn encode(self) -> Vec<u8> {
150        let mut bytes = Vec::new();
151        self.append_to(&mut bytes);
152        bytes
153    }
154}