pack_io/codec.rs
1//! The codec primitives: the [`Encode`] / [`Decode`] behaviour traits, the
2//! concrete in-memory [`Encoder`] / [`Decoder`] types, the [`Config`] struct,
3//! and the Tier-1 [`encode`] / [`decode`] free functions.
4//!
5//! ## Layering
6//!
7//! - **Tier 1** — the [`encode`] / [`decode`] free functions. One line each
8//! direction, no setup, no type parameters beyond the target type.
9//! - **Tier 2** — concrete encoder / decoder types. The in-memory pair
10//! ([`Encoder`] + [`Decoder`]) lives in this module; the streaming pair
11//! ([`crate::IoEncoder`] + [`crate::IoDecoder`]) lives in
12//! [`crate::io`] and is `std`-gated. All four implement the [`Encode`] /
13//! [`Decode`] behaviour traits, so [`Serialize`] / [`Deserialize`] impls
14//! work through any of them.
15//! - **Tier 3** — implementing the [`Serialize`] / [`Deserialize`] traits
16//! directly on your own types. Generic over `E: Encode` / `D: Decode`, so
17//! one impl works for both in-memory and streaming codecs.
18//!
19//! ## Safety contract for decoders
20//!
21//! Every method on [`Decode`] is total: it either returns the requested
22//! value (advancing the read cursor) or returns a [`SerialError`]. It never
23//! panics, never reads past the input, and never allocates more memory than
24//! the [`Config::max_alloc`] cap permits.
25
26use alloc::vec;
27use alloc::vec::Vec;
28
29use crate::error::{Result, SerialError};
30use crate::traits::{Deserialize, Serialize};
31use crate::varint;
32
33/// Configuration for a decode session.
34///
35/// At construction time the codec validates the configuration; an invalid
36/// config (currently: `max_alloc == 0`) is rejected before any bytes are read.
37/// Validation happens once, in [`Decoder::with_config`] /
38/// [`crate::IoDecoder::with_config`], not on every operation.
39///
40/// `Config` is `#[non_exhaustive]` so the project can add knobs in a MINOR
41/// release without breaking downstream code. Build instances with
42/// [`Config::new`] / [`Config::with_max_alloc`] or via [`Default`].
43///
44/// # Examples
45///
46/// ```
47/// use pack_io::{Config, Decoder};
48///
49/// // Refuse to allocate more than 16 KiB for any single length-prefixed
50/// // value (a `String`, a `Vec<u8>`, a collection element count, …).
51/// // Hostile producers that send multi-gigabyte length prefixes fail fast.
52/// let cfg = Config::new().with_max_alloc(16 * 1024);
53/// let dec = Decoder::with_config(&[], cfg).expect("non-zero cap");
54/// drop(dec);
55/// ```
56#[non_exhaustive]
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct Config {
59 /// Maximum number of bytes the decoder may allocate for any single
60 /// length-prefixed value (a `String`, a `Vec<u8>`, a collection element
61 /// count, …).
62 ///
63 /// The default is 1 GiB, which is enough that well-formed inputs are
64 /// never rejected on size, while still defending against the obvious
65 /// hostile-length-prefix DoS. Tighten this in any context that accepts
66 /// untrusted input from a low-budget producer.
67 pub max_alloc: usize,
68}
69
70impl Default for Config {
71 fn default() -> Self {
72 Self::new()
73 }
74}
75
76impl Config {
77 /// Default configuration: `max_alloc = 1 GiB`.
78 ///
79 /// 1 GiB is large enough to be irrelevant for well-formed inputs and
80 /// small enough to refuse the obvious `length = u64::MAX` attack before
81 /// allocating a single byte.
82 ///
83 /// # Examples
84 ///
85 /// ```
86 /// let cfg = pack_io::Config::new();
87 /// assert_eq!(cfg.max_alloc, 1 << 30);
88 /// ```
89 #[must_use]
90 pub const fn new() -> Self {
91 Self { max_alloc: 1 << 30 }
92 }
93
94 /// Replace `max_alloc` and return the updated config.
95 ///
96 /// # Examples
97 ///
98 /// ```
99 /// let cfg = pack_io::Config::new().with_max_alloc(4096);
100 /// assert_eq!(cfg.max_alloc, 4096);
101 /// ```
102 #[must_use]
103 pub const fn with_max_alloc(mut self, max_alloc: usize) -> Self {
104 self.max_alloc = max_alloc;
105 self
106 }
107
108 /// Validate the configuration. Returns an error if any field is
109 /// nonsensical.
110 pub(crate) fn validate(self) -> Result<Self> {
111 if self.max_alloc == 0 {
112 return Err(SerialError::InvalidLength {
113 declared: 0,
114 remaining: 0,
115 });
116 }
117 Ok(self)
118 }
119}
120
121// ---------------------------------------------------------------------------
122// Encode / Decode behaviour traits
123// ---------------------------------------------------------------------------
124
125/// Sink that a [`Serialize`] implementation writes its wire-format bytes
126/// into.
127///
128/// Implemented by every concrete encoder in the crate ([`Encoder`] for the
129/// in-memory case, [`crate::IoEncoder`] for `std::io::Write` streams). User
130/// code rarely implements `Encode` directly — `Serialize` impls are written
131/// generically over `E: Encode` so a single impl works for every encoder
132/// flavour.
133///
134/// # Examples
135///
136/// ```
137/// use pack_io::{Encode, Encoder, Result};
138///
139/// // A helper that writes a length-prefixed list of `u32`s into any encoder.
140/// fn write_u32_list<E: Encode>(enc: &mut E, items: &[u32]) -> Result<()> {
141/// enc.write_varint_u64(items.len() as u64)?;
142/// for item in items {
143/// enc.write_varint_u64(u64::from(*item))?;
144/// }
145/// Ok(())
146/// }
147///
148/// let mut enc = Encoder::new();
149/// write_u32_list(&mut enc, &[1, 2, 3]).unwrap();
150/// ```
151pub trait Encode {
152 /// Append a single byte.
153 ///
154 /// # Errors
155 ///
156 /// Returns the encoder's underlying error variant (I/O failure for
157 /// streaming encoders; never errors for the in-memory [`Encoder`]).
158 fn write_byte(&mut self, byte: u8) -> Result<()>;
159
160 /// Append a slice of bytes.
161 ///
162 /// # Errors
163 ///
164 /// Same as [`Encode::write_byte`].
165 fn write_bytes(&mut self, bytes: &[u8]) -> Result<()>;
166
167 /// Hint that the caller is about to write `additional` more bytes.
168 ///
169 /// In-memory encoders MAY pre-allocate the requested capacity to avoid
170 /// intermediate `Vec` growth. Streaming encoders typically ignore the
171 /// hint. The default implementation is a no-op.
172 #[inline]
173 fn reserve(&mut self, additional: usize) {
174 let _ = additional;
175 }
176
177 /// Append a `u64` as an unsigned LEB128 varint (1–10 bytes).
178 ///
179 /// # Errors
180 ///
181 /// Same as [`Encode::write_bytes`].
182 #[inline]
183 fn write_varint_u64(&mut self, value: u64) -> Result<()> {
184 // Fast path for the overwhelmingly common case: value fits in a
185 // single byte. Skips the stack buffer + write_bytes round-trip.
186 if value < 0x80 {
187 return self.write_byte(value as u8);
188 }
189 let mut buf = [0u8; varint::MAX_VARINT_LEN_U64];
190 let n = varint::write_u64(value, &mut buf);
191 self.write_bytes(&buf[..n])
192 }
193
194 /// Append a `u128` as an unsigned LEB128 varint (1–19 bytes).
195 ///
196 /// # Errors
197 ///
198 /// Same as [`Encode::write_bytes`].
199 #[inline]
200 fn write_varint_u128(&mut self, value: u128) -> Result<()> {
201 let mut buf = [0u8; varint::MAX_VARINT_LEN_U128];
202 let n = varint::write_u128(value, &mut buf);
203 self.write_bytes(&buf[..n])
204 }
205}
206
207/// Source that a [`Deserialize`] implementation reads its wire-format bytes
208/// from.
209///
210/// Implemented by every concrete decoder in the crate ([`Decoder`] for the
211/// in-memory case, [`crate::IoDecoder`] for `std::io::Read` streams). User
212/// code rarely implements `Decode` directly — `Deserialize` impls are
213/// written generically over `D: Decode`.
214///
215/// All methods are **total**: on any byte sequence they either succeed
216/// (advancing the cursor) or return a [`SerialError`]. They never panic,
217/// never read past the input, and never allocate more memory than
218/// [`Decode::max_alloc`] permits.
219pub trait Decode {
220 /// Read the next byte, advancing the cursor.
221 ///
222 /// # Errors
223 ///
224 /// Returns [`SerialError::UnexpectedEof`] if the input is exhausted.
225 /// Streaming decoders MAY return an I/O-flavoured error variant.
226 fn read_byte(&mut self) -> Result<u8>;
227
228 /// Fill `out` with exactly `out.len()` bytes, advancing the cursor.
229 ///
230 /// # Errors
231 ///
232 /// Returns [`SerialError::UnexpectedEof`] on short read.
233 fn read_into(&mut self, out: &mut [u8]) -> Result<()>;
234
235 /// Maximum number of bytes the decoder will allocate for a single
236 /// length-prefixed value. Mirrors [`Config::max_alloc`].
237 fn max_alloc(&self) -> usize;
238
239 /// Read a LEB128 varint as a `u64`.
240 ///
241 /// # Errors
242 ///
243 /// Returns [`SerialError::VarintOverflow`] for an overlong encoding,
244 /// or [`SerialError::UnexpectedEof`] for a truncated one.
245 #[inline]
246 fn read_varint_u64(&mut self) -> Result<u64> {
247 // Fast path for single-byte varints (values 0..=127, the
248 // overwhelmingly common case for length prefixes and small ints).
249 let first = self.read_byte()?;
250 if first < 0x80 {
251 return Ok(u64::from(first));
252 }
253 let mut result: u64 = u64::from(first & 0x7f);
254 let mut shift: u32 = 7;
255 for consumed in 2..=varint::MAX_VARINT_LEN_U64 {
256 let byte = self.read_byte()?;
257 // The 10th byte may only set bit 0 — anything else overflows u64.
258 if consumed == varint::MAX_VARINT_LEN_U64 && (byte & 0xfe) != 0 {
259 return Err(SerialError::VarintOverflow);
260 }
261 result |= u64::from(byte & 0x7f) << shift;
262 if byte & 0x80 == 0 {
263 return Ok(result);
264 }
265 shift += 7;
266 }
267 Err(SerialError::VarintOverflow)
268 }
269
270 /// Read a LEB128 varint as a `u128`.
271 ///
272 /// # Errors
273 ///
274 /// See [`Decode::read_varint_u64`].
275 #[inline]
276 fn read_varint_u128(&mut self) -> Result<u128> {
277 let mut result: u128 = 0;
278 let mut shift: u32 = 0;
279 for consumed in 1..=varint::MAX_VARINT_LEN_U128 {
280 let byte = self.read_byte()?;
281 // The 19th byte may only set the low two bits.
282 if consumed == varint::MAX_VARINT_LEN_U128 && (byte & 0xfc) != 0 {
283 return Err(SerialError::VarintOverflow);
284 }
285 result |= u128::from(byte & 0x7f) << shift;
286 if byte & 0x80 == 0 {
287 return Ok(result);
288 }
289 shift += 7;
290 }
291 Err(SerialError::VarintOverflow)
292 }
293
294 /// Read a length-prefixed byte run, allocating a fresh `Vec<u8>`.
295 ///
296 /// The length is read as a varint, validated against
297 /// [`Decode::max_alloc`], then the corresponding number of bytes is
298 /// read from the underlying source.
299 ///
300 /// # Errors
301 ///
302 /// - [`SerialError::InvalidLength`] if the prefix exceeds `max_alloc`.
303 /// - [`SerialError::UnexpectedEof`] if the source runs out before the
304 /// declared length is satisfied.
305 #[inline]
306 fn read_length_prefixed(&mut self) -> Result<Vec<u8>> {
307 let declared = self.read_varint_u64()?;
308 let max = self.max_alloc() as u64;
309 if declared > max {
310 return Err(SerialError::InvalidLength {
311 declared,
312 remaining: 0,
313 });
314 }
315 let len = declared as usize;
316 let mut buf = vec![0u8; len];
317 self.read_into(&mut buf)?;
318 Ok(buf)
319 }
320}
321
322// ---------------------------------------------------------------------------
323// In-memory Encoder
324// ---------------------------------------------------------------------------
325
326/// In-memory encoder. Writes into an owned `Vec<u8>`; the buffer can be
327/// reused across encodes by calling [`Encoder::take`] to swap it out.
328///
329/// Implements [`Encode`], so [`Serialize`] impls written generically over
330/// `E: Encode` work directly through it.
331///
332/// # Examples
333///
334/// ```
335/// use pack_io::Encoder;
336///
337/// let mut enc = Encoder::new();
338/// enc.write(&7_u64).unwrap();
339/// enc.write(&"hello").unwrap();
340/// let bytes = enc.into_inner();
341/// assert!(bytes.len() > 0);
342/// ```
343#[derive(Debug, Default)]
344pub struct Encoder {
345 out: Vec<u8>,
346}
347
348impl Encoder {
349 /// Construct an encoder with an empty output buffer.
350 ///
351 /// # Examples
352 ///
353 /// ```
354 /// let enc = pack_io::Encoder::new();
355 /// assert!(enc.as_bytes().is_empty());
356 /// ```
357 #[must_use]
358 pub fn new() -> Self {
359 Self { out: Vec::new() }
360 }
361
362 /// Construct an encoder backed by `buffer`. The encoder appends to the
363 /// buffer rather than allocating its own — callers that re-use a single
364 /// `Vec<u8>` across many encodes avoid the per-call allocation.
365 ///
366 /// # Examples
367 ///
368 /// ```
369 /// use pack_io::Encoder;
370 ///
371 /// let buf = Vec::with_capacity(64);
372 /// let mut enc = Encoder::into_buffer(buf);
373 /// enc.write(&42_u64).unwrap();
374 /// let buf = enc.into_inner();
375 /// assert!(!buf.is_empty());
376 /// ```
377 #[must_use]
378 pub fn into_buffer(buffer: Vec<u8>) -> Self {
379 Self { out: buffer }
380 }
381
382 /// Borrow the encoded bytes accumulated so far.
383 #[inline]
384 #[must_use]
385 pub fn as_bytes(&self) -> &[u8] {
386 &self.out
387 }
388
389 /// Consume the encoder and return its underlying buffer.
390 #[inline]
391 #[must_use]
392 pub fn into_inner(self) -> Vec<u8> {
393 self.out
394 }
395
396 /// Swap the encoder's buffer with a fresh empty one, returning the bytes
397 /// written so far. Useful for "encode then send" loops that want to
398 /// re-use the encoder.
399 #[must_use]
400 pub fn take(&mut self) -> Vec<u8> {
401 core::mem::take(&mut self.out)
402 }
403
404 /// Encode `value`, appending its bytes to the internal buffer.
405 ///
406 /// # Errors
407 ///
408 /// Propagates any error returned by the type's [`Serialize`]
409 /// implementation. Primitive impls in this crate never error on an
410 /// in-memory encoder.
411 #[inline]
412 pub fn write<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
413 value.serialize(self)
414 }
415}
416
417impl Encode for Encoder {
418 #[inline]
419 fn write_byte(&mut self, byte: u8) -> Result<()> {
420 self.out.push(byte);
421 Ok(())
422 }
423
424 #[inline]
425 fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
426 self.out.extend_from_slice(bytes);
427 Ok(())
428 }
429
430 #[inline]
431 fn reserve(&mut self, additional: usize) {
432 self.out.reserve(additional);
433 }
434}
435
436// ---------------------------------------------------------------------------
437// In-memory Decoder
438// ---------------------------------------------------------------------------
439
440/// In-memory decoder. Borrows from an input slice and advances a position
441/// pointer as values are read. Bounds-checked on every operation.
442///
443/// Implements [`Decode`], so [`Deserialize`] impls written generically over
444/// `D: Decode` work directly through it.
445///
446/// # Examples
447///
448/// ```
449/// use pack_io::{Encoder, Decoder};
450///
451/// let mut enc = Encoder::new();
452/// enc.write(&7_u64).unwrap();
453/// enc.write(&true).unwrap();
454/// let bytes = enc.into_inner();
455///
456/// let mut dec = Decoder::new(&bytes);
457/// let n: u64 = dec.read().unwrap();
458/// let b: bool = dec.read().unwrap();
459/// assert_eq!(n, 7);
460/// assert!(b);
461/// assert!(dec.is_empty());
462/// ```
463#[derive(Debug)]
464pub struct Decoder<'a> {
465 input: &'a [u8],
466 pos: usize,
467 config: Config,
468}
469
470impl<'a> Decoder<'a> {
471 /// Construct a decoder over `bytes`.
472 #[inline]
473 #[must_use]
474 pub fn new(bytes: &'a [u8]) -> Self {
475 Self {
476 input: bytes,
477 pos: 0,
478 config: Config::default(),
479 }
480 }
481
482 /// Construct a decoder with the supplied configuration.
483 ///
484 /// # Errors
485 ///
486 /// Returns [`SerialError::InvalidLength`] if `config.max_alloc == 0`.
487 pub fn with_config(bytes: &'a [u8], config: Config) -> Result<Self> {
488 Ok(Self {
489 input: bytes,
490 pos: 0,
491 config: config.validate()?,
492 })
493 }
494
495 /// Bytes consumed so far from the start of the input.
496 #[inline]
497 #[must_use]
498 pub fn position(&self) -> usize {
499 self.pos
500 }
501
502 /// Number of bytes remaining in the input.
503 #[inline]
504 #[must_use]
505 pub fn remaining(&self) -> usize {
506 self.input.len().saturating_sub(self.pos)
507 }
508
509 /// True when there are no more bytes to read.
510 #[inline]
511 #[must_use]
512 pub fn is_empty(&self) -> bool {
513 self.remaining() == 0
514 }
515
516 /// Decode a value of type `T` from the current position.
517 ///
518 /// # Errors
519 ///
520 /// Returns any [`SerialError`] surfaced by `T::deserialize`.
521 #[inline]
522 pub fn read<T: Deserialize>(&mut self) -> Result<T> {
523 T::deserialize(self)
524 }
525
526 /// Read a length-prefixed byte run as a **borrowed** slice of the
527 /// underlying input — no allocation, no copy.
528 ///
529 /// The borrowed slice has the same lifetime `'a` as the decoder's
530 /// input buffer, which lets caller-side `&'a str` / `&'a [u8]` decode
531 /// paths return a borrow directly into that buffer. This is the seam
532 /// the zero-copy [`crate::DeserializeView`] surface plugs into for
533 /// `&'a str` and `&'a [u8]`.
534 ///
535 /// # Errors
536 ///
537 /// - [`SerialError::InvalidLength`] if the prefix exceeds the
538 /// configured `max_alloc`, OR exceeds the remaining input.
539 /// - [`SerialError::UnexpectedEof`] is folded into `InvalidLength` for
540 /// this method, since the buffer length is known up front and a
541 /// declared length running off the end is logically a length-prefix
542 /// error, not a streaming EOF.
543 #[inline]
544 pub fn read_length_prefixed_borrowed(&mut self) -> Result<&'a [u8]> {
545 let declared = <Self as Decode>::read_varint_u64(self)?;
546 let max = self.config.max_alloc as u64;
547 if declared > max {
548 return Err(SerialError::InvalidLength {
549 declared,
550 remaining: self.remaining(),
551 });
552 }
553 let len = declared as usize;
554 let remaining = self.remaining();
555 if len > remaining {
556 return Err(SerialError::InvalidLength {
557 declared,
558 remaining,
559 });
560 }
561 let start = self.pos;
562 let end = start + len;
563 let slice = &self.input[start..end];
564 self.pos = end;
565 Ok(slice)
566 }
567}
568
569impl Decode for Decoder<'_> {
570 #[inline]
571 fn read_byte(&mut self) -> Result<u8> {
572 match self.input.get(self.pos) {
573 Some(&b) => {
574 self.pos += 1;
575 Ok(b)
576 }
577 None => Err(SerialError::UnexpectedEof {
578 needed: 1,
579 remaining: 0,
580 }),
581 }
582 }
583
584 #[inline]
585 fn read_into(&mut self, out: &mut [u8]) -> Result<()> {
586 let n = out.len();
587 let remaining = self.remaining();
588 if n > remaining {
589 return Err(SerialError::UnexpectedEof {
590 needed: n,
591 remaining,
592 });
593 }
594 let start = self.pos;
595 let end = start + n;
596 out.copy_from_slice(&self.input[start..end]);
597 self.pos = end;
598 Ok(())
599 }
600
601 #[inline]
602 fn max_alloc(&self) -> usize {
603 self.config.max_alloc
604 }
605
606 /// In-memory specialisation: validates length against the actual buffer
607 /// length too, not just `max_alloc`. Catches truncated inputs without
608 /// allocating.
609 #[inline]
610 fn read_length_prefixed(&mut self) -> Result<Vec<u8>> {
611 let declared = self.read_varint_u64()?;
612 let max = self.config.max_alloc as u64;
613 if declared > max {
614 return Err(SerialError::InvalidLength {
615 declared,
616 remaining: self.remaining(),
617 });
618 }
619 let len = declared as usize;
620 let remaining = self.remaining();
621 if len > remaining {
622 return Err(SerialError::InvalidLength {
623 declared,
624 remaining,
625 });
626 }
627 let start = self.pos;
628 let end = start + len;
629 let slice = &self.input[start..end];
630 self.pos = end;
631 Ok(slice.to_vec())
632 }
633}
634
635// ---------------------------------------------------------------------------
636// Tier-1 free functions
637// ---------------------------------------------------------------------------
638
639/// Encode `value` into a freshly allocated `Vec<u8>`.
640///
641/// This is the **Tier-1** entry point — the one-line surface for the common
642/// case. Allocates one buffer sized to fit the encoded value.
643///
644/// # Examples
645///
646/// ```
647/// let bytes = pack_io::encode(&42_u64).unwrap();
648/// let back: u64 = pack_io::decode(&bytes).unwrap();
649/// assert_eq!(back, 42);
650/// ```
651///
652/// # Errors
653///
654/// Propagates any error returned by the type's [`Serialize`] implementation.
655/// The built-in primitive and collection impls never error on an in-memory
656/// encoder.
657#[inline]
658pub fn encode<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>> {
659 let mut enc = Encoder::new();
660 value.serialize(&mut enc)?;
661 Ok(enc.into_inner())
662}
663
664/// Peek the schema version of a payload produced by a `#[pack_io(version = N)]`
665/// type without consuming the buffer.
666///
667/// Reads only the leading varint and returns it as `u32`, leaving the
668/// caller free to dispatch decode to the right `T` based on what they find.
669/// On a non-versioned payload (no `#[pack_io(version = N)]` on the type)
670/// this returns whatever the first varint of the encoding happens to be —
671/// callers should only use it on payloads they know are versioned.
672///
673/// # Examples
674///
675/// ```
676/// # #[cfg(feature = "derive")] {
677/// use pack_io::{encode, peek_version, Serialize, Deserialize};
678///
679/// #[derive(Serialize, Deserialize)]
680/// #[pack_io(version = 2)]
681/// struct Msg { id: u64 }
682///
683/// let bytes = encode(&Msg { id: 7 }).unwrap();
684/// assert_eq!(peek_version(&bytes).unwrap(), 2);
685/// # }
686/// ```
687///
688/// # Errors
689///
690/// - [`SerialError::UnexpectedEof`] if `bytes` is empty or the leading
691/// varint is truncated.
692/// - [`SerialError::VarintOverflow`] / [`SerialError::IntegerOutOfRange`]
693/// if the leading varint does not fit in `u32`.
694#[inline]
695pub fn peek_version(bytes: &[u8]) -> Result<u32> {
696 let mut dec = Decoder::new(bytes);
697 let v = dec.read_varint_u64()?;
698 u32::try_from(v).map_err(|_| SerialError::IntegerOutOfRange)
699}
700
701/// Decode a value of type `T` from `bytes`, requiring the input to be fully
702/// consumed.
703///
704/// This is the **Tier-1** entry point — the one-line surface for the common
705/// case. After the value has been read, the decoder checks that no bytes
706/// remain; trailing input is reported as [`SerialError::TrailingBytes`].
707/// Callers that want to read several values from a single buffer should use
708/// [`Decoder`] directly.
709///
710/// # Examples
711///
712/// ```
713/// let bytes = pack_io::encode(&"hello").unwrap();
714/// let back: String = pack_io::decode(&bytes).unwrap();
715/// assert_eq!(back, "hello");
716/// ```
717///
718/// # Errors
719///
720/// - Returns [`SerialError::TrailingBytes`] when extra bytes follow the value.
721/// - Propagates any [`SerialError`] from the type's [`Deserialize`] impl.
722#[inline]
723pub fn decode<T: Deserialize>(bytes: &[u8]) -> Result<T> {
724 let mut dec = Decoder::new(bytes);
725 let value = T::deserialize(&mut dec)?;
726 let remaining = dec.remaining();
727 if remaining != 0 {
728 return Err(SerialError::TrailingBytes { remaining });
729 }
730 Ok(value)
731}
732
733#[cfg(test)]
734mod tests {
735 use super::*;
736
737 #[test]
738 fn config_default_has_one_gib_cap() {
739 let cfg = Config::default();
740 assert_eq!(cfg.max_alloc, 1 << 30);
741 }
742
743 #[test]
744 fn decoder_with_zero_cap_is_rejected() {
745 let cfg = Config::new().with_max_alloc(0);
746 let err = Decoder::with_config(&[], cfg).expect_err("zero cap is invalid");
747 assert!(matches!(err, SerialError::InvalidLength { .. }));
748 }
749
750 #[test]
751 fn encoder_into_buffer_reuses_caller_vec() {
752 let mut buf = Vec::with_capacity(64);
753 buf.push(0xff);
754 let mut enc = Encoder::into_buffer(buf);
755 enc.write(&7_u64).unwrap();
756 let out = enc.into_inner();
757 assert_eq!(out[0], 0xff);
758 assert!(out.len() > 1);
759 }
760
761 #[test]
762 fn encoder_take_returns_buffer_and_resets() {
763 let mut enc = Encoder::new();
764 enc.write(&1_u64).unwrap();
765 let first = enc.take();
766 assert!(!first.is_empty());
767 assert!(enc.as_bytes().is_empty());
768
769 enc.write(&2_u64).unwrap();
770 let second = enc.take();
771 assert_eq!(second, [0x02]);
772 }
773
774 #[test]
775 fn decode_rejects_trailing_bytes() {
776 let mut bytes = encode(&7_u8).unwrap();
777 bytes.push(0xff);
778 let err = decode::<u8>(&bytes).expect_err("trailing bytes should fail");
779 assert!(matches!(err, SerialError::TrailingBytes { remaining: 1 }));
780 }
781
782 #[test]
783 fn decoder_read_past_end_returns_unexpected_eof() {
784 let mut dec = Decoder::new(&[0x01]);
785 let _: u8 = dec.read().unwrap();
786 let err = dec.read::<u8>().expect_err("past end should fail");
787 assert!(matches!(err, SerialError::UnexpectedEof { .. }));
788 }
789
790 #[test]
791 fn decoder_length_prefix_above_cap_is_rejected() {
792 let cfg = Config::new().with_max_alloc(4);
793 let bytes = [0x05, b'h', b'e', b'l', b'l', b'o'];
794 let mut dec = Decoder::with_config(&bytes, cfg).expect("non-zero cap");
795 let err = dec
796 .read_length_prefixed()
797 .expect_err("length > cap should fail");
798 assert!(matches!(
799 err,
800 SerialError::InvalidLength { declared: 5, .. }
801 ));
802 }
803
804 #[test]
805 fn decoder_length_prefix_overflowing_remaining_is_rejected() {
806 let bytes = [0x10, b'a', b'b'];
807 let mut dec = Decoder::new(&bytes);
808 let err = dec
809 .read_length_prefixed()
810 .expect_err("length > remaining should fail");
811 assert!(matches!(err, SerialError::InvalidLength { .. }));
812 }
813
814 #[test]
815 fn decoder_position_advances_with_reads() {
816 let bytes = [0x01, 0x02, 0x03];
817 let mut dec = Decoder::new(&bytes);
818 assert_eq!(dec.position(), 0);
819 let _ = dec.read_byte().unwrap();
820 assert_eq!(dec.position(), 1);
821 let mut buf = [0u8; 2];
822 dec.read_into(&mut buf).unwrap();
823 assert_eq!(dec.position(), 3);
824 assert!(dec.is_empty());
825 }
826
827 #[test]
828 fn read_into_short_read_is_rejected() {
829 let mut dec = Decoder::new(&[0x01, 0x02]);
830 let mut buf = [0u8; 4];
831 let err = dec.read_into(&mut buf).expect_err("short read");
832 assert!(matches!(err, SerialError::UnexpectedEof { .. }));
833 }
834}