pack_io/io.rs
1//! `std::io::Read` / `std::io::Write` integration: the streaming Tier-2
2//! encoder and decoder pair, plus convenience free functions.
3//!
4//! This module is gated on the `std` feature (on by default). With `std` off,
5//! the crate compiles for `no_std` targets using `core` + `alloc` only and
6//! none of this module is reachable.
7//!
8//! ## When to use which entry point
9//!
10//! - For one-shot send / receive of a single value, prefer [`encode_into`] /
11//! [`decode_from`]: they take any `Write` / `Read` and handle the
12//! buffering.
13//! - For interleaved writes / reads across many values without per-value
14//! allocation, instantiate an [`IoEncoder`] / [`IoDecoder`] and call
15//! `write` / `read` repeatedly.
16//!
17//! ## Errors
18//!
19//! Both directions surface I/O failure through the codec's
20//! [`crate::SerialError`] type via [`SerialError::Io`]. The `Io` variant
21//! captures `std::io::ErrorKind` and a message string — enough to surface
22//! the original cause without taking on a non-`Clone` payload.
23
24use std::io::{Read, Write};
25
26use crate::codec::{Config, Decode, Encode};
27use crate::error::{Result, SerialError};
28use crate::traits::{Deserialize, Serialize};
29
30/// Streaming encoder that writes directly into any [`Write`]-shaped sink.
31///
32/// Each [`IoEncoder::write`] call calls into the underlying writer for the
33/// bytes the type produces. The encoder does **not** buffer; if you wrap a
34/// raw socket / file, wrap it in a [`std::io::BufWriter`] first.
35///
36/// # Examples
37///
38/// ```
39/// use pack_io::IoEncoder;
40///
41/// let mut sink: Vec<u8> = Vec::new();
42/// let mut enc = IoEncoder::new(&mut sink);
43/// enc.write(&42_u64).unwrap();
44/// enc.write(&"hello").unwrap();
45/// assert!(!sink.is_empty());
46/// ```
47#[derive(Debug)]
48pub struct IoEncoder<W: Write> {
49 writer: W,
50}
51
52impl<W: Write> IoEncoder<W> {
53 /// Wrap `writer` in an encoder.
54 ///
55 /// The encoder does not buffer; wrap raw sockets / files in a
56 /// [`std::io::BufWriter`] first if syscall amplification is a concern.
57 ///
58 /// # Examples
59 ///
60 /// ```
61 /// use pack_io::IoEncoder;
62 ///
63 /// let mut sink: Vec<u8> = Vec::new();
64 /// let _enc = IoEncoder::new(&mut sink);
65 /// ```
66 #[must_use]
67 pub fn new(writer: W) -> Self {
68 Self { writer }
69 }
70
71 /// Borrow the underlying writer.
72 ///
73 /// # Examples
74 ///
75 /// ```
76 /// use pack_io::IoEncoder;
77 ///
78 /// let mut sink: Vec<u8> = Vec::new();
79 /// let enc = IoEncoder::new(&mut sink);
80 /// let _: &&mut Vec<u8> = &enc.writer();
81 /// ```
82 #[must_use]
83 pub fn writer(&self) -> &W {
84 &self.writer
85 }
86
87 /// Borrow the underlying writer mutably.
88 ///
89 /// Useful when downstream code needs `&mut W` to call writer-specific
90 /// methods (e.g. `flush`) without consuming the encoder.
91 ///
92 /// # Examples
93 ///
94 /// ```
95 /// use std::io::{BufWriter, Write};
96 /// use pack_io::IoEncoder;
97 ///
98 /// let mut sink: Vec<u8> = Vec::new();
99 /// let buffered = BufWriter::new(&mut sink);
100 /// let mut enc = IoEncoder::new(buffered);
101 /// enc.write(&7_u64).unwrap();
102 /// enc.writer_mut().flush().unwrap();
103 /// ```
104 #[must_use]
105 pub fn writer_mut(&mut self) -> &mut W {
106 &mut self.writer
107 }
108
109 /// Consume the encoder and return the underlying writer.
110 ///
111 /// # Examples
112 ///
113 /// ```
114 /// use pack_io::IoEncoder;
115 ///
116 /// let sink: Vec<u8> = Vec::new();
117 /// let mut enc = IoEncoder::new(sink);
118 /// enc.write(&42_u64).unwrap();
119 /// let written: Vec<u8> = enc.into_inner();
120 /// assert_eq!(written, &[0x2a]);
121 /// ```
122 #[must_use]
123 pub fn into_inner(self) -> W {
124 self.writer
125 }
126
127 /// Encode `value` straight into the underlying writer.
128 ///
129 /// # Errors
130 ///
131 /// - Propagates any [`crate::SerialError`] from the type's [`Serialize`].
132 /// - Maps any `std::io::Error` from the writer into [`SerialError::Io`].
133 #[inline]
134 pub fn write<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
135 value.serialize(self)
136 }
137}
138
139impl<W: Write> Encode for IoEncoder<W> {
140 #[inline]
141 fn write_byte(&mut self, byte: u8) -> Result<()> {
142 self.writer.write_all(&[byte]).map_err(map_io_error)
143 }
144
145 #[inline]
146 fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
147 self.writer.write_all(bytes).map_err(map_io_error)
148 }
149}
150
151/// Streaming decoder that reads directly from any [`Read`]-shaped source.
152///
153/// Each [`IoDecoder::read`] call may issue many small reads against the
154/// underlying source. Wrap raw sockets / files in [`std::io::BufReader`]
155/// first if read-syscall amplification is a concern.
156///
157/// # Examples
158///
159/// ```
160/// use pack_io::{IoEncoder, IoDecoder};
161/// use std::io::Cursor;
162///
163/// let mut buf: Vec<u8> = Vec::new();
164/// {
165/// let mut enc = IoEncoder::new(&mut buf);
166/// enc.write(&42_u64).unwrap();
167/// enc.write(&"hi").unwrap();
168/// }
169///
170/// let mut dec = IoDecoder::new(Cursor::new(buf));
171/// let n: u64 = dec.read().unwrap();
172/// let s: String = dec.read().unwrap();
173/// assert_eq!((n, s.as_str()), (42, "hi"));
174/// ```
175#[derive(Debug)]
176pub struct IoDecoder<R: Read> {
177 reader: R,
178 config: Config,
179 depth: usize,
180 /// Bytes consumed from `reader` so far (see `Decode::bytes_read`).
181 read: u64,
182 /// Running `Decode::unbacked` total.
183 unbacked: usize,
184}
185
186impl<R: Read> IoDecoder<R> {
187 /// Wrap `reader` with the default [`Config`] (1 GiB `max_alloc`,
188 /// depth limit 128).
189 ///
190 /// For tighter allocation caps on untrusted input, use
191 /// [`IoDecoder::with_config`] instead. Whatever the cap, the decoder
192 /// only grows a buffer as bytes actually arrive from `reader`, so a
193 /// large declared length on a short or stalled stream does not reserve
194 /// memory up front.
195 ///
196 /// # Examples
197 ///
198 /// ```
199 /// use std::io::Cursor;
200 /// use pack_io::IoDecoder;
201 ///
202 /// let bytes = pack_io::encode(&42_u64).unwrap();
203 /// let mut dec = IoDecoder::new(Cursor::new(bytes));
204 /// let n: u64 = dec.read().unwrap();
205 /// assert_eq!(n, 42);
206 /// ```
207 #[must_use]
208 pub fn new(reader: R) -> Self {
209 Self {
210 reader,
211 config: Config::new(),
212 depth: 0,
213 read: 0,
214 unbacked: 0,
215 }
216 }
217
218 /// Wrap `reader` with the supplied configuration.
219 ///
220 /// # Errors
221 ///
222 /// - [`SerialError::InvalidConfig`] if `config.max_alloc == 0`,
223 /// `config.max_depth == 0`, or
224 /// `config.canonical` is set: checking canonical map order needs the
225 /// raw input, which a streaming decoder does not keep. Read the frame
226 /// into memory and use [`crate::decode_with_config`] (or
227 /// [`decode_from_with_config`]) instead.
228 ///
229 /// # Examples
230 ///
231 /// ```
232 /// use std::io::Cursor;
233 /// use pack_io::{Config, IoDecoder};
234 ///
235 /// let cfg = Config::new().with_max_alloc(16 * 1024);
236 /// let bytes = pack_io::encode(&"hello").unwrap();
237 /// let mut dec = IoDecoder::with_config(Cursor::new(bytes), cfg).unwrap();
238 /// let s: String = dec.read().unwrap();
239 /// assert_eq!(s, "hello");
240 /// ```
241 pub fn with_config(reader: R, config: Config) -> Result<Self> {
242 let config = config.validate()?;
243 if config.canonical {
244 return Err(SerialError::InvalidConfig {
245 reason: "canonical mode is not supported by IoDecoder; buffer the frame and use decode_with_config",
246 });
247 }
248 Ok(Self {
249 reader,
250 config,
251 depth: 0,
252 read: 0,
253 unbacked: 0,
254 })
255 }
256
257 /// The configuration this decoder enforces.
258 ///
259 /// # Examples
260 ///
261 /// ```
262 /// use std::io::Cursor;
263 /// use pack_io::{Config, IoDecoder};
264 ///
265 /// let cfg = Config::new().with_max_alloc(4096);
266 /// let dec = IoDecoder::with_config(Cursor::new(Vec::new()), cfg).unwrap();
267 /// assert_eq!(dec.config().max_alloc, 4096);
268 /// ```
269 #[must_use]
270 pub fn config(&self) -> Config {
271 self.config
272 }
273
274 /// Borrow the underlying reader.
275 ///
276 /// # Examples
277 ///
278 /// ```
279 /// use std::io::Cursor;
280 /// use pack_io::IoDecoder;
281 ///
282 /// let dec = IoDecoder::new(Cursor::new(vec![0u8; 4]));
283 /// assert_eq!(dec.reader().get_ref().len(), 4);
284 /// ```
285 #[must_use]
286 pub fn reader(&self) -> &R {
287 &self.reader
288 }
289
290 /// Consume the decoder and return the underlying reader.
291 ///
292 /// Useful when the caller wants to take back ownership of the source
293 /// (e.g. to drop the reader, return it to a pool, or feed it to a
294 /// different consumer) after the decoded prefix has been processed.
295 ///
296 /// # Examples
297 ///
298 /// ```
299 /// use std::io::Cursor;
300 /// use pack_io::IoDecoder;
301 ///
302 /// let bytes = pack_io::encode(&42_u64).unwrap();
303 /// let mut dec = IoDecoder::new(Cursor::new(bytes));
304 /// let _n: u64 = dec.read().unwrap();
305 /// let reader: Cursor<Vec<u8>> = dec.into_inner();
306 /// assert_eq!(reader.position(), 1); // one byte consumed for u64=42
307 /// ```
308 #[must_use]
309 pub fn into_inner(self) -> R {
310 self.reader
311 }
312
313 /// Decode the next value from the underlying reader.
314 ///
315 /// # Errors
316 ///
317 /// - Propagates any [`crate::SerialError`] from the type's
318 /// [`Deserialize`].
319 /// - Maps any `std::io::Error` from the reader into [`SerialError::Io`].
320 #[inline]
321 pub fn read<T: Deserialize>(&mut self) -> Result<T> {
322 T::deserialize(self)
323 }
324}
325
326impl<R: Read> Decode for IoDecoder<R> {
327 #[inline]
328 fn read_byte(&mut self) -> Result<u8> {
329 let mut buf = [0u8; 1];
330 self.read_into(&mut buf)?;
331 Ok(buf[0])
332 }
333
334 #[inline]
335 fn read_into(&mut self, out: &mut [u8]) -> Result<()> {
336 self.reader.read_exact(out).map_err(|e| {
337 if e.kind() == std::io::ErrorKind::UnexpectedEof {
338 SerialError::UnexpectedEof {
339 needed: out.len(),
340 remaining: 0,
341 }
342 } else {
343 map_io_error(e)
344 }
345 })?;
346 self.read = self.read.wrapping_add(out.len() as u64);
347 Ok(())
348 }
349
350 fn max_alloc(&self) -> usize {
351 self.config.max_alloc
352 }
353
354 fn config(&self) -> Config {
355 self.config
356 }
357
358 fn depth(&self) -> usize {
359 self.depth
360 }
361
362 fn enter_nested(&mut self) -> Result<()> {
363 if self.depth >= self.config.max_depth {
364 return Err(SerialError::DepthLimitExceeded {
365 max_depth: self.config.max_depth,
366 });
367 }
368 self.depth += 1;
369 Ok(())
370 }
371
372 fn leave_nested(&mut self) {
373 self.depth = self.depth.saturating_sub(1);
374 }
375
376 #[inline]
377 fn bytes_read(&self) -> Option<u64> {
378 Some(self.read)
379 }
380
381 #[inline]
382 fn unbacked(&self) -> usize {
383 self.unbacked
384 }
385
386 fn charge_unbacked(&mut self, bytes: usize) -> Result<()> {
387 let total = self.unbacked.saturating_add(bytes);
388 if total > self.config.max_alloc {
389 return Err(crate::codec::unbacked_limit_error(total, None));
390 }
391 self.unbacked = total;
392 Ok(())
393 }
394}
395
396/// Encode `value` and write the result into `writer` in a single call.
397///
398/// # Errors
399///
400/// - Propagates any [`crate::SerialError`] from the type's [`Serialize`].
401/// - Maps any `std::io::Error` from the writer into [`SerialError::Io`].
402///
403/// # Examples
404///
405/// ```
406/// use pack_io::encode_into;
407///
408/// let mut buf: Vec<u8> = Vec::new();
409/// encode_into(&(7_u64, "hello"), &mut buf).unwrap();
410/// assert!(!buf.is_empty());
411/// ```
412#[inline]
413pub fn encode_into<T, W>(value: &T, writer: &mut W) -> Result<()>
414where
415 T: Serialize + ?Sized,
416 W: Write,
417{
418 let mut enc = IoEncoder::new(writer);
419 enc.write(value)
420}
421
422/// Read all remaining bytes from `reader` and decode them as a single value
423/// of type `T`, under the default [`Config`].
424///
425/// Use this for whole-buffer reads (a length-prefixed message you have
426/// already extracted from the transport, a small config file, …). For
427/// length-framed protocols where the producer wrote one value and then more
428/// bytes for something else, prefer [`IoDecoder`] directly.
429///
430/// The reader is drained into memory first, but never past
431/// [`Config::max_alloc`] bytes: an endless or oversized stream is cut off
432/// and rejected instead of buffered without limit. Use
433/// [`decode_from_with_config`] to set a tighter cap.
434///
435/// # Errors
436///
437/// - [`SerialError::InvalidLength`] if the reader yields more than
438/// `max_alloc` bytes (`declared` reports how many were read before the
439/// cut-off).
440/// - [`SerialError::TrailingBytes`] if the reader yielded extra bytes after
441/// the value was decoded.
442/// - Propagates any [`crate::SerialError`] from the type's [`Deserialize`].
443/// - Maps any `std::io::Error` from the reader into [`SerialError::Io`].
444///
445/// # Examples
446///
447/// ```
448/// use pack_io::{encode, decode_from};
449/// use std::io::Cursor;
450///
451/// let bytes = encode(&42_u64).unwrap();
452/// let n: u64 = decode_from(&mut Cursor::new(bytes)).unwrap();
453/// assert_eq!(n, 42);
454/// ```
455pub fn decode_from<T, R>(reader: &mut R) -> Result<T>
456where
457 T: Deserialize,
458 R: Read,
459{
460 decode_from_with_config(reader, Config::new())
461}
462
463/// [`decode_from`] under an explicit [`Config`].
464///
465/// At most `config.max_alloc` bytes are read from `reader` (one more is
466/// requested to detect an oversized stream); the buffered frame is then
467/// decoded with an in-memory [`crate::Decoder`], so every `Config` knob —
468/// including canonical mode — applies.
469///
470/// # Errors
471///
472/// - Any error [`crate::Decoder::with_config`] reports for an invalid
473/// `config`.
474/// - [`SerialError::InvalidLength`] if the reader yields more than
475/// `config.max_alloc` bytes.
476/// - [`SerialError::TrailingBytes`], decode errors and I/O errors as for
477/// [`decode_from`].
478///
479/// # Examples
480///
481/// ```
482/// use std::io::Cursor;
483/// use pack_io::{Config, SerialError, decode_from_with_config};
484///
485/// // A 1 MiB stream against a 4 KiB cap is cut off after 4 KiB + 1 bytes.
486/// let mut endless = Cursor::new(vec![0u8; 1 << 20]);
487/// let cfg = Config::new().with_max_alloc(4096);
488/// let err = decode_from_with_config::<u8, _>(&mut endless, cfg).unwrap_err();
489/// assert!(matches!(err, SerialError::InvalidLength { declared: 4097, .. }));
490/// ```
491pub fn decode_from_with_config<T, R>(reader: &mut R, config: Config) -> Result<T>
492where
493 T: Deserialize,
494 R: Read,
495{
496 let config = config.validate()?;
497 let cap = config.max_alloc as u64;
498 let mut buf = alloc::vec::Vec::new();
499 let _ = reader
500 .take(cap.saturating_add(1))
501 .read_to_end(&mut buf)
502 .map_err(map_io_error)?;
503 if buf.len() as u64 > cap {
504 return Err(SerialError::InvalidLength {
505 declared: buf.len() as u64,
506 remaining: buf.len(),
507 });
508 }
509 crate::decode_with_config(&buf, config)
510}
511
512/// Map a `std::io::Error` into [`SerialError::Io`].
513#[inline]
514fn map_io_error(err: std::io::Error) -> SerialError {
515 use alloc::string::ToString;
516 SerialError::Io {
517 kind: err.kind(),
518 message: err.to_string(),
519 }
520}
521
522#[cfg(test)]
523mod tests {
524 use super::*;
525 use crate::encode;
526 use alloc::vec::Vec;
527 use std::io::Cursor;
528
529 #[test]
530 fn io_encoder_decoder_round_trip() {
531 let mut buf: Vec<u8> = Vec::new();
532 {
533 let mut enc = IoEncoder::new(&mut buf);
534 enc.write(&42_u64).unwrap();
535 enc.write(&"hello").unwrap();
536 enc.write(&true).unwrap();
537 }
538 let mut dec = IoDecoder::new(Cursor::new(buf));
539 let n: u64 = dec.read().unwrap();
540 let s: String = dec.read().unwrap();
541 let b: bool = dec.read().unwrap();
542 assert_eq!((n, s.as_str(), b), (42, "hello", true));
543 }
544
545 #[test]
546 fn encode_into_writes_same_bytes_as_encode() {
547 let value = (1u32, String::from("hi"), -2i32);
548 let from_fn = encode(&value).unwrap();
549 let mut from_io: Vec<u8> = Vec::new();
550 encode_into(&value, &mut from_io).unwrap();
551 assert_eq!(from_fn, from_io);
552 }
553
554 #[test]
555 fn decode_from_reads_same_value_as_decode() {
556 let bytes = encode(&(7u64, true)).unwrap();
557 let value: (u64, bool) = decode_from(&mut Cursor::new(bytes)).unwrap();
558 assert_eq!(value, (7, true));
559 }
560
561 #[test]
562 fn io_decoder_with_zero_cap_is_rejected() {
563 let cfg = Config::new().with_max_alloc(0);
564 let bytes: Vec<u8> = Vec::new();
565 let err = IoDecoder::with_config(Cursor::new(bytes), cfg).expect_err("zero cap");
566 assert!(matches!(err, SerialError::InvalidConfig { .. }));
567 }
568
569 #[test]
570 fn io_decoder_short_read_surfaces_unexpected_eof() {
571 // Two-byte varint that says "more coming" but there's nothing after.
572 let bytes = alloc::vec![0x80];
573 let mut dec = IoDecoder::new(Cursor::new(bytes));
574 let err = dec.read::<u64>().expect_err("truncated");
575 assert!(matches!(err, SerialError::UnexpectedEof { .. }));
576 }
577}