Skip to main content

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 for the value being decoded.
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 input from a peer, use [`IoDecoder::with_config`] with
191    /// [`Config::network`] (or tighter) 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    /// Each top-level call starts a fresh [`Config::total_alloc_limit`]
316    /// budget, so a decoder that reads one message after another from a
317    /// socket gives every message the same limit.
318    ///
319    /// # Errors
320    ///
321    /// - Propagates any [`crate::SerialError`] from the type's
322    ///   [`Deserialize`].
323    /// - Maps any `std::io::Error` from the reader into [`SerialError::Io`].
324    #[inline]
325    pub fn read<T: Deserialize>(&mut self) -> Result<T> {
326        if self.depth == 0 {
327            self.unbacked = 0;
328        }
329        T::deserialize(self)
330    }
331}
332
333impl<R: Read> Decode for IoDecoder<R> {
334    #[inline]
335    fn read_byte(&mut self) -> Result<u8> {
336        let mut buf = [0u8; 1];
337        self.read_into(&mut buf)?;
338        Ok(buf[0])
339    }
340
341    #[inline]
342    fn read_into(&mut self, out: &mut [u8]) -> Result<()> {
343        self.reader.read_exact(out).map_err(|e| {
344            if e.kind() == std::io::ErrorKind::UnexpectedEof {
345                SerialError::UnexpectedEof {
346                    needed: out.len(),
347                    remaining: 0,
348                }
349            } else {
350                map_io_error(e)
351            }
352        })?;
353        self.read = self.read.wrapping_add(out.len() as u64);
354        Ok(())
355    }
356
357    fn max_alloc(&self) -> usize {
358        self.config.max_alloc
359    }
360
361    fn config(&self) -> Config {
362        self.config
363    }
364
365    fn depth(&self) -> usize {
366        self.depth
367    }
368
369    fn enter_nested(&mut self) -> Result<()> {
370        if self.depth >= self.config.max_depth {
371            return Err(SerialError::DepthLimitExceeded {
372                max_depth: self.config.max_depth,
373            });
374        }
375        self.depth += 1;
376        Ok(())
377    }
378
379    fn leave_nested(&mut self) {
380        self.depth = self.depth.saturating_sub(1);
381    }
382
383    #[inline]
384    fn bytes_read(&self) -> Option<u64> {
385        Some(self.read)
386    }
387
388    #[inline]
389    fn unbacked(&self) -> usize {
390        self.unbacked
391    }
392
393    fn charge_unbacked(&mut self, bytes: usize) -> Result<()> {
394        let total = self.unbacked.saturating_add(bytes);
395        if total > self.config.total_alloc_limit() {
396            return Err(crate::codec::unbacked_limit_error(total, None));
397        }
398        self.unbacked = total;
399        Ok(())
400    }
401
402    #[inline]
403    fn reset_unbacked(&mut self) {
404        self.unbacked = 0;
405    }
406}
407
408/// Encode `value` and write the result into `writer` in a single call.
409///
410/// # Errors
411///
412/// - Propagates any [`crate::SerialError`] from the type's [`Serialize`].
413/// - Maps any `std::io::Error` from the writer into [`SerialError::Io`].
414///
415/// # Examples
416///
417/// ```
418/// use pack_io::encode_into;
419///
420/// let mut buf: Vec<u8> = Vec::new();
421/// encode_into(&(7_u64, "hello"), &mut buf).unwrap();
422/// assert!(!buf.is_empty());
423/// ```
424#[inline]
425pub fn encode_into<T, W>(value: &T, writer: &mut W) -> Result<()>
426where
427    T: Serialize + ?Sized,
428    W: Write,
429{
430    let mut enc = IoEncoder::new(writer);
431    enc.write(value)
432}
433
434/// Read all remaining bytes from `reader` and decode them as a single value
435/// of type `T`, under the default [`Config`].
436///
437/// Use this for whole-buffer reads (a length-prefixed message you have
438/// already extracted from the transport, a small config file, …). For
439/// length-framed protocols where the producer wrote one value and then more
440/// bytes for something else, prefer [`IoDecoder`] directly.
441///
442/// The reader is drained into memory first, but never past
443/// [`Config::max_alloc`] bytes: an endless or oversized stream is cut off
444/// and rejected instead of buffered without limit. Use
445/// [`decode_from_with_config`] to set a tighter cap.
446///
447/// # Errors
448///
449/// - [`SerialError::InvalidLength`] if the reader yields more than
450///   `max_alloc` bytes (`declared` reports how many were read before the
451///   cut-off).
452/// - [`SerialError::TrailingBytes`] if the reader yielded extra bytes after
453///   the value was decoded.
454/// - Propagates any [`crate::SerialError`] from the type's [`Deserialize`].
455/// - Maps any `std::io::Error` from the reader into [`SerialError::Io`].
456///
457/// # Examples
458///
459/// ```
460/// use pack_io::{encode, decode_from};
461/// use std::io::Cursor;
462///
463/// let bytes = encode(&42_u64).unwrap();
464/// let n: u64 = decode_from(&mut Cursor::new(bytes)).unwrap();
465/// assert_eq!(n, 42);
466/// ```
467pub fn decode_from<T, R>(reader: &mut R) -> Result<T>
468where
469    T: Deserialize,
470    R: Read,
471{
472    decode_from_with_config(reader, Config::new())
473}
474
475/// [`decode_from`] under an explicit [`Config`].
476///
477/// At most `config.max_alloc` bytes are read from `reader` (one more is
478/// requested to detect an oversized stream); the buffered frame is then
479/// decoded with an in-memory [`crate::Decoder`], so every `Config` knob —
480/// including canonical mode — applies.
481///
482/// # Errors
483///
484/// - Any error [`crate::Decoder::with_config`] reports for an invalid
485///   `config`.
486/// - [`SerialError::InvalidLength`] if the reader yields more than
487///   `config.max_alloc` bytes.
488/// - [`SerialError::TrailingBytes`], decode errors and I/O errors as for
489///   [`decode_from`].
490///
491/// # Examples
492///
493/// ```
494/// use std::io::Cursor;
495/// use pack_io::{Config, SerialError, decode_from_with_config};
496///
497/// // A 1 MiB stream against a 4 KiB cap is cut off after 4 KiB + 1 bytes.
498/// let mut endless = Cursor::new(vec![0u8; 1 << 20]);
499/// let cfg = Config::new().with_max_alloc(4096);
500/// let err = decode_from_with_config::<u8, _>(&mut endless, cfg).unwrap_err();
501/// assert!(matches!(err, SerialError::InvalidLength { declared: 4097, .. }));
502/// ```
503pub fn decode_from_with_config<T, R>(reader: &mut R, config: Config) -> Result<T>
504where
505    T: Deserialize,
506    R: Read,
507{
508    let config = config.validate()?;
509    let cap = config.max_alloc as u64;
510    let mut buf = alloc::vec::Vec::new();
511    let _ = reader
512        .take(cap.saturating_add(1))
513        .read_to_end(&mut buf)
514        .map_err(map_io_error)?;
515    if buf.len() as u64 > cap {
516        return Err(SerialError::InvalidLength {
517            declared: buf.len() as u64,
518            remaining: buf.len(),
519        });
520    }
521    crate::decode_with_config(&buf, config)
522}
523
524/// Map a `std::io::Error` into [`SerialError::Io`].
525#[inline]
526fn map_io_error(err: std::io::Error) -> SerialError {
527    use alloc::string::ToString;
528    SerialError::Io {
529        kind: err.kind(),
530        message: err.to_string(),
531    }
532}
533
534#[cfg(test)]
535mod tests {
536    use super::*;
537    use crate::encode;
538    use alloc::vec::Vec;
539    use std::io::Cursor;
540
541    #[test]
542    fn io_encoder_decoder_round_trip() {
543        let mut buf: Vec<u8> = Vec::new();
544        {
545            let mut enc = IoEncoder::new(&mut buf);
546            enc.write(&42_u64).unwrap();
547            enc.write(&"hello").unwrap();
548            enc.write(&true).unwrap();
549        }
550        let mut dec = IoDecoder::new(Cursor::new(buf));
551        let n: u64 = dec.read().unwrap();
552        let s: String = dec.read().unwrap();
553        let b: bool = dec.read().unwrap();
554        assert_eq!((n, s.as_str(), b), (42, "hello", true));
555    }
556
557    #[test]
558    fn encode_into_writes_same_bytes_as_encode() {
559        let value = (1u32, String::from("hi"), -2i32);
560        let from_fn = encode(&value).unwrap();
561        let mut from_io: Vec<u8> = Vec::new();
562        encode_into(&value, &mut from_io).unwrap();
563        assert_eq!(from_fn, from_io);
564    }
565
566    #[test]
567    fn decode_from_reads_same_value_as_decode() {
568        let bytes = encode(&(7u64, true)).unwrap();
569        let value: (u64, bool) = decode_from(&mut Cursor::new(bytes)).unwrap();
570        assert_eq!(value, (7, true));
571    }
572
573    #[test]
574    fn io_decoder_with_zero_cap_is_rejected() {
575        let cfg = Config::new().with_max_alloc(0);
576        let bytes: Vec<u8> = Vec::new();
577        let err = IoDecoder::with_config(Cursor::new(bytes), cfg).expect_err("zero cap");
578        assert!(matches!(err, SerialError::InvalidConfig { .. }));
579    }
580
581    #[test]
582    fn io_decoder_short_read_surfaces_unexpected_eof() {
583        // Two-byte varint that says "more coming" but there's nothing after.
584        let bytes = alloc::vec![0x80];
585        let mut dec = IoDecoder::new(Cursor::new(bytes));
586        let err = dec.read::<u64>().expect_err("truncated");
587        assert!(matches!(err, SerialError::UnexpectedEof { .. }));
588    }
589}