Skip to main content

yeti_types/
encoding.rs

1//! Storage encoding — serialize/deserialize values for storage.
2//!
3//! Provides `encode()` and `decode()` using MessagePack for compact binary
4//! serialization, and the `KeyEncoder` trait for ordered-binary key encoding.
5//!
6//! # Errors
7//!
8//! `encode` / `decode` and the `KeyEncoder` methods return
9//! `Result<T, YetiError>` with `Encoding(EncodingError::MessagePack)` on
10//! failure. Causes:
11//! - serialization: a `Serialize` impl returning an error, or a value
12//!   shape unrepresentable in `MessagePack`.
13//! - deserialization: bytes not valid `MessagePack`, or the wire shape
14//!   does not match `T: DeserializeOwned`.
15#![allow(clippy::missing_errors_doc)]
16
17use crate::error::{EncodingError, Result, YetiError};
18use serde::Serialize;
19use serde::de::DeserializeOwned;
20
21/// Serialize a value to bytes for storage (`MessagePack` format).
22#[inline]
23pub fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>> {
24    rmp_serde::to_vec(value).map_err(|e| {
25        YetiError::Encoding(EncodingError::MessagePack(format!(
26            "Failed to serialize to MessagePack: {e}"
27        )))
28    })
29}
30
31/// Deserialize bytes from storage to a value (`MessagePack` format).
32#[inline]
33pub fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {
34    rmp_serde::from_slice(bytes).map_err(|e| {
35        YetiError::Encoding(EncodingError::MessagePack(format!(
36            "Failed to deserialize from MessagePack: {e}"
37        )))
38    })
39}
40
41/// Try to deserialize bytes, returning None on failure.
42#[inline]
43#[must_use]
44pub fn try_decode<T: DeserializeOwned>(bytes: &[u8]) -> Option<T> {
45    rmp_serde::from_slice(bytes).ok()
46}
47
48/// Trait for ordered-binary key encoding.
49///
50/// Implementations must preserve lexicographic sort order in binary
51/// representation — critical for range queries to work correctly.
52pub trait KeyEncoder {
53    /// Encode a JSON value to ordered-binary bytes.
54    fn encode_key(&self, key: &serde_json::Value) -> Result<Vec<u8>>;
55
56    /// Decode ordered-binary bytes back to a JSON value.
57    ///
58    /// Returns (decoded value, bytes consumed).
59    fn decode_key(&self, bytes: &[u8]) -> Result<(serde_json::Value, usize)>;
60}