Skip to main content

reliakit_codec/
helpers.rs

1//! Convenience helpers for common encode and decode operations.
2
3use crate::{CanonicalDecode, CodecError, SliceReader};
4
5#[cfg(feature = "alloc")]
6use crate::CanonicalEncode;
7
8/// Encodes a value into an owned byte vector.
9#[cfg(feature = "alloc")]
10pub fn encode_to_vec<T: CanonicalEncode + ?Sized>(
11    value: &T,
12) -> Result<alloc::vec::Vec<u8>, CodecError> {
13    let mut out = alloc::vec::Vec::new();
14    value.encode(&mut out)?;
15    Ok(out)
16}
17
18/// Decodes a value from a byte slice and returns the value plus unread byte count.
19pub fn decode_from_slice<T: CanonicalDecode>(bytes: &[u8]) -> Result<(T, usize), CodecError> {
20    let mut reader = SliceReader::new(bytes);
21    let value = T::decode(&mut reader)?;
22    Ok((value, reader.remaining()))
23}
24
25/// Decodes a value from a byte slice and rejects trailing bytes.
26pub fn decode_from_slice_exact<T: CanonicalDecode>(bytes: &[u8]) -> Result<T, CodecError> {
27    let (value, remaining) = decode_from_slice(bytes)?;
28    if remaining != 0 {
29        return Err(CodecError::trailing_bytes());
30    }
31    Ok(value)
32}