icydb_schema/
subaccount.rs1use crate::Principal;
4use candid::CandidType;
5use serde::{Deserialize, Serialize};
6use std::fmt::{self, Display};
7
8type SubaccountBytes = [u8; 32];
13
14#[derive(
15 CandidType,
16 Clone,
17 Copy,
18 Debug,
19 Default,
20 Eq,
21 PartialEq,
22 Hash,
23 Ord,
24 PartialOrd,
25 Serialize,
26 Deserialize,
27)]
28pub struct Subaccount(SubaccountBytes);
30
31impl Subaccount {
32 pub const MIN: Self = Self::from_array([0x00; 32]);
34 pub const MAX: Self = Self::from_array([0xFF; 32]);
36
37 #[must_use]
39 pub const fn to_array(&self) -> [u8; 32] {
40 self.0
41 }
42
43 #[must_use]
45 pub const fn from_array(array: [u8; 32]) -> Self {
46 Self(array)
47 }
48
49 #[must_use]
51 pub const fn as_slice(&self) -> &[u8] {
52 &self.0
53 }
54
55 #[must_use]
57 pub const fn to_bytes(self) -> [u8; 32] {
58 self.0
59 }
60}
61
62impl Display for Subaccount {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 for byte in &self.0 {
65 write!(f, "{byte:02x}")?;
66 }
67
68 Ok(())
69 }
70}
71
72#[expect(clippy::cast_possible_truncation)]
75impl From<Principal> for Subaccount {
76 fn from(principal: Principal) -> Self {
77 let mut bytes = [0u8; 32];
78 let p = principal.as_slice();
79
80 let len = p.len().min(31); bytes[0] = len as u8;
83
84 bytes[1..=len].copy_from_slice(&p[..len]);
86
87 Self(bytes)
88 }
89}