Skip to main content

const_cbor_serde/
lib.rs

1//! Serde support for [`const-cbor`](const_cbor) — a CBOR (RFC 8949)
2//! `serde::Serializer` / `serde::Deserializer` over the allocation-free
3//! core codec.
4//!
5//! # Representation choices
6//!
7//! RFC 8949 does not define a struct/enum mapping, so this crate follows
8//! the ecosystem conventions established by `serde_cbor` and `ciborium`
9//! for interoperability:
10//!
11//! * structs and maps serialize as CBOR maps keyed by field name,
12//! * enums are externally tagged: unit variants as bare text strings,
13//!   other variants as one-entry maps `{ name: payload }`,
14//! * sequences serialize as indefinite-length arrays, maps as
15//!   indefinite-length maps (the core encoder requires known lengths for
16//!   definite forms),
17//! * `Option::None`/unit map to `null`,
18//! * `char` maps to a single-character text string.
19//!
20//! The crate is `no_std` + `alloc`; it never allocates on the encode or
21//! decode path itself.
22
23#![no_std]
24#![forbid(unsafe_code)]
25
26extern crate alloc;
27
28mod de;
29mod error;
30mod ser;
31
32pub use crate::de::Deserializer;
33pub use crate::error::Error;
34pub use crate::ser::Serializer;
35
36use serde::{Deserialize, Serialize};
37
38/// Serializes `value` into `buf`, returning the number of bytes written.
39///
40/// # Errors
41///
42/// Encoding failures ([`Error::Cbor`] out-of-space) and unsupported
43/// data-model elements.
44pub fn to_slice<T: Serialize + ?Sized>(value: &T, buf: &mut [u8]) -> Result<usize, Error> {
45    let mut ser = Serializer::new(buf);
46    value.serialize(&mut ser)?;
47    Ok(ser.written())
48}
49
50/// Deserializes a `T` from the complete CBOR `input`.
51///
52/// Zero-copy: borrowed strings and byte slices point into `input`.
53///
54/// # Errors
55///
56/// Structural/type errors from the decoder, plus trailing-bytes checks.
57pub fn from_slice<'a, T: Deserialize<'a>>(input: &'a [u8]) -> Result<T, Error> {
58    let mut de = Deserializer::new(input);
59    let value = T::deserialize(&mut de)?;
60    if de.pos != de.input.len() {
61        return Err(Error::custom("trailing bytes after value"));
62    }
63    Ok(value)
64}
65
66/// Serializes into a fresh `Vec<u8>` (`alloc`).
67///
68/// Grows a scratch buffer until the value fits; worst case is O(n) total
69/// work across attempts.
70///
71/// # Errors
72///
73/// As [`to_slice`] (except out-of-space, which is resolved by growth).
74pub fn to_vec<T: Serialize + ?Sized>(value: &T) -> Result<alloc::vec::Vec<u8>, Error> {
75    let mut capacity = 512usize;
76    loop {
77        let mut buf = alloc::vec![0u8; capacity];
78        match to_slice(value, &mut buf) {
79            Ok(n) => {
80                buf.truncate(n);
81                return Ok(buf);
82            }
83            Err(Error::Cbor(const_cbor::Error::OUT_OF_SPACE)) => {
84                capacity = capacity.saturating_mul(2);
85            }
86            Err(e) => return Err(e),
87        }
88    }
89}