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/// Generic CBOR serialization infrastructure.
8///
9/// This module is format-level only:
10/// - No database-layer constants or policy limits are defined here.
11/// - Callers that need bounded decode must pass explicit limits.
12/// - Engine-specific decode policy belongs in subsystem wrappers (for example, `db::codec`).
13
14///
15/// SerializeError
16///
17
18#[derive(Debug, ThisError)]
19pub enum SerializeError {
20    #[error("serialize error: {0}")]
21    Serialize(String),
22
23    #[error("deserialize error: {0}")]
24    Deserialize(String),
25}
26
27impl From<SerializeError> for InternalError {
28    fn from(err: SerializeError) -> Self {
29        Self::new(
30            ErrorClass::Internal,
31            ErrorOrigin::Serialize,
32            err.to_string(),
33        )
34    }
35}
36
37/// Serialize a value using the default `canic` serializer.
38///
39/// This helper keeps the error type aligned with the rest of `icydb`.
40pub fn serialize<T>(ty: &T) -> Result<Vec<u8>, SerializeError>
41where
42    T: Serialize,
43{
44    cbor::serialize(ty)
45}
46
47/// Deserialize a value produced by [`serialize`].
48pub fn deserialize<T>(bytes: &[u8]) -> Result<T, SerializeError>
49where
50    T: DeserializeOwned,
51{
52    cbor::deserialize(bytes)
53}
54
55/// Deserialize a value produced by [`serialize`], with an explicit size limit.
56///
57/// Size limits are caller policy, not serialization-format policy.
58pub fn deserialize_bounded<T>(bytes: &[u8], max_bytes: usize) -> Result<T, SerializeError>
59where
60    T: DeserializeOwned,
61{
62    cbor::deserialize_bounded(bytes, max_bytes)
63}