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