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