use alloc::borrow::Cow;
use alloc::vec::Vec;
use crate::error::{Result, SerialError};
use crate::traits::{Deserialize, Serialize};
use crate::varint;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Config {
pub max_alloc: usize,
pub max_total_alloc: Option<usize>,
pub max_depth: usize,
pub canonical: bool,
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
impl Config {
pub const DEFAULT_MAX_ALLOC: usize = 1 << 30;
pub const DEFAULT_MAX_DEPTH: usize = 128;
pub const NETWORK_MAX_ALLOC: usize = 16 << 20;
#[must_use]
pub const fn new() -> Self {
Self {
max_alloc: Self::DEFAULT_MAX_ALLOC,
max_total_alloc: None,
max_depth: Self::DEFAULT_MAX_DEPTH,
canonical: false,
}
}
#[must_use]
pub const fn network() -> Self {
Self {
max_alloc: Self::NETWORK_MAX_ALLOC,
max_total_alloc: Some(Self::NETWORK_MAX_ALLOC),
max_depth: Self::DEFAULT_MAX_DEPTH,
canonical: false,
}
}
#[inline]
#[must_use]
pub const fn total_alloc_limit(&self) -> usize {
match self.max_total_alloc {
Some(total) => total,
None => self.max_alloc,
}
}
#[must_use]
pub const fn with_max_alloc(mut self, max_alloc: usize) -> Self {
self.max_alloc = max_alloc;
self
}
#[must_use]
pub const fn with_max_total_alloc(mut self, max_total_alloc: usize) -> Self {
self.max_total_alloc = Some(max_total_alloc);
self
}
#[must_use]
pub const fn with_max_depth(mut self, max_depth: usize) -> Self {
self.max_depth = max_depth;
self
}
#[must_use]
pub const fn with_canonical(mut self, canonical: bool) -> Self {
self.canonical = canonical;
self
}
pub(crate) fn validate(self) -> Result<Self> {
if self.max_alloc == 0 {
return Err(SerialError::InvalidConfig {
reason: "max_alloc must be at least 1",
});
}
if self.max_total_alloc == Some(0) {
return Err(SerialError::InvalidConfig {
reason: "max_total_alloc must be at least 1",
});
}
if self.max_depth == 0 {
return Err(SerialError::InvalidConfig {
reason: "max_depth must be at least 1",
});
}
Ok(self)
}
}
pub(crate) const PREALLOC_BYTES: usize = 64 * 1024;
pub(crate) const STREAM_PREALLOC_BYTES: usize = 4 * 1024;
#[inline]
pub(crate) fn initial_capacity<T, D: Decode + ?Sized>(count: usize, decoder: &D) -> usize {
let per_element = core::mem::size_of::<T>().max(1);
match decoder.remaining_hint() {
Some(remaining) => count.min(PREALLOC_BYTES / per_element).min(remaining),
None => count.min(STREAM_PREALLOC_BYTES / per_element),
}
}
pub(crate) const FREE_ELEMENT_COST: usize = 64;
#[inline]
pub(crate) fn charge_elements<T, D: Decode + ?Sized>(decoder: &mut D, count: usize) -> Result<()> {
let size = core::mem::size_of::<T>();
if size == 0 || count == 0 {
return Ok(());
}
decoder.charge_unbacked(count.saturating_mul(size))
}
#[inline]
pub(crate) fn charge_boxed<T, D: Decode + ?Sized>(decoder: &mut D, extra: usize) -> Result<()> {
let size = core::mem::size_of::<T>();
if size == 0 && extra == 0 {
return Ok(());
}
decoder.charge_unbacked(size.saturating_add(extra))
}
#[inline]
pub(crate) fn decode_elements_counted<T, D, F>(
decoder: &mut D,
count: usize,
mut each: F,
) -> Result<()>
where
D: Decode + ?Sized,
F: FnMut(&mut D) -> Result<()>,
{
let Some(start) = decoder.bytes_read() else {
for _ in 0..count {
each(decoder)?;
}
return Ok(());
};
let per_element = core::mem::size_of::<T>().max(1);
let mut done = 0usize;
let mut charged = 0usize;
let mut stop = count.min((PREALLOC_BYTES / per_element).max(1));
loop {
for _ in done..stop {
each(decoder)?;
}
done = stop;
let read = decoder.bytes_read().unwrap_or(start).wrapping_sub(start);
if done as u64 > read {
charged = charge_free_elements(decoder, done, read, charged)?;
}
if done == count {
return Ok(());
}
stop = next_element_stop(decoder, done, count)?;
}
}
#[inline]
fn free_budget<D: Decode + ?Sized>(decoder: &D) -> usize {
decoder
.config()
.total_alloc_limit()
.saturating_sub(decoder.unbacked())
/ FREE_ELEMENT_COST
}
#[cold]
#[inline(never)]
fn charge_free_elements<D: Decode + ?Sized>(
decoder: &mut D,
done: usize,
read: u64,
charged: usize,
) -> Result<usize> {
let free = usize::try_from(done as u64 - read).unwrap_or(usize::MAX);
if free > charged {
decoder.charge_unbacked((free - charged).saturating_mul(FREE_ELEMENT_COST))?;
return Ok(free);
}
Ok(charged)
}
#[cold]
#[inline(never)]
fn next_element_stop<D: Decode + ?Sized>(decoder: &D, done: usize, count: usize) -> Result<usize> {
let free_budget = free_budget(decoder);
let left = count - done;
let room = match decoder.remaining_hint() {
Some(input) => {
let room = free_budget.saturating_add(input);
if left > room {
let total = decoder
.unbacked()
.saturating_add(left.saturating_mul(FREE_ELEMENT_COST));
return Err(unbacked_limit_error(total, Some(input)));
}
room
}
None => free_budget,
};
let chunk = done.min(room).max(1);
Ok(done.saturating_add(chunk).min(count))
}
#[cfg(feature = "serde")]
#[derive(Debug)]
pub(crate) struct FreeElements {
start: Option<u64>,
done: usize,
charged: usize,
}
#[cfg(feature = "serde")]
impl FreeElements {
#[inline]
pub(crate) fn new<D: Decode + ?Sized>(decoder: &D) -> Self {
Self {
start: decoder.bytes_read(),
done: 0,
charged: 0,
}
}
#[inline]
pub(crate) fn after_element<D: Decode + ?Sized>(
&mut self,
decoder: &mut D,
per_element: usize,
) -> Result<()> {
self.done += 1;
if per_element != 0 {
decoder.charge_unbacked(per_element)?;
}
let Some(start) = self.start else {
return Ok(());
};
let read = decoder.bytes_read().unwrap_or(start).wrapping_sub(start);
if self.done as u64 > read {
self.charged = charge_free_elements(decoder, self.done, read, self.charged)?;
}
Ok(())
}
}
#[cold]
pub(crate) fn unbacked_limit_error(total: usize, remaining: Option<usize>) -> SerialError {
SerialError::InvalidLength {
declared: total as u64,
remaining: remaining.unwrap_or(0),
}
}
#[inline]
pub(crate) fn guard_element_count<D: Decode + ?Sized>(declared: u64, decoder: &D) -> Result<usize> {
let max = decoder.max_alloc() as u64;
if declared > max {
return Err(SerialError::InvalidLength {
declared,
remaining: decoder.remaining_hint().unwrap_or(0),
});
}
usize::try_from(declared).map_err(|_| SerialError::IntegerOutOfRange)
}
#[inline]
pub(crate) fn guard_owned_bytes<D: Decode + ?Sized>(
declared: u64,
decoder: &mut D,
) -> Result<usize> {
let len = guard_element_count(declared, decoder)?;
if len != 0 {
decoder.charge_unbacked(len)?;
}
Ok(len)
}
pub trait Encode {
fn write_byte(&mut self, byte: u8) -> Result<()>;
fn write_bytes(&mut self, bytes: &[u8]) -> Result<()>;
#[inline]
fn reserve(&mut self, additional: usize) {
let _ = additional;
}
#[doc(hidden)]
#[inline]
fn in_memory_buffer(&mut self) -> Option<&mut Vec<u8>> {
None
}
#[inline]
fn write_varint_u64(&mut self, value: u64) -> Result<()> {
if value < 0x80 {
return self.write_byte(value as u8);
}
let mut buf = [0u8; varint::MAX_VARINT_LEN_U64];
let n = varint::write_u64(value, &mut buf);
self.write_bytes(&buf[..n])
}
#[inline]
fn write_varint_u128(&mut self, value: u128) -> Result<()> {
let mut buf = [0u8; varint::MAX_VARINT_LEN_U128];
let n = varint::write_u128(value, &mut buf);
self.write_bytes(&buf[..n])
}
}
pub trait Decode {
fn read_byte(&mut self) -> Result<u8>;
fn read_into(&mut self, out: &mut [u8]) -> Result<()>;
fn max_alloc(&self) -> usize;
#[inline]
fn remaining_hint(&self) -> Option<usize> {
None
}
#[inline]
fn config(&self) -> Config {
Config::new().with_max_alloc(self.max_alloc())
}
#[inline]
fn depth(&self) -> usize {
0
}
#[inline]
fn enter_nested(&mut self) -> Result<()> {
Ok(())
}
#[inline]
fn leave_nested(&mut self) {}
#[inline]
fn consumed(&self) -> Option<&[u8]> {
None
}
#[inline]
fn bytes_read(&self) -> Option<u64> {
self.consumed().map(|bytes| bytes.len() as u64)
}
#[inline]
fn unbacked(&self) -> usize {
0
}
#[inline]
fn charge_unbacked(&mut self, bytes: usize) -> Result<()> {
if bytes > self.config().total_alloc_limit() {
return Err(unbacked_limit_error(bytes, self.remaining_hint()));
}
Ok(())
}
#[inline]
fn reset_unbacked(&mut self) {}
fn read_byte_cow(&mut self, len: usize) -> Result<Cow<'_, [u8]>> {
read_bytes_incrementally(self, len).map(Cow::Owned)
}
#[inline]
fn read_varint_u64(&mut self) -> Result<u64> {
let first = self.read_byte()?;
if first < 0x80 {
return Ok(u64::from(first));
}
let mut result: u64 = u64::from(first & 0x7f);
let mut shift: u32 = 7;
for consumed in 2..=varint::MAX_VARINT_LEN_U64 {
let byte = self.read_byte()?;
if consumed == varint::MAX_VARINT_LEN_U64 && (byte & 0xfe) != 0 {
return Err(SerialError::VarintOverflow);
}
result |= u64::from(byte & 0x7f) << shift;
if byte & 0x80 == 0 {
if byte == 0 && self.config().canonical {
return Err(SerialError::NonCanonical { reason: "varint" });
}
return Ok(result);
}
shift += 7;
}
Err(SerialError::VarintOverflow)
}
#[inline]
fn read_varint_u128(&mut self) -> Result<u128> {
let mut result: u128 = 0;
let mut shift: u32 = 0;
for consumed in 1..=varint::MAX_VARINT_LEN_U128 {
let byte = self.read_byte()?;
if consumed == varint::MAX_VARINT_LEN_U128 && (byte & 0xfc) != 0 {
return Err(SerialError::VarintOverflow);
}
result |= u128::from(byte & 0x7f) << shift;
if byte & 0x80 == 0 {
if consumed > 1 && byte == 0 && self.config().canonical {
return Err(SerialError::NonCanonical { reason: "varint" });
}
return Ok(result);
}
shift += 7;
}
Err(SerialError::VarintOverflow)
}
#[inline]
fn read_length_prefixed(&mut self) -> Result<Vec<u8>> {
let declared = self.read_varint_u64()?;
let len = guard_owned_bytes(declared, self)?;
self.read_byte_cow(len).map(Cow::into_owned)
}
}
#[inline]
pub(crate) fn read_varint_u64_with<D: Decode + ?Sized, const CANONICAL: bool>(
decoder: &mut D,
) -> Result<u64> {
let first = decoder.read_byte()?;
if first < 0x80 {
return Ok(u64::from(first));
}
let mut result: u64 = u64::from(first & 0x7f);
let mut shift: u32 = 7;
for consumed in 2..=varint::MAX_VARINT_LEN_U64 {
let byte = decoder.read_byte()?;
if consumed == varint::MAX_VARINT_LEN_U64 && (byte & 0xfe) != 0 {
return Err(SerialError::VarintOverflow);
}
result |= u64::from(byte & 0x7f) << shift;
if byte & 0x80 == 0 {
if CANONICAL && byte == 0 {
return Err(SerialError::NonCanonical { reason: "varint" });
}
return Ok(result);
}
shift += 7;
}
Err(SerialError::VarintOverflow)
}
fn read_bytes_incrementally<D: Decode + ?Sized>(decoder: &mut D, len: usize) -> Result<Vec<u8>> {
if let Some(remaining) = decoder.remaining_hint() {
if len > remaining {
return Err(SerialError::UnexpectedEof {
needed: len,
remaining,
});
}
}
let mut filled = len.min(PREALLOC_BYTES);
let mut out: Vec<u8> = alloc::vec![0u8; filled];
decoder.read_into(&mut out)?;
while filled < len {
let target = len.min(filled.saturating_mul(2).max(PREALLOC_BYTES));
out.resize(target, 0);
decoder.read_into(&mut out[filled..target])?;
filled = target;
}
Ok(out)
}
#[derive(Debug, Default)]
pub struct Encoder {
out: Vec<u8>,
}
impl Encoder {
#[must_use]
pub fn new() -> Self {
Self { out: Vec::new() }
}
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self {
out: Vec::with_capacity(capacity),
}
}
#[must_use]
pub fn into_buffer(buffer: Vec<u8>) -> Self {
Self { out: buffer }
}
#[inline]
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.out
}
#[inline]
#[must_use]
pub fn into_inner(self) -> Vec<u8> {
self.out
}
#[must_use]
pub fn take(&mut self) -> Vec<u8> {
core::mem::take(&mut self.out)
}
#[inline]
pub fn write<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
value.serialize(self)
}
}
impl Encode for Encoder {
#[inline(always)]
fn write_byte(&mut self, byte: u8) -> Result<()> {
self.out.push(byte);
Ok(())
}
#[inline(always)]
fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
self.out.extend_from_slice(bytes);
Ok(())
}
#[inline(always)]
fn reserve(&mut self, additional: usize) {
self.out.reserve(additional);
}
#[inline]
fn in_memory_buffer(&mut self) -> Option<&mut Vec<u8>> {
Some(&mut self.out)
}
#[inline]
fn write_varint_u64(&mut self, value: u64) -> Result<()> {
if value < 0x80 {
self.out.push(value as u8);
return Ok(());
}
self.out.reserve(varint::MAX_VARINT_LEN_U64);
let mut n = value;
while n >= 0x80 {
self.out.push((n as u8) | 0x80);
n >>= 7;
}
self.out.push(n as u8);
Ok(())
}
#[inline]
fn write_varint_u128(&mut self, value: u128) -> Result<()> {
if value < 0x80 {
self.out.push(value as u8);
return Ok(());
}
self.out.reserve(varint::MAX_VARINT_LEN_U128);
let mut n = value;
while n >= 0x80 {
self.out.push((n as u8) | 0x80);
n >>= 7;
}
self.out.push(n as u8);
Ok(())
}
}
#[derive(Debug)]
pub struct Decoder<'a> {
input: &'a [u8],
pos: usize,
config: Config,
depth: usize,
unbacked: usize,
}
impl<'a> Decoder<'a> {
#[inline]
#[must_use]
pub fn new(bytes: &'a [u8]) -> Self {
Self {
input: bytes,
pos: 0,
config: Config::new(),
depth: 0,
unbacked: 0,
}
}
pub fn with_config(bytes: &'a [u8], config: Config) -> Result<Self> {
Ok(Self {
input: bytes,
pos: 0,
config: config.validate()?,
depth: 0,
unbacked: 0,
})
}
#[inline]
pub(crate) fn nested(bytes: &'a [u8], config: Config, depth: usize, unbacked: usize) -> Self {
Self {
input: bytes,
pos: 0,
config,
depth,
unbacked,
}
}
#[inline]
#[must_use]
pub fn config(&self) -> Config {
self.config
}
#[inline]
#[must_use]
pub fn position(&self) -> usize {
self.pos
}
#[inline]
#[must_use]
pub fn remaining(&self) -> usize {
self.input.len().saturating_sub(self.pos)
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.remaining() == 0
}
#[inline]
pub fn read<T: Deserialize>(&mut self) -> Result<T> {
if self.depth == 0 {
self.unbacked = 0;
}
T::deserialize(self)
}
#[inline]
pub fn read_length_prefixed_borrowed(&mut self) -> Result<&'a [u8]> {
let declared = <Self as Decode>::read_varint_u64(self)?;
let remaining = self.remaining();
let max = self.config.max_alloc as u64;
if declared > max || declared > remaining as u64 {
return Err(SerialError::InvalidLength {
declared,
remaining,
});
}
self.read_borrowed(declared as usize)
}
#[inline]
pub fn read_borrowed(&mut self, len: usize) -> Result<&'a [u8]> {
let remaining = self.remaining();
if len > remaining {
return Err(SerialError::UnexpectedEof {
needed: len,
remaining,
});
}
let start = self.pos;
let end = start + len;
let input: &'a [u8] = self.input;
self.pos = end;
Ok(&input[start..end])
}
}
impl Decode for Decoder<'_> {
#[inline]
fn read_byte(&mut self) -> Result<u8> {
match self.input.get(self.pos) {
Some(&b) => {
self.pos += 1;
Ok(b)
}
None => Err(SerialError::UnexpectedEof {
needed: 1,
remaining: 0,
}),
}
}
#[inline]
fn read_into(&mut self, out: &mut [u8]) -> Result<()> {
let n = out.len();
let remaining = self.remaining();
if n > remaining {
return Err(SerialError::UnexpectedEof {
needed: n,
remaining,
});
}
let start = self.pos;
let end = start + n;
out.copy_from_slice(&self.input[start..end]);
self.pos = end;
Ok(())
}
#[inline]
fn max_alloc(&self) -> usize {
self.config.max_alloc
}
#[inline]
fn remaining_hint(&self) -> Option<usize> {
Some(self.remaining())
}
#[inline]
fn config(&self) -> Config {
self.config
}
#[inline]
fn depth(&self) -> usize {
self.depth
}
#[inline]
fn enter_nested(&mut self) -> Result<()> {
if self.depth >= self.config.max_depth {
return Err(SerialError::DepthLimitExceeded {
max_depth: self.config.max_depth,
});
}
self.depth += 1;
Ok(())
}
#[inline]
fn leave_nested(&mut self) {
self.depth = self.depth.saturating_sub(1);
}
#[inline]
fn consumed(&self) -> Option<&[u8]> {
self.input.get(..self.pos)
}
#[inline]
fn bytes_read(&self) -> Option<u64> {
Some(self.pos as u64)
}
#[inline]
fn unbacked(&self) -> usize {
self.unbacked
}
#[inline]
fn charge_unbacked(&mut self, bytes: usize) -> Result<()> {
let total = self.unbacked.saturating_add(bytes);
if total > self.config.total_alloc_limit() {
return Err(unbacked_limit_error(total, Some(self.remaining())));
}
self.unbacked = total;
Ok(())
}
#[inline]
fn reset_unbacked(&mut self) {
self.unbacked = 0;
}
#[inline]
fn read_byte_cow(&mut self, len: usize) -> Result<Cow<'_, [u8]>> {
self.read_borrowed(len).map(Cow::Borrowed)
}
#[inline]
fn read_length_prefixed(&mut self) -> Result<Vec<u8>> {
let bytes = self.read_length_prefixed_borrowed()?;
if !bytes.is_empty() {
self.charge_unbacked(bytes.len())?;
}
Ok(bytes.to_vec())
}
}
#[inline]
pub fn encode<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>> {
let mut enc = Encoder::with_capacity(512);
value.serialize(&mut enc)?;
Ok(enc.into_inner())
}
#[inline]
pub fn peek_version(bytes: &[u8]) -> Result<u32> {
let mut dec = Decoder::new(bytes);
let v = dec.read_varint_u64()?;
u32::try_from(v).map_err(|_| SerialError::IntegerOutOfRange)
}
#[inline]
pub fn decode<T: Deserialize>(bytes: &[u8]) -> Result<T> {
let mut dec = Decoder::new(bytes);
let value = T::deserialize(&mut dec)?;
finish(&dec, value)
}
#[inline]
pub fn decode_with_config<T: Deserialize>(bytes: &[u8], config: Config) -> Result<T> {
let mut dec = Decoder::with_config(bytes, config)?;
let value = T::deserialize(&mut dec)?;
finish(&dec, value)
}
#[inline]
pub(crate) fn finish<T>(dec: &Decoder<'_>, value: T) -> Result<T> {
let remaining = dec.remaining();
if remaining != 0 {
return Err(SerialError::TrailingBytes { remaining });
}
Ok(value)
}
#[inline]
#[must_use]
pub const fn varint_len(value: u64) -> usize {
let bits = 64 - (value | 1).leading_zeros() as usize;
bits.div_ceil(7)
}
#[derive(Debug, Default)]
pub struct SizeCounter {
len: usize,
}
impl SizeCounter {
#[inline]
pub fn count(&self) -> usize {
self.len
}
}
impl Encode for SizeCounter {
#[inline]
fn write_byte(&mut self, _byte: u8) -> Result<()> {
self.len = self.len.saturating_add(1);
Ok(())
}
#[inline]
fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
self.len = self.len.saturating_add(bytes.len());
Ok(())
}
#[inline]
fn write_varint_u64(&mut self, value: u64) -> Result<()> {
self.len = self.len.saturating_add(varint_len(value));
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn config_default_has_one_gib_cap() {
let cfg = Config::default();
assert_eq!(cfg.max_alloc, 1 << 30);
}
#[test]
fn decoder_with_zero_cap_is_rejected() {
let cfg = Config::new().with_max_alloc(0);
let err = Decoder::with_config(&[], cfg).expect_err("zero cap is invalid");
assert!(matches!(err, SerialError::InvalidConfig { .. }));
}
#[test]
fn encoder_into_buffer_reuses_caller_vec() {
let mut buf = Vec::with_capacity(64);
buf.push(0xff);
let mut enc = Encoder::into_buffer(buf);
enc.write(&7_u64).unwrap();
let out = enc.into_inner();
assert_eq!(out[0], 0xff);
assert!(out.len() > 1);
}
#[test]
fn encoder_take_returns_buffer_and_resets() {
let mut enc = Encoder::new();
enc.write(&1_u64).unwrap();
let first = enc.take();
assert!(!first.is_empty());
assert!(enc.as_bytes().is_empty());
enc.write(&2_u64).unwrap();
let second = enc.take();
assert_eq!(second, [0x02]);
}
#[test]
fn decode_rejects_trailing_bytes() {
let mut bytes = encode(&7_u8).unwrap();
bytes.push(0xff);
let err = decode::<u8>(&bytes).expect_err("trailing bytes should fail");
assert!(matches!(err, SerialError::TrailingBytes { remaining: 1 }));
}
#[test]
fn decoder_read_past_end_returns_unexpected_eof() {
let mut dec = Decoder::new(&[0x01]);
let _: u8 = dec.read().unwrap();
let err = dec.read::<u8>().expect_err("past end should fail");
assert!(matches!(err, SerialError::UnexpectedEof { .. }));
}
#[test]
fn decoder_length_prefix_above_cap_is_rejected() {
let cfg = Config::new().with_max_alloc(4);
let bytes = [0x05, b'h', b'e', b'l', b'l', b'o'];
let mut dec = Decoder::with_config(&bytes, cfg).expect("non-zero cap");
let err = dec
.read_length_prefixed()
.expect_err("length > cap should fail");
assert!(matches!(
err,
SerialError::InvalidLength { declared: 5, .. }
));
}
#[test]
fn decoder_length_prefix_overflowing_remaining_is_rejected() {
let bytes = [0x10, b'a', b'b'];
let mut dec = Decoder::new(&bytes);
let err = dec
.read_length_prefixed()
.expect_err("length > remaining should fail");
assert!(matches!(err, SerialError::InvalidLength { .. }));
}
#[test]
fn decoder_position_advances_with_reads() {
let bytes = [0x01, 0x02, 0x03];
let mut dec = Decoder::new(&bytes);
assert_eq!(dec.position(), 0);
let _ = dec.read_byte().unwrap();
assert_eq!(dec.position(), 1);
let mut buf = [0u8; 2];
dec.read_into(&mut buf).unwrap();
assert_eq!(dec.position(), 3);
assert!(dec.is_empty());
}
#[test]
fn test_config_builders_and_validation() {
let cfg = Config::new()
.with_max_alloc(10)
.with_max_depth(3)
.with_canonical(true);
assert_eq!((cfg.max_alloc, cfg.max_depth, cfg.canonical), (10, 3, true));
assert_eq!(Config::default(), Config::new());
assert!(matches!(
Decoder::with_config(&[], Config::new().with_max_depth(0)),
Err(SerialError::InvalidConfig { .. })
));
}
#[test]
fn test_varint_len_matches_the_encoder_at_every_boundary() {
for shift in 0..64 {
for v in [
1u64 << shift,
(1u64 << shift) - 1,
(1u64 << shift).wrapping_add(1),
] {
let mut enc = Encoder::new();
enc.write_varint_u64(v).unwrap();
assert_eq!(varint_len(v), enc.as_bytes().len(), "{v}");
}
}
assert_eq!(varint_len(u64::MAX), 10);
}
struct Minimal<'a> {
bytes: &'a [u8],
reads: usize,
}
impl Decode for Minimal<'_> {
fn read_byte(&mut self) -> Result<u8> {
let (first, rest) = self.bytes.split_first().ok_or(SerialError::UnexpectedEof {
needed: 1,
remaining: 0,
})?;
self.bytes = rest;
Ok(*first)
}
fn read_into(&mut self, out: &mut [u8]) -> Result<()> {
if out.len() > self.bytes.len() {
return Err(SerialError::UnexpectedEof {
needed: out.len(),
remaining: self.bytes.len(),
});
}
self.reads += 1;
let (head, rest) = self.bytes.split_at(out.len());
out.copy_from_slice(head);
self.bytes = rest;
Ok(())
}
fn max_alloc(&self) -> usize {
1 << 30
}
}
#[test]
fn test_provided_methods_work_for_a_minimal_decoder() {
let big = alloc::vec![7u8; PREALLOC_BYTES * 3 + 5];
let mut encoded = encode(&big).unwrap();
encoded.extend(encode(&"tail").unwrap());
let mut dec = Minimal {
bytes: &encoded,
reads: 0,
};
let back: Vec<u8> = Deserialize::deserialize(&mut dec).unwrap();
assert_eq!(back, big);
assert!(dec.reads >= 2, "read in chunks, got {}", dec.reads);
let tail: alloc::string::String = Deserialize::deserialize(&mut dec).unwrap();
assert_eq!(tail, "tail");
assert_eq!(dec.depth(), 0);
assert!(dec.enter_nested().is_ok());
dec.leave_nested();
assert!(dec.consumed().is_none());
assert_eq!(dec.remaining_hint(), None);
assert_eq!(dec.config().max_alloc, 1 << 30);
}
struct CountingConfig<'a> {
inner: Decoder<'a>,
config_calls: core::cell::Cell<usize>,
}
impl Decode for CountingConfig<'_> {
fn read_byte(&mut self) -> Result<u8> {
self.inner.read_byte()
}
fn read_into(&mut self, out: &mut [u8]) -> Result<()> {
self.inner.read_into(out)
}
fn max_alloc(&self) -> usize {
self.inner.max_alloc()
}
fn config(&self) -> Config {
self.config_calls.set(self.config_calls.get() + 1);
self.inner.config()
}
}
#[test]
fn test_varint_decode_consults_config_only_for_overlong_encodings() {
let mut bytes = Vec::new();
for v in [0u64, 1, 127, 128, 300, 16_384, u32::MAX as u64, u64::MAX] {
bytes.extend(encode(&v).unwrap());
}
for strict in [false, true] {
let config = Config::new().with_canonical(strict);
let mut dec = CountingConfig {
inner: Decoder::with_config(&bytes, config).unwrap(),
config_calls: core::cell::Cell::new(0),
};
for _ in 0..8 {
let _ = dec.read_varint_u64().unwrap();
}
assert_eq!(dec.config_calls.get(), 0, "canonical = {strict}");
}
let overlong = [0x80, 0x00];
for (strict, expected) in [
(false, Ok(0)),
(true, Err(SerialError::NonCanonical { reason: "varint" })),
] {
let mut dec = CountingConfig {
inner: Decoder::with_config(&overlong, Config::new().with_canonical(strict))
.unwrap(),
config_calls: core::cell::Cell::new(0),
};
assert_eq!(dec.read_varint_u64(), expected);
assert_eq!(dec.config_calls.get(), 1);
}
}
#[test]
fn test_unbacked_charges_accumulate_and_stop_at_max_alloc() {
let cfg = Config::new().with_max_alloc(10);
let mut dec = Decoder::with_config(&[], cfg).unwrap();
dec.charge_unbacked(4).unwrap();
dec.charge_unbacked(6).unwrap();
assert_eq!(dec.unbacked(), 10);
assert!(matches!(
dec.charge_unbacked(1),
Err(SerialError::InvalidLength { declared: 11, .. })
));
assert_eq!(dec.unbacked(), 10, "a refused charge is not recorded");
let mut minimal = Minimal {
bytes: &[],
reads: 0,
};
minimal.charge_unbacked(1 << 30).unwrap();
minimal.charge_unbacked(1 << 30).unwrap();
assert!(minimal.charge_unbacked((1 << 30) + 1).is_err());
assert_eq!(minimal.unbacked(), 0);
assert_eq!(minimal.bytes_read(), None);
}
#[test]
fn test_canonical_mode_rejects_overlong_u128_varints() {
let strict = Config::new().with_canonical(true);
let mut dec = Decoder::with_config(&[0x80, 0x00], strict).unwrap();
assert_eq!(
dec.read_varint_u128(),
Err(SerialError::NonCanonical { reason: "varint" })
);
let mut dec = Decoder::new(&[0x80, 0x00]);
assert_eq!(dec.read_varint_u128(), Ok(0));
}
#[test]
fn test_read_borrowed_and_consumed() {
let mut dec = Decoder::new(&[1, 2, 3]);
assert_eq!(dec.read_borrowed(2).unwrap(), &[1, 2]);
assert_eq!(dec.consumed(), Some(&[1u8, 2][..]));
assert!(matches!(
dec.read_borrowed(2),
Err(SerialError::UnexpectedEof {
needed: 2,
remaining: 1
})
));
assert_eq!(dec.position(), 2, "a failed read does not move the cursor");
}
#[test]
fn test_size_counter_counts_without_storing() {
let mut counter = SizeCounter::default();
counter.write_bytes(&[0; 10]).unwrap();
counter.write_byte(1).unwrap();
counter.write_varint_u64(300).unwrap();
assert_eq!(counter.count(), 13);
}
#[test]
fn read_into_short_read_is_rejected() {
let mut dec = Decoder::new(&[0x01, 0x02]);
let mut buf = [0u8; 4];
let err = dec.read_into(&mut buf).expect_err("short read");
assert!(matches!(err, SerialError::UnexpectedEof { .. }));
}
}