//! Canonical CBOR encoding.
//!
//! Determinism depends on two properties:
//! 1. The encoder MUST NOT emit indefinite-length items.
//! 2. Map keys MUST appear in lexicographic byte order (CBOR canonical form,
//!    RFC 8949 §4.2.1). `ciborium` respects struct field declaration order; the
//!    type-level invariant is: every serialized struct declares fields in
//!    lexicographic order. Each new struct added must respect this.

use serde::{de::DeserializeOwned, Serialize};

use crate::error::{Error, Result};

/// Encode any serializable value to canonical CBOR bytes.
pub fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>> {
    let mut buf = Vec::new();
    ciborium::into_writer(value, &mut buf).map_err(|err| Error::Encode(err.to_string()))?;
    Ok(buf)
}

/// Decode canonical CBOR bytes back to a value.
pub fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {
    ciborium::from_reader(bytes).map_err(|err| Error::Decode(err.to_string()))
}
