1#![expect(clippy::cast_possible_truncation)]
10
11use super::Value;
12use crate::{
13 error::InternalError,
14 traits::Repr,
15 types::{Account, Principal, Subaccount, Timestamp, Ulid},
16};
17use candid::CandidType;
18use derive_more::Display;
19use serde::{Deserialize, Serialize};
20use std::cmp::Ordering;
21use thiserror::Error as ThisError;
22
23#[derive(Debug, ThisError)]
29pub enum StorageKeyEncodeError {
30 #[error("account owner principal exceeds max length: {len} bytes (limit {max})")]
31 AccountOwnerTooLarge { len: usize, max: usize },
32
33 #[error("account payload length mismatch: {len} bytes (expected {expected})")]
34 AccountLengthMismatch { len: usize, expected: usize },
35
36 #[error("value kind '{kind}' is not storage-key encodable")]
37 UnsupportedValueKind { kind: &'static str },
38
39 #[error("principal exceeds max length: {len} bytes (limit {max})")]
40 PrincipalTooLarge { len: usize, max: usize },
41}
42
43impl From<StorageKeyEncodeError> for InternalError {
44 fn from(err: StorageKeyEncodeError) -> Self {
45 Self::serialize_unsupported(err.to_string())
46 }
47}
48
49#[derive(Debug, ThisError)]
55pub enum StorageKeyDecodeError {
56 #[error("corrupted StorageKey: invalid size")]
57 InvalidSize,
58
59 #[error("corrupted StorageKey: invalid tag")]
60 InvalidTag,
61
62 #[error("corrupted StorageKey: invalid principal length")]
63 InvalidPrincipalLength,
64
65 #[error("corrupted StorageKey: non-zero {field} padding")]
66 NonZeroPadding { field: &'static str },
67
68 #[error("corrupted StorageKey: invalid account payload ({reason})")]
69 InvalidAccountPayload { reason: &'static str },
70}
71
72#[derive(CandidType, Clone, Copy, Debug, Deserialize, Display, Eq, Hash, PartialEq, Serialize)]
82pub enum StorageKey {
83 Account(Account),
84 Int(i64),
85 Principal(Principal),
86 Subaccount(Subaccount),
87 Timestamp(Timestamp),
88 Uint(u64),
89 Ulid(Ulid),
90 Unit,
91}
92
93macro_rules! value_is_storage_key_encodable_from_registry {
95 ( @args $value:expr; @entries $( ($scalar:ident, $family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
96 match $value {
97 $( $value_pat => $is_storage_key_encodable, )*
98 _ => false,
99 }
100 };
101}
102
103impl StorageKey {
104 pub(crate) const TAG_ACCOUNT: u8 = 0;
106 pub(crate) const TAG_INT: u8 = 1;
107 pub(crate) const TAG_PRINCIPAL: u8 = 2;
108 pub(crate) const TAG_SUBACCOUNT: u8 = 3;
109 pub(crate) const TAG_TIMESTAMP: u8 = 4;
110 pub(crate) const TAG_UINT: u8 = 5;
111 pub(crate) const TAG_ULID: u8 = 6;
112 pub(crate) const TAG_UNIT: u8 = 7;
113
114 pub const STORED_SIZE_BYTES: u64 = 64;
117 pub const STORED_SIZE_USIZE: usize = Self::STORED_SIZE_BYTES as usize;
118
119 const TAG_SIZE: usize = 1;
120 pub(crate) const TAG_OFFSET: usize = 0;
121
122 pub(crate) const PAYLOAD_OFFSET: usize = Self::TAG_SIZE;
123 const PAYLOAD_SIZE: usize = Self::STORED_SIZE_USIZE - Self::TAG_SIZE;
124
125 pub(crate) const INT_SIZE: usize = 8;
126 pub(crate) const UINT_SIZE: usize = 8;
127 pub(crate) const TIMESTAMP_SIZE: usize = 8;
128 pub(crate) const ULID_SIZE: usize = 16;
129 pub(crate) const SUBACCOUNT_SIZE: usize = 32;
130 const ACCOUNT_MAX_SIZE: usize = 62;
131
132 pub const fn try_from_value(value: &Value) -> Result<Self, StorageKeyEncodeError> {
133 let is_storage_key_encodable =
137 scalar_registry!(value_is_storage_key_encodable_from_registry, value);
138 if !is_storage_key_encodable {
139 return Err(StorageKeyEncodeError::UnsupportedValueKind {
140 kind: Self::value_kind_label(value),
141 });
142 }
143
144 match value {
145 Value::Account(v) => Ok(Self::Account(*v)),
146 Value::Int(v) => Ok(Self::Int(*v)),
147 Value::Principal(v) => Ok(Self::Principal(*v)),
148 Value::Subaccount(v) => Ok(Self::Subaccount(*v)),
149 Value::Timestamp(v) => Ok(Self::Timestamp(*v)),
150 Value::Uint(v) => Ok(Self::Uint(*v)),
151 Value::Ulid(v) => Ok(Self::Ulid(*v)),
152 Value::Unit => Ok(Self::Unit),
153
154 _ => Err(StorageKeyEncodeError::UnsupportedValueKind {
155 kind: Self::value_kind_label(value),
156 }),
157 }
158 }
159
160 const fn value_kind_label(value: &Value) -> &'static str {
161 match value {
162 Value::Account(_) => "Account",
163 Value::Blob(_) => "Blob",
164 Value::Bool(_) => "Bool",
165 Value::Date(_) => "Date",
166 Value::Decimal(_) => "Decimal",
167 Value::Duration(_) => "Duration",
168 Value::Enum(_) => "Enum",
169 Value::Float32(_) => "Float32",
170 Value::Float64(_) => "Float64",
171 Value::Int(_) => "Int",
172 Value::Int128(_) => "Int128",
173 Value::IntBig(_) => "IntBig",
174 Value::List(_) => "List",
175 Value::Map(_) => "Map",
176 Value::Null => "Null",
177 Value::Principal(_) => "Principal",
178 Value::Subaccount(_) => "Subaccount",
179 Value::Text(_) => "Text",
180 Value::Timestamp(_) => "Timestamp",
181 Value::Uint(_) => "Uint",
182 Value::Uint128(_) => "Uint128",
183 Value::UintBig(_) => "UintBig",
184 Value::Ulid(_) => "Ulid",
185 Value::Unit => "Unit",
186 }
187 }
188
189 const fn tag(&self) -> u8 {
190 match self {
191 Self::Account(_) => Self::TAG_ACCOUNT,
192 Self::Int(_) => Self::TAG_INT,
193 Self::Principal(_) => Self::TAG_PRINCIPAL,
194 Self::Subaccount(_) => Self::TAG_SUBACCOUNT,
195 Self::Timestamp(_) => Self::TAG_TIMESTAMP,
196 Self::Uint(_) => Self::TAG_UINT,
197 Self::Ulid(_) => Self::TAG_ULID,
198 Self::Unit => Self::TAG_UNIT,
199 }
200 }
201
202 #[must_use]
204 pub fn max_storable() -> Self {
205 Self::Account(Account::max_storable())
206 }
207
208 pub const MIN: Self = Self::Account(Account::from_parts(Principal::from_slice(&[]), None));
210
211 #[must_use]
212 pub const fn lower_bound() -> Self {
213 Self::MIN
214 }
215
216 #[must_use]
217 pub const fn upper_bound() -> Self {
218 Self::Unit
219 }
220
221 const fn variant_rank(&self) -> u8 {
222 self.tag()
223 }
224
225 const fn from_account_encode_error(
226 err: crate::types::AccountEncodeError,
227 ) -> StorageKeyEncodeError {
228 match err {
229 crate::types::AccountEncodeError::OwnerEncode(inner) => {
230 Self::from_principal_encode_error(inner)
231 }
232 crate::types::AccountEncodeError::OwnerTooLarge { len, max } => {
233 StorageKeyEncodeError::AccountOwnerTooLarge { len, max }
234 }
235 }
236 }
237
238 const fn from_principal_encode_error(
239 err: crate::types::PrincipalEncodeError,
240 ) -> StorageKeyEncodeError {
241 match err {
242 crate::types::PrincipalEncodeError::TooLarge { len, max } => {
243 StorageKeyEncodeError::PrincipalTooLarge { len, max }
244 }
245 }
246 }
247
248 pub fn to_bytes(self) -> Result<[u8; Self::STORED_SIZE_USIZE], StorageKeyEncodeError> {
250 let mut buf = [0u8; Self::STORED_SIZE_USIZE];
252 buf[Self::TAG_OFFSET] = self.tag();
253 let payload = &mut buf[Self::PAYLOAD_OFFSET..=Self::PAYLOAD_SIZE];
254
255 match self {
257 Self::Account(v) => {
258 let bytes = v.to_bytes().map_err(Self::from_account_encode_error)?;
259 if bytes.len() != Self::ACCOUNT_MAX_SIZE {
260 return Err(StorageKeyEncodeError::AccountLengthMismatch {
261 len: bytes.len(),
262 expected: Self::ACCOUNT_MAX_SIZE,
263 });
264 }
265 payload[..bytes.len()].copy_from_slice(&bytes);
266 }
267 Self::Int(v) => {
268 let biased = v.cast_unsigned() ^ (1u64 << 63);
269 payload[..Self::INT_SIZE].copy_from_slice(&biased.to_be_bytes());
270 }
271 Self::Uint(v) => payload[..Self::UINT_SIZE].copy_from_slice(&v.to_be_bytes()),
272 Self::Timestamp(v) => {
273 payload[..Self::TIMESTAMP_SIZE].copy_from_slice(&v.repr().to_be_bytes());
274 }
275 Self::Principal(v) => {
276 let bytes = v.to_bytes().map_err(Self::from_principal_encode_error)?;
277 let len = bytes.len();
278 payload[0] =
279 u8::try_from(len).map_err(|_| StorageKeyEncodeError::PrincipalTooLarge {
280 len,
281 max: Principal::MAX_LENGTH_IN_BYTES as usize,
282 })?;
283 payload[1..=len].copy_from_slice(&bytes[..len]);
284 }
285 Self::Subaccount(v) => payload[..Self::SUBACCOUNT_SIZE].copy_from_slice(&v.to_array()),
286 Self::Ulid(v) => payload[..Self::ULID_SIZE].copy_from_slice(&v.to_bytes()),
287 Self::Unit => {}
288 }
289
290 Ok(buf)
291 }
292
293 pub fn try_from_bytes(bytes: &[u8]) -> Result<Self, StorageKeyDecodeError> {
294 if bytes.len() != Self::STORED_SIZE_USIZE {
296 return Err(StorageKeyDecodeError::InvalidSize);
297 }
298
299 let tag = bytes[Self::TAG_OFFSET];
300 let payload = &bytes[Self::PAYLOAD_OFFSET..=Self::PAYLOAD_SIZE];
301
302 let ensure_zero_padding = |used: usize, ctx: &'static str| {
303 if payload[used..].iter().all(|&b| b == 0) {
304 Ok(())
305 } else {
306 Err(StorageKeyDecodeError::NonZeroPadding { field: ctx })
307 }
308 };
309
310 match tag {
312 Self::TAG_ACCOUNT => {
313 let end = Account::STORED_SIZE as usize;
314 ensure_zero_padding(end, "account")?;
315 Ok(Self::Account(
316 Account::try_from_bytes(&payload[..end]).map_err(|reason| {
317 StorageKeyDecodeError::InvalidAccountPayload { reason }
318 })?,
319 ))
320 }
321 Self::TAG_INT => {
322 let mut buf = [0u8; Self::INT_SIZE];
323 buf.copy_from_slice(&payload[..Self::INT_SIZE]);
324 ensure_zero_padding(Self::INT_SIZE, "int")?;
325 Ok(Self::Int(
326 (u64::from_be_bytes(buf) ^ (1u64 << 63)).cast_signed(),
327 ))
328 }
329 Self::TAG_PRINCIPAL => {
330 let len = payload[0] as usize;
331 if len > Principal::MAX_LENGTH_IN_BYTES as usize {
332 return Err(StorageKeyDecodeError::InvalidPrincipalLength);
333 }
334 ensure_zero_padding(1 + len, "principal")?;
335 Ok(Self::Principal(Principal::from_slice(&payload[1..=len])))
336 }
337 Self::TAG_SUBACCOUNT => {
338 ensure_zero_padding(Self::SUBACCOUNT_SIZE, "subaccount")?;
339 let mut buf = [0u8; Self::SUBACCOUNT_SIZE];
340 buf.copy_from_slice(&payload[..Self::SUBACCOUNT_SIZE]);
341 Ok(Self::Subaccount(Subaccount::from_array(buf)))
342 }
343 Self::TAG_TIMESTAMP => {
344 ensure_zero_padding(Self::TIMESTAMP_SIZE, "timestamp")?;
345 let mut buf = [0u8; Self::TIMESTAMP_SIZE];
346 buf.copy_from_slice(&payload[..Self::TIMESTAMP_SIZE]);
347 Ok(Self::Timestamp(Timestamp::from_repr(i64::from_be_bytes(
348 buf,
349 ))))
350 }
351 Self::TAG_UINT => {
352 ensure_zero_padding(Self::UINT_SIZE, "uint")?;
353 let mut buf = [0u8; Self::UINT_SIZE];
354 buf.copy_from_slice(&payload[..Self::UINT_SIZE]);
355 Ok(Self::Uint(u64::from_be_bytes(buf)))
356 }
357 Self::TAG_ULID => {
358 ensure_zero_padding(Self::ULID_SIZE, "ulid")?;
359 let mut buf = [0u8; Self::ULID_SIZE];
360 buf.copy_from_slice(&payload[..Self::ULID_SIZE]);
361 Ok(Self::Ulid(Ulid::from_bytes(buf)))
362 }
363 Self::TAG_UNIT => {
364 ensure_zero_padding(0, "unit")?;
365 Ok(Self::Unit)
366 }
367 _ => Err(StorageKeyDecodeError::InvalidTag),
368 }
369 }
370
371 #[must_use]
376 pub const fn as_value(&self) -> Value {
377 match self {
378 Self::Account(v) => Value::Account(*v),
379 Self::Int(v) => Value::Int(*v),
380 Self::Principal(v) => Value::Principal(*v),
381 Self::Subaccount(v) => Value::Subaccount(*v),
382 Self::Timestamp(v) => Value::Timestamp(*v),
383 Self::Uint(v) => Value::Uint(*v),
384 Self::Ulid(v) => Value::Ulid(*v),
385 Self::Unit => Value::Unit,
386 }
387 }
388}
389
390impl Ord for StorageKey {
391 fn cmp(&self, other: &Self) -> Ordering {
392 match (self, other) {
393 (Self::Account(a), Self::Account(b)) => a.cmp(b),
394 (Self::Int(a), Self::Int(b)) => a.cmp(b),
395 (Self::Principal(a), Self::Principal(b)) => a.cmp(b),
396 (Self::Uint(a), Self::Uint(b)) => a.cmp(b),
397 (Self::Ulid(a), Self::Ulid(b)) => a.cmp(b),
398 (Self::Subaccount(a), Self::Subaccount(b)) => a.cmp(b),
399 (Self::Timestamp(a), Self::Timestamp(b)) => a.cmp(b),
400 _ => self.variant_rank().cmp(&other.variant_rank()),
401 }
402 }
403}
404
405impl PartialOrd for StorageKey {
406 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
407 Some(self.cmp(other))
408 }
409}
410
411impl TryFrom<&[u8]> for StorageKey {
412 type Error = StorageKeyDecodeError;
413 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
414 Self::try_from_bytes(bytes)
415 }
416}
417
418#[cfg(test)]
423mod tests {
424 use super::{StorageKey, StorageKeyDecodeError, StorageKeyEncodeError};
425 use crate::{
426 types::{
427 Account, Date, Decimal, Duration, Float32, Float64, Int, Int128, Nat, Nat128,
428 Principal, Subaccount, Timestamp, Ulid,
429 },
430 value::{Value, ValueEnum},
431 };
432
433 macro_rules! sample_value_for_scalar {
434 (Account) => {
435 Value::Account(Account::dummy(7))
436 };
437 (Blob) => {
438 Value::Blob(vec![1u8, 2u8, 3u8])
439 };
440 (Bool) => {
441 Value::Bool(true)
442 };
443 (Date) => {
444 Value::Date(Date::new(2024, 1, 2))
445 };
446 (Decimal) => {
447 Value::Decimal(Decimal::new(123, 2))
448 };
449 (Duration) => {
450 Value::Duration(Duration::from_secs(1))
451 };
452 (Enum) => {
453 Value::Enum(ValueEnum::loose("example"))
454 };
455 (Float32) => {
456 Value::Float32(Float32::try_new(1.25).expect("Float32 sample should be finite"))
457 };
458 (Float64) => {
459 Value::Float64(Float64::try_new(2.5).expect("Float64 sample should be finite"))
460 };
461 (Int) => {
462 Value::Int(-7)
463 };
464 (Int128) => {
465 Value::Int128(Int128::from(123i128))
466 };
467 (IntBig) => {
468 Value::IntBig(Int::from(99i32))
469 };
470 (Principal) => {
471 Value::Principal(Principal::from_slice(&[1u8, 2u8, 3u8]))
472 };
473 (Subaccount) => {
474 Value::Subaccount(Subaccount::new([1u8; 32]))
475 };
476 (Text) => {
477 Value::Text("example".to_string())
478 };
479 (Timestamp) => {
480 Value::Timestamp(Timestamp::from_secs(1))
481 };
482 (Uint) => {
483 Value::Uint(7)
484 };
485 (Uint128) => {
486 Value::Uint128(Nat128::from(9u128))
487 };
488 (UintBig) => {
489 Value::UintBig(Nat::from(11u64))
490 };
491 (Ulid) => {
492 Value::Ulid(Ulid::from_u128(42))
493 };
494 (Unit) => {
495 Value::Unit
496 };
497 }
498
499 fn registry_storage_encodable_cases() -> Vec<(Value, bool)> {
500 macro_rules! collect_cases {
501 ( @entries $( ($scalar:ident, $family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
502 vec![ $( (sample_value_for_scalar!($scalar), $is_storage_key_encodable) ),* ]
503 };
504 ( @args $($ignore:tt)*; @entries $( ($scalar:ident, $family:expr, $value_pat:pat, is_numeric_value = $is_numeric:expr, supports_numeric_coercion = $supports_numeric_coercion:expr, supports_arithmetic = $supports_arithmetic:expr, supports_equality = $supports_equality:expr, supports_ordering = $supports_ordering:expr, is_keyable = $is_keyable:expr, is_storage_key_encodable = $is_storage_key_encodable:expr) ),* $(,)? ) => {
505 vec![ $( (sample_value_for_scalar!($scalar), $is_storage_key_encodable) ),* ]
506 };
507 }
508
509 scalar_registry!(collect_cases)
510 }
511
512 #[test]
513 fn storage_key_try_from_value_matches_registry_flag() {
514 for (value, expected_encodable) in registry_storage_encodable_cases() {
515 assert_eq!(
516 StorageKey::try_from_value(&value).is_ok(),
517 expected_encodable,
518 "value: {value:?}"
519 );
520 }
521 }
522
523 #[test]
524 fn storage_key_known_encodability_contracts() {
525 assert!(StorageKey::try_from_value(&Value::Unit).is_ok());
526 assert!(StorageKey::try_from_value(&Value::Decimal(Decimal::new(1, 0))).is_err());
527 assert!(StorageKey::try_from_value(&Value::Text("x".to_string())).is_err());
528 assert!(StorageKey::try_from_value(&Value::Account(Account::dummy(1))).is_ok());
529 }
530
531 #[test]
532 fn storage_key_unsupported_values_report_kind() {
533 let decimal_err = StorageKey::try_from_value(&Value::Decimal(Decimal::new(1, 0)))
534 .expect_err("Decimal is not storage-key encodable");
535 assert!(matches!(
536 decimal_err,
537 StorageKeyEncodeError::UnsupportedValueKind { kind } if kind == "Decimal"
538 ));
539
540 let text_err = StorageKey::try_from_value(&Value::Text("x".to_string()))
541 .expect_err("Text is not storage-key encodable");
542 assert!(matches!(
543 text_err,
544 StorageKeyEncodeError::UnsupportedValueKind { kind } if kind == "Text"
545 ));
546 }
547
548 #[test]
549 fn storage_keys_sort_deterministically_across_mixed_variants() {
550 let mut keys = vec![
551 StorageKey::try_from_value(&Value::Unit).expect("Unit is encodable"),
552 StorageKey::try_from_value(&Value::Ulid(Ulid::from_u128(2)))
553 .expect("Ulid is encodable"),
554 StorageKey::try_from_value(&Value::Uint(2)).expect("Uint is encodable"),
555 StorageKey::try_from_value(&Value::Timestamp(Timestamp::from_secs(2)))
556 .expect("Timestamp is encodable"),
557 StorageKey::try_from_value(&Value::Subaccount(Subaccount::new([3u8; 32])))
558 .expect("Subaccount is encodable"),
559 StorageKey::try_from_value(&Value::Principal(Principal::from_slice(&[9u8])))
560 .expect("Principal is encodable"),
561 StorageKey::try_from_value(&Value::Int(-1)).expect("Int is encodable"),
562 StorageKey::try_from_value(&Value::Account(Account::dummy(3)))
563 .expect("Account is encodable"),
564 ];
565
566 keys.sort();
567
568 let expected = vec![
569 StorageKey::Account(Account::dummy(3)),
570 StorageKey::Int(-1),
571 StorageKey::Principal(Principal::from_slice(&[9u8])),
572 StorageKey::Subaccount(Subaccount::new([3u8; 32])),
573 StorageKey::Timestamp(Timestamp::from_secs(2)),
574 StorageKey::Uint(2),
575 StorageKey::Ulid(Ulid::from_u128(2)),
576 StorageKey::Unit,
577 ];
578
579 assert_eq!(keys, expected);
580 }
581
582 #[test]
583 fn storage_key_decode_rejects_invalid_size_as_structured_error() {
584 let err =
585 StorageKey::try_from_bytes(&[]).expect_err("decode should reject invalid key size");
586 assert!(matches!(err, StorageKeyDecodeError::InvalidSize));
587 }
588
589 #[test]
590 fn storage_key_decode_rejects_invalid_tag_as_structured_error() {
591 let mut bytes = [0u8; StorageKey::STORED_SIZE_USIZE];
592 bytes[StorageKey::TAG_OFFSET] = 0xFF;
593
594 let err = StorageKey::try_from_bytes(&bytes).expect_err("decode should reject invalid tag");
595 assert!(matches!(err, StorageKeyDecodeError::InvalidTag));
596 }
597
598 #[test]
599 fn storage_key_decode_rejects_non_zero_padding_with_segment_context() {
600 let mut bytes = [0u8; StorageKey::STORED_SIZE_USIZE];
601 bytes[StorageKey::TAG_OFFSET] = StorageKey::TAG_UNIT;
602 bytes[StorageKey::PAYLOAD_OFFSET] = 1;
603
604 let err = StorageKey::try_from_bytes(&bytes)
605 .expect_err("decode should reject non-zero padding for unit payload");
606 assert!(matches!(
607 err,
608 StorageKeyDecodeError::NonZeroPadding { field } if field == "unit"
609 ));
610 }
611}