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 fn integer<const N: usize>(bytes: &[u8], sign_mask: u8) -> Result<[u8; N], Error> {
169 let mut value: [u8; N] = bytes.try_into().map_err(|_| Error::Corrupt)?;
170 value[0] ^= sign_mask;
171 Ok(value)
172 }
173 match field {
174 FieldType::Nat8 => Ok(Self::Nat8(u8::from_be_bytes(integer(bytes, 0)?))),
175 FieldType::Nat16 => Ok(Self::Nat16(u16::from_be_bytes(integer(bytes, 0)?))),
176 FieldType::Nat32 => Ok(Self::Nat32(u32::from_be_bytes(integer(bytes, 0)?))),
177 FieldType::Nat64 => Ok(Self::Nat64(u64::from_be_bytes(integer(bytes, 0)?))),
178 FieldType::Nat128 => Ok(Self::Nat128(u128::from_be_bytes(integer(bytes, 0)?))),
179 FieldType::Int8 => Ok(Self::Int8(i8::from_be_bytes(integer(bytes, 0x80)?))),
180 FieldType::Int16 => Ok(Self::Int16(i16::from_be_bytes(integer(bytes, 0x80)?))),
181 FieldType::Int32 => Ok(Self::Int32(i32::from_be_bytes(integer(bytes, 0x80)?))),
182 FieldType::Int64 => Ok(Self::Int64(i64::from_be_bytes(integer(bytes, 0x80)?))),
183 FieldType::Int128 => Ok(Self::Int128(i128::from_be_bytes(integer(bytes, 0x80)?))),
184 FieldType::U256 => Ok(Self::U256(U256::from_be_bytes(
185 bytes.try_into().map_err(|_| Error::Corrupt)?,
186 ))),
187 FieldType::Ulid => Ok(Self::Ulid(Ulid::from_bytes(
188 bytes.try_into().map_err(|_| Error::Corrupt)?,
189 ))),
190 FieldType::Subaccount => Ok(Self::Subaccount(
191 bytes.try_into().map_err(|_| Error::Corrupt)?,
192 )),
193 FieldType::Principal | FieldType::Account => {
194 let mut remaining = bytes;
195 key::consume(&mut remaining, field)?;
196 if !remaining.is_empty() {
197 return Err(Error::Corrupt);
198 }
199 let owner_end = 1 + usize::from(bytes[0]);
202 let owner =
203 Principal::try_from_slice(&bytes[1..owner_end]).map_err(|_| Error::Corrupt)?;
204
205 if field == FieldType::Principal {
206 Ok(Self::Principal(owner))
207 } else {
208 let subaccount: Subaccount =
209 bytes[owner_end..].try_into().map_err(|_| Error::Corrupt)?;
210
211 Ok(Self::Account(Account {
212 owner,
213 subaccount: (subaccount != [0; 32]).then_some(subaccount),
214 }))
215 }
216 }
217 _ => Err(Error::Corrupt),
218 }
219 }
220
221 pub(crate) fn append_to(self, bytes: &mut Vec<u8>) {
222 self.index_value().append_component(false, bytes);
223 }
224
225 pub(crate) fn encode(self) -> Vec<u8> {
226 let mut bytes = Vec::new();
227 self.append_to(&mut bytes);
228
229 bytes
230 }
231}