Skip to main content

icydb_core/key/
mod.rs

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///
18/// Key
19///
20/// Treating IndexKey as the atomic, normalized unit of the keyspace
21/// Backing primary keys and secondary indexes with the same value representation
22/// Planning to enforce Copy semantics (i.e., fast, clean, safe)
23///
24
25#[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///
38/// KeyEncodeError
39///
40/// Errors returned when encoding a key for persistence.
41///
42
43#[derive(Debug, ThisError)]
44pub enum KeyEncodeError {
45    #[error("account encoding failed: {0}")]
46    Account(#[from] AccountEncodeError),
47    #[error("account payload length mismatch: {len} bytes (expected {expected})")]
48    AccountLengthMismatch { len: usize, expected: usize },
49    #[error("principal encoding failed: {0}")]
50    Principal(#[from] PrincipalEncodeError),
51}
52
53impl From<KeyEncodeError> for InternalError {
54    fn from(err: KeyEncodeError) -> Self {
55        Self::new(
56            ErrorClass::Unsupported,
57            ErrorOrigin::Serialize,
58            err.to_string(),
59        )
60    }
61}
62
63impl Key {
64    // ── Variant tags (do not reorder) ─────────────────
65    pub(crate) const TAG_ACCOUNT: u8 = 0;
66    pub(crate) const TAG_INT: u8 = 1;
67    pub(crate) const TAG_PRINCIPAL: u8 = 2;
68    pub(crate) const TAG_SUBACCOUNT: u8 = 3;
69    pub(crate) const TAG_TIMESTAMP: u8 = 4;
70    pub(crate) const TAG_UINT: u8 = 5;
71    pub(crate) const TAG_ULID: u8 = 6;
72    pub(crate) const TAG_UNIT: u8 = 7;
73
74    /// Fixed serialized size (do not change without migration)
75    pub const STORED_SIZE: usize = 64;
76
77    // ── Layout ─────────────────────────────────────
78    const TAG_SIZE: usize = 1;
79    pub(crate) const TAG_OFFSET: usize = 0;
80
81    pub(crate) const PAYLOAD_OFFSET: usize = Self::TAG_SIZE;
82    const PAYLOAD_SIZE: usize = Self::STORED_SIZE - Self::TAG_SIZE;
83
84    // ── Payload sizes ──────────────────────────────
85    pub(crate) const INT_SIZE: usize = 8;
86    pub(crate) const UINT_SIZE: usize = 8;
87    pub(crate) const TIMESTAMP_SIZE: usize = 8;
88    pub(crate) const ULID_SIZE: usize = 16;
89    pub(crate) const SUBACCOUNT_SIZE: usize = 32;
90    const ACCOUNT_MAX_SIZE: usize = 62;
91
92    const fn tag(&self) -> u8 {
93        match self {
94            Self::Account(_) => Self::TAG_ACCOUNT,
95            Self::Int(_) => Self::TAG_INT,
96            Self::Principal(_) => Self::TAG_PRINCIPAL,
97            Self::Subaccount(_) => Self::TAG_SUBACCOUNT,
98            Self::Timestamp(_) => Self::TAG_TIMESTAMP,
99            Self::Uint(_) => Self::TAG_UINT,
100            Self::Ulid(_) => Self::TAG_ULID,
101            Self::Unit => Self::TAG_UNIT,
102        }
103    }
104
105    #[must_use]
106    /// Sentinel key representing the maximum storable account value.
107    pub fn max_storable() -> Self {
108        Self::Account(Account::max_storable())
109    }
110
111    /// Global minimum key for scan bounds and key range construction.
112    pub const MIN: Self = Self::Account(Account {
113        owner: Principal::from_slice(&[]),
114        subaccount: None,
115    });
116
117    #[must_use]
118    pub const fn lower_bound() -> Self {
119        Self::MIN
120    }
121
122    #[must_use]
123    pub const fn upper_bound() -> Self {
124        Self::Unit
125    }
126
127    const fn variant_rank(&self) -> u8 {
128        self.tag()
129    }
130
131    /// Encode this key into its fixed-size storage representation.
132    pub fn to_bytes(&self) -> Result<[u8; Self::STORED_SIZE], KeyEncodeError> {
133        let mut buf = [0u8; Self::STORED_SIZE];
134
135        // ── Tag ─────────────────────────────────────
136        buf[Self::TAG_OFFSET] = self.tag();
137        let payload = &mut buf[Self::PAYLOAD_OFFSET..=Self::PAYLOAD_SIZE];
138
139        // ── Payload ─────────────────────────────────
140        #[allow(clippy::cast_possible_truncation)]
141        match self {
142            Self::Account(v) => {
143                let bytes = v.to_bytes()?;
144                if bytes.len() != Self::ACCOUNT_MAX_SIZE {
145                    return Err(KeyEncodeError::AccountLengthMismatch {
146                        len: bytes.len(),
147                        expected: Self::ACCOUNT_MAX_SIZE,
148                    });
149                }
150                payload[..bytes.len()].copy_from_slice(&bytes);
151            }
152
153            Self::Int(v) => {
154                // Flip sign bit to preserve ordering in lexicographic bytes.
155                let biased = (*v).cast_unsigned() ^ (1u64 << 63);
156                payload[..Self::INT_SIZE].copy_from_slice(&biased.to_be_bytes());
157            }
158
159            Self::Uint(v) => {
160                payload[..Self::UINT_SIZE].copy_from_slice(&v.to_be_bytes());
161            }
162
163            Self::Timestamp(v) => {
164                payload[..Self::TIMESTAMP_SIZE].copy_from_slice(&v.get().to_be_bytes());
165            }
166
167            Self::Principal(v) => {
168                let bytes = v.to_bytes()?;
169                let len = bytes.len();
170                payload[0] = u8::try_from(len).map_err(|_| {
171                    KeyEncodeError::Principal(PrincipalEncodeError::TooLarge {
172                        len,
173                        max: Principal::MAX_LENGTH_IN_BYTES as usize,
174                    })
175                })?;
176                if len > 0 {
177                    payload[1..=len].copy_from_slice(&bytes[..len]);
178                }
179            }
180
181            Self::Subaccount(v) => {
182                let bytes = v.to_array();
183                payload[..Self::SUBACCOUNT_SIZE].copy_from_slice(&bytes);
184            }
185
186            Self::Ulid(v) => {
187                payload[..Self::ULID_SIZE].copy_from_slice(&v.to_bytes());
188            }
189
190            Self::Unit => {}
191        }
192
193        Ok(buf)
194    }
195
196    pub fn try_from_bytes(bytes: &[u8]) -> Result<Self, &'static str> {
197        if bytes.len() != Self::STORED_SIZE {
198            return Err("corrupted Key: invalid size");
199        }
200
201        let tag = bytes[Self::TAG_OFFSET];
202        let payload = &bytes[Self::PAYLOAD_OFFSET..=Self::PAYLOAD_SIZE];
203
204        let ensure_zero_padding = |used: usize, context: &str| {
205            if payload[used..].iter().all(|&b| b == 0) {
206                Ok(())
207            } else {
208                Err(match context {
209                    "account" => "corrupted Key: non-zero account padding",
210                    "int" => "corrupted Key: non-zero int padding",
211                    "principal" => "corrupted Key: non-zero principal padding",
212                    "subaccount" => "corrupted Key: non-zero subaccount padding",
213                    "timestamp" => "corrupted Key: non-zero timestamp padding",
214                    "uint" => "corrupted Key: non-zero uint padding",
215                    "ulid" => "corrupted Key: non-zero ulid padding",
216                    "unit" => "corrupted Key: non-zero unit padding",
217                    _ => "corrupted Key: non-zero padding",
218                })
219            }
220        };
221
222        match tag {
223            Self::TAG_ACCOUNT => {
224                let end = Account::STORED_SIZE as usize;
225                ensure_zero_padding(end, "account")?;
226                let account = Account::try_from_bytes(&payload[..end])?;
227                Ok(Self::Account(account))
228            }
229
230            Self::TAG_INT => {
231                let mut buf = [0u8; Self::INT_SIZE];
232                buf.copy_from_slice(&payload[..Self::INT_SIZE]);
233                let biased = u64::from_be_bytes(buf);
234                ensure_zero_padding(Self::INT_SIZE, "int")?;
235                Ok(Self::Int((biased ^ (1u64 << 63)).cast_signed()))
236            }
237
238            Self::TAG_PRINCIPAL => {
239                let len = payload[0] as usize;
240                if len > Principal::MAX_LENGTH_IN_BYTES as usize {
241                    return Err("corrupted Key: invalid principal length");
242                }
243                let end = 1 + len;
244                ensure_zero_padding(end, "principal")?;
245                Ok(Self::Principal(Principal::from_slice(&payload[1..end])))
246            }
247
248            Self::TAG_SUBACCOUNT => {
249                let mut buf = [0u8; Self::SUBACCOUNT_SIZE];
250                buf.copy_from_slice(&payload[..Self::SUBACCOUNT_SIZE]);
251                ensure_zero_padding(Self::SUBACCOUNT_SIZE, "subaccount")?;
252                Ok(Self::Subaccount(Subaccount::from_array(buf)))
253            }
254
255            Self::TAG_TIMESTAMP => {
256                let mut buf = [0u8; Self::TIMESTAMP_SIZE];
257                buf.copy_from_slice(&payload[..Self::TIMESTAMP_SIZE]);
258                ensure_zero_padding(Self::TIMESTAMP_SIZE, "timestamp")?;
259                Ok(Self::Timestamp(Timestamp::from(u64::from_be_bytes(buf))))
260            }
261
262            Self::TAG_UINT => {
263                let mut buf = [0u8; Self::UINT_SIZE];
264                buf.copy_from_slice(&payload[..Self::UINT_SIZE]);
265                ensure_zero_padding(Self::UINT_SIZE, "uint")?;
266                Ok(Self::Uint(u64::from_be_bytes(buf)))
267            }
268
269            Self::TAG_ULID => {
270                let mut buf = [0u8; Self::ULID_SIZE];
271                buf.copy_from_slice(&payload[..Self::ULID_SIZE]);
272                ensure_zero_padding(Self::ULID_SIZE, "ulid")?;
273                Ok(Self::Ulid(Ulid::from_bytes(buf)))
274            }
275
276            Self::TAG_UNIT => {
277                ensure_zero_padding(0, "unit")?;
278                Ok(Self::Unit)
279            }
280
281            _ => Err("corrupted Key: invalid tag"),
282        }
283    }
284}
285
286impl TryFrom<&[u8]> for Key {
287    type Error = &'static str;
288
289    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
290        Self::try_from_bytes(bytes)
291    }
292}
293
294impl Ord for Key {
295    fn cmp(&self, other: &Self) -> Ordering {
296        match (self, other) {
297            (Self::Account(a), Self::Account(b)) => Ord::cmp(a, b),
298            (Self::Int(a), Self::Int(b)) => Ord::cmp(a, b),
299            (Self::Principal(a), Self::Principal(b)) => Ord::cmp(a, b),
300            (Self::Uint(a), Self::Uint(b)) => Ord::cmp(a, b),
301            (Self::Ulid(a), Self::Ulid(b)) => Ord::cmp(a, b),
302            (Self::Subaccount(a), Self::Subaccount(b)) => Ord::cmp(a, b),
303            (Self::Timestamp(a), Self::Timestamp(b)) => Ord::cmp(a, b),
304
305            _ => Ord::cmp(&self.variant_rank(), &other.variant_rank()), // fallback for cross-type comparison
306        }
307    }
308}
309
310impl PartialOrd for Key {
311    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
312        Some(Ord::cmp(self, other))
313    }
314}