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
6/// An application key branded with the entity that owns it. Constructing one
7/// does not read storage or prove that the row exists.
8/// An ID for one entity cannot address another entity with the same raw key.
9/// ```compile_fail
10/// use ic_db::{Database, Entity, Id};
11/// fn wrong<A: Entity, B: Entity<Key = A::Key>>(db: &Database, id: Id<A>) {
12///     let _ = db.get::<B>(id);
13/// }
14/// ```
15#[repr(transparent)]
16#[derive(serde::Serialize, serde::Deserialize)]
17#[serde(
18    transparent,
19    bound(
20        serialize = "E::Key: serde::Serialize",
21        deserialize = "E::Key: serde::Deserialize<'de>"
22    )
23)]
24pub struct Id<E: crate::Entity>(E::Key);
25
26impl<E: crate::Entity> Id<E> {
27    /// Associate a raw key with its entity at an application boundary.
28    pub const fn from_key(key: E::Key) -> Self {
29        Self(key)
30    }
31
32    /// Return the stored primary key.
33    pub const fn key(self) -> E::Key {
34        self.0
35    }
36}
37// Fluent predicates admit scalar operands against the selected field's type.
38impl<'a, E: crate::Entity> From<Id<E>> for IndexValue<'a>
39where
40    E::Key: Into<IndexValue<'a>>,
41{
42    fn from(id: Id<E>) -> Self {
43        id.key().into()
44    }
45}
46
47impl<'a, E: crate::Entity> From<&Id<E>> for IndexValue<'a>
48where
49    E::Key: Into<IndexValue<'a>>,
50{
51    fn from(id: &Id<E>) -> Self {
52        (*id).into()
53    }
54}
55
56impl<E: crate::Entity> Copy for Id<E> {}
57impl<E: crate::Entity> Clone for Id<E> {
58    fn clone(&self) -> Self {
59        *self
60    }
61}
62impl<E: crate::Entity> PartialEq for Id<E> {
63    fn eq(&self, other: &Self) -> bool {
64        self.0 == other.0
65    }
66}
67impl<E: crate::Entity> Eq for Id<E> {}
68impl<E: crate::Entity> std::fmt::Debug for Id<E>
69where
70    E::Key: std::fmt::Debug,
71{
72    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        self.0.fmt(formatter)
74    }
75}
76
77mod sealed {
78    pub trait Sealed {}
79}
80/// Supported supplied primary key: integers, U256, Ulid, Principal, Account or Subaccount.
81/// This sealed boundary keeps lookup/delete/page arguments typed to their entity.
82pub trait PrimaryKey: sealed::Sealed + Copy + Eq {
83    /// Convert at the generated entity boundary.
84    #[doc(hidden)]
85    fn into_row_key(self) -> RowKey;
86
87    /// Restore the exact key type after shared storage validation.
88    #[doc(hidden)]
89    fn from_row_key(key: RowKey) -> Result<Self, Error>;
90}
91macro_rules! primary_keys {
92    ($( $variant:ident($ty:ty) ),* $(,)?) => {
93        /// Internal identity used by shared mutation and reference preparation.
94        #[doc(hidden)]
95        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
96        pub enum RowKey { $( $variant($ty), )* }
97        $(
98            impl<E: crate::Entity<Key = $ty>> From<$ty> for Id<E> {
99                fn from(key: $ty) -> Self { Self::from_key(key) }
100            }
101            impl sealed::Sealed for $ty {}
102            impl PrimaryKey for $ty {
103                fn into_row_key(self) -> RowKey { RowKey::$variant(self) }
104
105                fn from_row_key(key: RowKey) -> Result<Self, Error> {
106                    match key { RowKey::$variant(value) => Ok(value), _ => Err(Error::Corrupt) }
107                }
108            }
109        )*
110        impl RowKey {
111            pub(crate) fn supports(field: FieldType) -> bool {
112                matches!(field, $( FieldType::$variant )|*)
113            }
114
115            pub(crate) fn from_index(value: IndexValue<'_>) -> Result<Self, Error> {
116                match value { $( IndexValue::$variant(value) => Ok(Self::$variant(value)), )* _ => Err(Error::Corrupt) }
117            }
118
119            pub(crate) fn index_value(self) -> IndexValue<'static> {
120                match self { $( Self::$variant(value) => value.into(), )* }
121            }
122        }
123    };
124}
125primary_keys!(
126    Nat8(u8),
127    Nat16(u16),
128    Nat32(u32),
129    Nat64(u64),
130    Nat128(u128),
131    Int8(i8),
132    Int16(i16),
133    Int32(i32),
134    Int64(i64),
135    Int128(i128),
136    U256(U256),
137    Ulid(Ulid),
138    Principal(Principal),
139    Subaccount(Subaccount),
140    Account(Account)
141);
142impl RowKey {
143    pub(crate) fn decode(bytes: &[u8], field: FieldType) -> Result<Self, Error> {
144        match field {
145            FieldType::Nat8 => Ok(Self::Nat8(u8::from_be_bytes(
146                bytes.try_into().map_err(|_| Error::Corrupt)?,
147            ))),
148            FieldType::Nat16 => Ok(Self::Nat16(u16::from_be_bytes(
149                bytes.try_into().map_err(|_| Error::Corrupt)?,
150            ))),
151            FieldType::Nat32 => Ok(Self::Nat32(u32::from_be_bytes(
152                bytes.try_into().map_err(|_| Error::Corrupt)?,
153            ))),
154            FieldType::Nat64 => Ok(Self::Nat64(u64::from_be_bytes(
155                bytes.try_into().map_err(|_| Error::Corrupt)?,
156            ))),
157            FieldType::Nat128 => Ok(Self::Nat128(u128::from_be_bytes(
158                bytes.try_into().map_err(|_| Error::Corrupt)?,
159            ))),
160            FieldType::Int8 => {
161                let mut bytes: [u8; 1] = bytes.try_into().map_err(|_| Error::Corrupt)?;
162                bytes[0] ^= 0x80;
163
164                Ok(Self::Int8(i8::from_be_bytes(bytes)))
165            }
166            FieldType::Int16 => {
167                let mut bytes: [u8; 2] = bytes.try_into().map_err(|_| Error::Corrupt)?;
168                bytes[0] ^= 0x80;
169
170                Ok(Self::Int16(i16::from_be_bytes(bytes)))
171            }
172            FieldType::Int32 => {
173                let mut bytes: [u8; 4] = bytes.try_into().map_err(|_| Error::Corrupt)?;
174                bytes[0] ^= 0x80;
175
176                Ok(Self::Int32(i32::from_be_bytes(bytes)))
177            }
178            FieldType::Int64 => {
179                let mut bytes: [u8; 8] = bytes.try_into().map_err(|_| Error::Corrupt)?;
180                bytes[0] ^= 0x80;
181
182                Ok(Self::Int64(i64::from_be_bytes(bytes)))
183            }
184            FieldType::Int128 => {
185                let mut bytes: [u8; 16] = bytes.try_into().map_err(|_| Error::Corrupt)?;
186                bytes[0] ^= 0x80;
187
188                Ok(Self::Int128(i128::from_be_bytes(bytes)))
189            }
190            FieldType::U256 => Ok(Self::U256(U256::from_be_bytes(
191                bytes.try_into().map_err(|_| Error::Corrupt)?,
192            ))),
193            FieldType::Ulid => Ok(Self::Ulid(Ulid::from_bytes(
194                bytes.try_into().map_err(|_| Error::Corrupt)?,
195            ))),
196            FieldType::Subaccount => Ok(Self::Subaccount(
197                bytes.try_into().map_err(|_| Error::Corrupt)?,
198            )),
199            FieldType::Principal | FieldType::Account => {
200                let mut remaining = bytes;
201                key::consume(&mut remaining, field)?;
202                if !remaining.is_empty() {
203                    return Err(Error::Corrupt);
204                }
205                // Component admission proves the owner length and, for an
206                // account, the complete effective-subaccount suffix.
207                let owner_end = 1 + usize::from(bytes[0]);
208                let owner =
209                    Principal::try_from_slice(&bytes[1..owner_end]).map_err(|_| Error::Corrupt)?;
210
211                if field == FieldType::Principal {
212                    Ok(Self::Principal(owner))
213                } else {
214                    let subaccount: Subaccount =
215                        bytes[owner_end..].try_into().map_err(|_| Error::Corrupt)?;
216
217                    Ok(Self::Account(Account {
218                        owner,
219                        subaccount: (subaccount != [0; 32]).then_some(subaccount),
220                    }))
221                }
222            }
223            _ => Err(Error::Corrupt),
224        }
225    }
226
227    pub(crate) fn append_to(self, bytes: &mut Vec<u8>) {
228        self.index_value().append_component(false, bytes);
229    }
230
231    pub(crate) fn encode(self) -> Vec<u8> {
232        let mut bytes = Vec::new();
233        self.append_to(&mut bytes);
234
235        bytes
236    }
237}