Skip to main content

icydb_schema/
subaccount.rs

1//! Canonical fixed-width subaccount atom.
2
3use crate::Principal;
4use candid::CandidType;
5use serde::{Deserialize, Serialize};
6use std::fmt::{self, Display};
7
8//
9// Subaccount
10//
11
12type 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)]
28/// A canonical 32-byte ICRC account subaccount.
29pub struct Subaccount(SubaccountBytes);
30
31impl Subaccount {
32    /// The lexicographically smallest subaccount.
33    pub const MIN: Self = Self::from_array([0x00; 32]);
34    /// The lexicographically largest subaccount.
35    pub const MAX: Self = Self::from_array([0xFF; 32]);
36
37    /// Return the fixed-width byte array.
38    #[must_use]
39    pub const fn to_array(&self) -> [u8; 32] {
40        self.0
41    }
42
43    /// Construct from the exact fixed-width byte array.
44    #[must_use]
45    pub const fn from_array(array: [u8; 32]) -> Self {
46        Self(array)
47    }
48
49    /// Borrow the fixed-width bytes.
50    #[must_use]
51    pub const fn as_slice(&self) -> &[u8] {
52        &self.0
53    }
54
55    /// Consume the value and return its fixed-width bytes.
56    #[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// code taken from
73// <https://docs.rs/ic-ledger-types/latest/src/ic_ledger_types/lib.rs.html#140-148>
74#[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        // Defensive check: Principals are currently <= 29 bytes
81        let len = p.len().min(31); // reserve 1 byte for the length prefix
82        bytes[0] = len as u8;
83
84        // Copy safely without panic risk
85        bytes[1..=len].copy_from_slice(&p[..len]);
86
87        Self(bytes)
88    }
89}