1use crate::{Account, Error, FieldType, IndexValue, Principal, Subaccount, U256, Ulid, key};
5
6#[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 pub const fn from_key(key: E::Key) -> Self {
29 Self(key)
30 }
31
32 pub const fn key(self) -> E::Key {
34 self.0
35 }
36}
37impl<'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::hash::Hash for Id<E>
69where
70 E::Key: std::hash::Hash,
71{
72 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
73 self.0.hash(state);
74 }
75}
76impl<E: crate::Entity> PartialOrd for Id<E>
77where
78 E::Key: PartialOrd,
79{
80 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
81 self.0.partial_cmp(&other.0)
82 }
83}
84impl<E: crate::Entity> Ord for Id<E>
85where
86 E::Key: Ord,
87{
88 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
89 self.0.cmp(&other.0)
90 }
91}
92impl<E: crate::Entity> std::fmt::Debug for Id<E>
93where
94 E::Key: std::fmt::Debug,
95{
96 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 self.0.fmt(formatter)
98 }
99}
100
101mod sealed {
102 pub trait Sealed {}
103}
104pub trait PrimaryKey: sealed::Sealed + Copy + Eq {
107 #[doc(hidden)]
109 fn into_row_key(self) -> RowKey;
110
111 #[doc(hidden)]
113 fn from_row_key(key: RowKey) -> Result<Self, Error>;
114}
115macro_rules! primary_keys {
116 ($( $variant:ident($ty:ty) ),* $(,)?) => {
117 #[doc(hidden)]
119 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
120 pub enum RowKey { $( $variant($ty), )* }
121 $(
122 impl<E: crate::Entity<Key = $ty>> From<$ty> for Id<E> {
123 fn from(key: $ty) -> Self { Self::from_key(key) }
124 }
125 impl sealed::Sealed for $ty {}
126 impl PrimaryKey for $ty {
127 fn into_row_key(self) -> RowKey { RowKey::$variant(self) }
128
129 fn from_row_key(key: RowKey) -> Result<Self, Error> {
130 match key { RowKey::$variant(value) => Ok(value), _ => Err(Error::Corrupt) }
131 }
132 }
133 )*
134 impl RowKey {
135 pub(crate) fn supports(field: FieldType) -> bool {
136 matches!(field, $( FieldType::$variant )|*)
137 }
138
139 pub(crate) fn from_index(value: IndexValue<'_>) -> Result<Self, Error> {
140 match value { $( IndexValue::$variant(value) => Ok(Self::$variant(value)), )* _ => Err(Error::Corrupt) }
141 }
142
143 pub(crate) fn index_value(self) -> IndexValue<'static> {
144 match self { $( Self::$variant(value) => value.into(), )* }
145 }
146 }
147 };
148}
149primary_keys!(
150 Nat8(u8),
151 Nat16(u16),
152 Nat32(u32),
153 Nat64(u64),
154 Nat128(u128),
155 Int8(i8),
156 Int16(i16),
157 Int32(i32),
158 Int64(i64),
159 Int128(i128),
160 U256(U256),
161 Ulid(Ulid),
162 Principal(Principal),
163 Subaccount(Subaccount),
164 Account(Account)
165);
166impl RowKey {
167 pub(crate) fn decode(bytes: &[u8], field: FieldType) -> Result<Self, Error> {
168 match field {
169 FieldType::Nat8 => Ok(Self::Nat8(u8::from_be_bytes(
170 bytes.try_into().map_err(|_| Error::Corrupt)?,
171 ))),
172 FieldType::Nat16 => Ok(Self::Nat16(u16::from_be_bytes(
173 bytes.try_into().map_err(|_| Error::Corrupt)?,
174 ))),
175 FieldType::Nat32 => Ok(Self::Nat32(u32::from_be_bytes(
176 bytes.try_into().map_err(|_| Error::Corrupt)?,
177 ))),
178 FieldType::Nat64 => Ok(Self::Nat64(u64::from_be_bytes(
179 bytes.try_into().map_err(|_| Error::Corrupt)?,
180 ))),
181 FieldType::Nat128 => Ok(Self::Nat128(u128::from_be_bytes(
182 bytes.try_into().map_err(|_| Error::Corrupt)?,
183 ))),
184 FieldType::Int8 => {
185 let mut bytes: [u8; 1] = bytes.try_into().map_err(|_| Error::Corrupt)?;
186 bytes[0] ^= 0x80;
187
188 Ok(Self::Int8(i8::from_be_bytes(bytes)))
189 }
190 FieldType::Int16 => {
191 let mut bytes: [u8; 2] = bytes.try_into().map_err(|_| Error::Corrupt)?;
192 bytes[0] ^= 0x80;
193
194 Ok(Self::Int16(i16::from_be_bytes(bytes)))
195 }
196 FieldType::Int32 => {
197 let mut bytes: [u8; 4] = bytes.try_into().map_err(|_| Error::Corrupt)?;
198 bytes[0] ^= 0x80;
199
200 Ok(Self::Int32(i32::from_be_bytes(bytes)))
201 }
202 FieldType::Int64 => {
203 let mut bytes: [u8; 8] = bytes.try_into().map_err(|_| Error::Corrupt)?;
204 bytes[0] ^= 0x80;
205
206 Ok(Self::Int64(i64::from_be_bytes(bytes)))
207 }
208 FieldType::Int128 => {
209 let mut bytes: [u8; 16] = bytes.try_into().map_err(|_| Error::Corrupt)?;
210 bytes[0] ^= 0x80;
211
212 Ok(Self::Int128(i128::from_be_bytes(bytes)))
213 }
214 FieldType::U256 => Ok(Self::U256(U256::from_be_bytes(
215 bytes.try_into().map_err(|_| Error::Corrupt)?,
216 ))),
217 FieldType::Ulid => Ok(Self::Ulid(Ulid::from_bytes(
218 bytes.try_into().map_err(|_| Error::Corrupt)?,
219 ))),
220 FieldType::Subaccount => Ok(Self::Subaccount(
221 bytes.try_into().map_err(|_| Error::Corrupt)?,
222 )),
223 FieldType::Principal | FieldType::Account => {
224 let mut remaining = bytes;
225 key::consume(&mut remaining, field)?;
226 if !remaining.is_empty() {
227 return Err(Error::Corrupt);
228 }
229 let owner_end = 1 + usize::from(bytes[0]);
232 let owner =
233 Principal::try_from_slice(&bytes[1..owner_end]).map_err(|_| Error::Corrupt)?;
234
235 if field == FieldType::Principal {
236 Ok(Self::Principal(owner))
237 } else {
238 let subaccount: Subaccount =
239 bytes[owner_end..].try_into().map_err(|_| Error::Corrupt)?;
240
241 Ok(Self::Account(Account {
242 owner,
243 subaccount: (subaccount != [0; 32]).then_some(subaccount),
244 }))
245 }
246 }
247 _ => Err(Error::Corrupt),
248 }
249 }
250
251 pub(crate) fn append_to(self, bytes: &mut Vec<u8>) {
252 self.index_value().append_component(false, bytes);
253 }
254
255 pub(crate) fn encode(self) -> Vec<u8> {
256 let mut bytes = Vec::new();
257 self.append_to(&mut bytes);
258
259 bytes
260 }
261}