Skip to main content

icydb_core/serialize/
mod.rs

1mod cbor;
2
3use crate::error::{ErrorClass, ErrorOrigin, InternalError};
4use serde::{Serialize, de::DeserializeOwned};
5use thiserror::Error as ThisError;
6
7///
8/// SerializeError
9///
10
11#[derive(Debug, ThisError)]
12pub enum SerializeError {
13    #[error("serialize error: {0}")]
14    Serialize(String),
15
16    #[error("deserialize error: {0}")]
17    Deserialize(String),
18}
19
20impl SerializeError {
21    pub(crate) const fn class() -> ErrorClass {
22        ErrorClass::Internal
23    }
24}
25
26impl From<SerializeError> for InternalError {
27    fn from(err: SerializeError) -> Self {
28        Self::new(
29            SerializeError::class(),
30            ErrorOrigin::Serialize,
31            err.to_string(),
32        )
33    }
34}
35
36/// Serialize a value using the default `canic` serializer.
37///
38/// This helper keeps the error type aligned with the rest of `icydb`.
39pub fn serialize<T>(ty: &T) -> Result<Vec<u8>, SerializeError>
40where
41    T: Serialize,
42{
43    cbor::serialize(ty)
44}
45
46/// Deserialize a value produced by [`serialize`].
47pub fn deserialize<T>(bytes: &[u8]) -> Result<T, SerializeError>
48where
49    T: DeserializeOwned,
50{
51    cbor::deserialize(bytes)
52}