1mod convert;
2#[cfg(test)]
3mod tests;
4
5use crate::{
6 error::{ErrorClass, ErrorOrigin, InternalError},
7 types::{
8 Account, AccountEncodeError, Principal, PrincipalEncodeError, Subaccount, Timestamp, Ulid,
9 },
10};
11use candid::CandidType;
12use derive_more::Display;
13use serde::{Deserialize, Serialize};
14use std::cmp::Ordering;
15use thiserror::Error as ThisError;
16
17#[derive(CandidType, Clone, Copy, Debug, Deserialize, Display, Eq, Hash, PartialEq, Serialize)]
26pub enum Key {
27 Account(Account),
28 Int(i64),
29 Principal(Principal),
30 Subaccount(Subaccount),
31 Timestamp(Timestamp),
32 Uint(u64),
33 Ulid(Ulid),
34 Unit,
35}
36
37#[derive(Debug, ThisError)]
44pub enum KeyEncodeError {
45 #[error("account encoding failed: {0}")]
46 Account(#[from] AccountEncodeError),
47
48 #[error("account payload length mismatch: {len} bytes (expected {expected})")]
49 AccountLengthMismatch { len: usize, expected: usize },
50
51 #[error("principal encoding failed: {0}")]
52 Principal(#[from] PrincipalEncodeError),
53}
54
55impl From<KeyEncodeError> for InternalError {
56 fn from(err: KeyEncodeError) -> Self {
57 Self::new(
58 ErrorClass::Unsupported,
59 ErrorOrigin::Serialize,
60 err.to_string(),
61 )
62 }
63}
64
65impl Key {
66 pub(crate) const TAG_ACCOUNT: u8 = 0;
68 pub(crate) const TAG_INT: u8 = 1;
69 pub(crate) const TAG_PRINCIPAL: u8 = 2;
70 pub(crate) const TAG_SUBACCOUNT: u8 = 3;
71 pub(crate) const TAG_TIMESTAMP: u8 = 4;
72 pub(crate) const TAG_UINT: u8 = 5;
73 pub(crate) const TAG_ULID: u8 = 6;
74 pub(crate) const TAG_UNIT: u8 = 7;
75
76 pub const STORED_SIZE: usize = 64;
78
79 const TAG_SIZE: usize = 1;
81 pub(crate) const TAG_OFFSET: usize = 0;
82
83 pub(crate) const PAYLOAD_OFFSET: usize = Self::TAG_SIZE;
84 const PAYLOAD_SIZE: usize = Self::STORED_SIZE - Self::TAG_SIZE;
85
86 pub(crate) const INT_SIZE: usize = 8;
88 pub(crate) const UINT_SIZE: usize = 8;
89 pub(crate) const TIMESTAMP_SIZE: usize = 8;
90 pub(crate) const ULID_SIZE: usize = 16;
91 pub(crate) const SUBACCOUNT_SIZE: usize = 32;
92 const ACCOUNT_MAX_SIZE: usize = 62;
93
94 const fn tag(&self) -> u8 {
95 match self {
96 Self::Account(_) => Self::TAG_ACCOUNT,
97 Self::Int(_) => Self::TAG_INT,
98 Self::Principal(_) => Self::TAG_PRINCIPAL,
99 Self::Subaccount(_) => Self::TAG_SUBACCOUNT,
100 Self::Timestamp(_) => Self::TAG_TIMESTAMP,
101 Self::Uint(_) => Self::TAG_UINT,
102 Self::Ulid(_) => Self::TAG_ULID,
103 Self::Unit => Self::TAG_UNIT,
104 }
105 }
106
107 #[must_use]
108 pub fn max_storable() -> Self {
110 Self::Account(Account::max_storable())
111 }
112
113 pub const MIN: Self = Self::Account(Account {
115 owner: Principal::from_slice(&[]),
116 subaccount: None,
117 });
118
119 #[must_use]
120 pub const fn lower_bound() -> Self {
121 Self::MIN
122 }
123
124 #[must_use]
125 pub const fn upper_bound() -> Self {
126 Self::Unit
127 }
128
129 const fn variant_rank(&self) -> u8 {
130 self.tag()
131 }
132
133 pub fn to_bytes(&self) -> Result<[u8; Self::STORED_SIZE], KeyEncodeError> {
135 let mut buf = [0u8; Self::STORED_SIZE];
136
137 buf[Self::TAG_OFFSET] = self.tag();
139 let payload = &mut buf[Self::PAYLOAD_OFFSET..=Self::PAYLOAD_SIZE];
140
141 #[allow(clippy::cast_possible_truncation)]
143 match self {
144 Self::Account(v) => {
145 let bytes = v.to_bytes()?;
146 if bytes.len() != Self::ACCOUNT_MAX_SIZE {
147 return Err(KeyEncodeError::AccountLengthMismatch {
148 len: bytes.len(),
149 expected: Self::ACCOUNT_MAX_SIZE,
150 });
151 }
152 payload[..bytes.len()].copy_from_slice(&bytes);
153 }
154
155 Self::Int(v) => {
156 let biased = (*v).cast_unsigned() ^ (1u64 << 63);
158 payload[..Self::INT_SIZE].copy_from_slice(&biased.to_be_bytes());
159 }
160
161 Self::Uint(v) => {
162 payload[..Self::UINT_SIZE].copy_from_slice(&v.to_be_bytes());
163 }
164
165 Self::Timestamp(v) => {
166 payload[..Self::TIMESTAMP_SIZE].copy_from_slice(&v.get().to_be_bytes());
167 }
168
169 Self::Principal(v) => {
170 let bytes = v.to_bytes()?;
171 let len = bytes.len();
172 payload[0] = u8::try_from(len).map_err(|_| {
173 KeyEncodeError::Principal(PrincipalEncodeError::TooLarge {
174 len,
175 max: Principal::MAX_LENGTH_IN_BYTES as usize,
176 })
177 })?;
178 if len > 0 {
179 payload[1..=len].copy_from_slice(&bytes[..len]);
180 }
181 }
182
183 Self::Subaccount(v) => {
184 let bytes = v.to_array();
185 payload[..Self::SUBACCOUNT_SIZE].copy_from_slice(&bytes);
186 }
187
188 Self::Ulid(v) => {
189 payload[..Self::ULID_SIZE].copy_from_slice(&v.to_bytes());
190 }
191
192 Self::Unit => {}
193 }
194
195 Ok(buf)
196 }
197
198 pub fn try_from_bytes(bytes: &[u8]) -> Result<Self, &'static str> {
199 if bytes.len() != Self::STORED_SIZE {
200 return Err("corrupted Key: invalid size");
201 }
202
203 let tag = bytes[Self::TAG_OFFSET];
204 let payload = &bytes[Self::PAYLOAD_OFFSET..=Self::PAYLOAD_SIZE];
205
206 let ensure_zero_padding = |used: usize, context: &str| {
207 if payload[used..].iter().all(|&b| b == 0) {
208 Ok(())
209 } else {
210 Err(match context {
211 "account" => "corrupted Key: non-zero account padding",
212 "int" => "corrupted Key: non-zero int padding",
213 "principal" => "corrupted Key: non-zero principal padding",
214 "subaccount" => "corrupted Key: non-zero subaccount padding",
215 "timestamp" => "corrupted Key: non-zero timestamp padding",
216 "uint" => "corrupted Key: non-zero uint padding",
217 "ulid" => "corrupted Key: non-zero ulid padding",
218 "unit" => "corrupted Key: non-zero unit padding",
219 _ => "corrupted Key: non-zero padding",
220 })
221 }
222 };
223
224 match tag {
225 Self::TAG_ACCOUNT => {
226 let end = Account::STORED_SIZE as usize;
227 ensure_zero_padding(end, "account")?;
228 let account = Account::try_from_bytes(&payload[..end])?;
229 Ok(Self::Account(account))
230 }
231
232 Self::TAG_INT => {
233 let mut buf = [0u8; Self::INT_SIZE];
234 buf.copy_from_slice(&payload[..Self::INT_SIZE]);
235 let biased = u64::from_be_bytes(buf);
236 ensure_zero_padding(Self::INT_SIZE, "int")?;
237 Ok(Self::Int((biased ^ (1u64 << 63)).cast_signed()))
238 }
239
240 Self::TAG_PRINCIPAL => {
241 let len = payload[0] as usize;
242 if len > Principal::MAX_LENGTH_IN_BYTES as usize {
243 return Err("corrupted Key: invalid principal length");
244 }
245 let end = 1 + len;
246 ensure_zero_padding(end, "principal")?;
247 Ok(Self::Principal(Principal::from_slice(&payload[1..end])))
248 }
249
250 Self::TAG_SUBACCOUNT => {
251 let mut buf = [0u8; Self::SUBACCOUNT_SIZE];
252 buf.copy_from_slice(&payload[..Self::SUBACCOUNT_SIZE]);
253 ensure_zero_padding(Self::SUBACCOUNT_SIZE, "subaccount")?;
254 Ok(Self::Subaccount(Subaccount::from_array(buf)))
255 }
256
257 Self::TAG_TIMESTAMP => {
258 let mut buf = [0u8; Self::TIMESTAMP_SIZE];
259 buf.copy_from_slice(&payload[..Self::TIMESTAMP_SIZE]);
260 ensure_zero_padding(Self::TIMESTAMP_SIZE, "timestamp")?;
261 Ok(Self::Timestamp(Timestamp::from(u64::from_be_bytes(buf))))
262 }
263
264 Self::TAG_UINT => {
265 let mut buf = [0u8; Self::UINT_SIZE];
266 buf.copy_from_slice(&payload[..Self::UINT_SIZE]);
267 ensure_zero_padding(Self::UINT_SIZE, "uint")?;
268 Ok(Self::Uint(u64::from_be_bytes(buf)))
269 }
270
271 Self::TAG_ULID => {
272 let mut buf = [0u8; Self::ULID_SIZE];
273 buf.copy_from_slice(&payload[..Self::ULID_SIZE]);
274 ensure_zero_padding(Self::ULID_SIZE, "ulid")?;
275 Ok(Self::Ulid(Ulid::from_bytes(buf)))
276 }
277
278 Self::TAG_UNIT => {
279 ensure_zero_padding(0, "unit")?;
280 Ok(Self::Unit)
281 }
282
283 _ => Err("corrupted Key: invalid tag"),
284 }
285 }
286}
287
288impl TryFrom<&[u8]> for Key {
289 type Error = &'static str;
290
291 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
292 Self::try_from_bytes(bytes)
293 }
294}
295
296impl Ord for Key {
297 fn cmp(&self, other: &Self) -> Ordering {
298 match (self, other) {
299 (Self::Account(a), Self::Account(b)) => Ord::cmp(a, b),
300 (Self::Int(a), Self::Int(b)) => Ord::cmp(a, b),
301 (Self::Principal(a), Self::Principal(b)) => Ord::cmp(a, b),
302 (Self::Uint(a), Self::Uint(b)) => Ord::cmp(a, b),
303 (Self::Ulid(a), Self::Ulid(b)) => Ord::cmp(a, b),
304 (Self::Subaccount(a), Self::Subaccount(b)) => Ord::cmp(a, b),
305 (Self::Timestamp(a), Self::Timestamp(b)) => Ord::cmp(a, b),
306
307 _ => Ord::cmp(&self.variant_rank(), &other.variant_rank()), }
309 }
310}
311
312impl PartialOrd for Key {
313 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
314 Some(Ord::cmp(self, other))
315 }
316}