ic_dbms_api/memory/
encode.rs

1use std::borrow::Cow;
2
3use crate::memory::{MSize, MemoryResult};
4
5/// This trait defines the encoding and decoding behaviour for data types used in the DBMS canister.
6pub trait Encode: Clone {
7    const SIZE: DataSize;
8
9    /// Encodes the data type into a vector of bytes.
10    fn encode(&'_ self) -> Cow<'_, [u8]>;
11
12    /// Decodes the data type from a slice of bytes.
13    fn decode(data: Cow<[u8]>) -> MemoryResult<Self>
14    where
15        Self: Sized;
16
17    /// Returns the size in bytes of the encoded data type.
18    fn size(&self) -> MSize;
19}
20
21/// Represents the size of data types used in the DBMS canister.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum DataSize {
24    /// A fixed size in bytes.
25    Fixed(MSize),
26    /// A variable size.
27    Dynamic,
28}
29
30impl DataSize {
31    /// Returns the size in bytes if the data size is fixed.
32    pub fn get_fixed_size(&self) -> Option<MSize> {
33        match self {
34            DataSize::Fixed(size) => Some(*size),
35            DataSize::Dynamic => None,
36        }
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    #[test]
45    fn test_should_get_data_size_fixed() {
46        let size = DataSize::Fixed(10);
47        assert_eq!(size.get_fixed_size(), Some(10));
48
49        let variable_size = DataSize::Dynamic;
50        assert_eq!(variable_size.get_fixed_size(), None);
51    }
52}