Skip to main content

bitcoin_io/
lib.rs

1//! Rust-Bitcoin IO Library
2//!
3//! The `std::io` module is not exposed in `no-std` Rust so building `no-std` applications which
4//! require reading and writing objects via standard traits is not generally possible. Thus, this
5//! library exists to export a minmal version of `std::io`'s traits which we use in `rust-bitcoin`
6//! so that we can support `no-std` applications.
7//!
8//! These traits are not one-for-one drop-ins, but are as close as possible while still implementing
9//! `std::io`'s traits without unnecessary complexity.
10
11#![cfg_attr(not(feature = "std"), no_std)]
12
13// Coding conventions.
14#![warn(missing_docs)]
15
16// Exclude lints we don't think are valuable.
17#![allow(clippy::needless_question_mark)] // https://github.com/rust-bitcoin/rust-bitcoin/pull/2134
18#![allow(clippy::manual_range_contains)] // More readable than clippy's format.
19
20#[cfg(feature = "alloc")]
21extern crate alloc;
22
23#[cfg(feature = "encoding")]
24pub extern crate encoding;
25
26mod error;
27mod macros;
28#[cfg(feature = "std")]
29mod bridge;
30
31#[cfg(feature = "std")]
32pub use bridge::{FromStd, ToStd};
33
34#[cfg(all(not(feature = "std"), feature = "alloc"))]
35use alloc::vec::Vec;
36use core::cmp;
37
38#[cfg(feature = "encoding")]
39use encoding::Decoder;
40
41#[rustfmt::skip]                // Keep public re-exports separate.
42pub use self::error::{Error, ErrorKind};
43
44/// Result type returned by functions in this crate.
45pub type Result<T> = core::result::Result<T, Error>;
46
47/// A generic trait describing an input stream. See [`std::io::Read`] for more info.
48pub trait Read {
49    /// Reads bytes from source into `buf`.
50    fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
51
52    /// Reads bytes from source until `buf` is full.
53    #[inline]
54    fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
55        while !buf.is_empty() {
56            match self.read(buf) {
57                Ok(0) => return Err(ErrorKind::UnexpectedEof.into()),
58                Ok(len) => buf = &mut buf[len..],
59                Err(e) if e.kind() == ErrorKind::Interrupted => {}
60                Err(e) => return Err(e),
61            }
62        }
63        Ok(())
64    }
65
66    /// Creates an adapter which will read at most `limit` bytes.
67    #[inline]
68    fn take(&mut self, limit: u64) -> Take<'_, Self> { Take { reader: self, remaining: limit } }
69
70    /// Attempts to read up to limit bytes from the reader, allocating space in `buf` as needed.
71    ///
72    /// `limit` is used to prevent a denial of service attack vector since an unbounded reader will
73    /// exhaust all memory.
74    ///
75    /// Similar to `std::io::Read::read_to_end` but with the DOS protection.
76    #[doc(alias = "read_to_end")]
77    #[cfg(feature = "alloc")]
78    #[inline]
79    fn read_to_limit(&mut self, buf: &mut Vec<u8>, limit: u64) -> Result<usize> {
80        self.take(limit).read_to_end(buf)
81    }
82}
83
84/// A trait describing an input stream that uses an internal buffer when reading.
85pub trait BufRead: Read {
86    /// Returns data read from this reader, filling the internal buffer if needed.
87    fn fill_buf(&mut self) -> Result<&[u8]>;
88
89    /// Marks the buffered data up to amount as consumed.
90    ///
91    /// # Panics
92    ///
93    /// May panic if `amount` is greater than amount of data read by `fill_buf`.
94    fn consume(&mut self, amount: usize);
95}
96
97/// Reader adapter which limits the bytes read from an underlying reader.
98///
99/// Created by calling `[Read::take]`.
100pub struct Take<'a, R: Read + ?Sized> {
101    reader: &'a mut R,
102    remaining: u64,
103}
104
105impl<'a, R: Read + ?Sized> Take<'a, R> {
106    /// Reads all bytes until EOF from the underlying reader into `buf`.
107    #[cfg(feature = "alloc")]
108    #[inline]
109    pub fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
110        let mut read: usize = 0;
111        let mut chunk = [0u8; 64];
112        loop {
113            match self.read(&mut chunk) {
114                Ok(0) => break,
115                Ok(n) => {
116                    buf.extend_from_slice(&chunk[0..n]);
117                    read += n;
118                }
119                Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
120                Err(e) => return Err(e),
121            };
122        }
123        Ok(read)
124    }
125}
126
127impl<'a, R: Read + ?Sized> Read for Take<'a, R> {
128    #[inline]
129    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
130        let len = cmp::min(buf.len(), self.remaining.try_into().unwrap_or(buf.len()));
131        let read = self.reader.read(&mut buf[..len])?;
132        self.remaining -= read.try_into().unwrap_or(self.remaining);
133        Ok(read)
134    }
135}
136
137// Impl copied from Rust stdlib.
138impl<'a, R: BufRead + ?Sized> BufRead for Take<'a, R> {
139    #[inline]
140    fn fill_buf(&mut self) -> Result<&[u8]> {
141        // Don't call into inner reader at all at EOF because it may still block
142        if self.remaining == 0 {
143            return Ok(&[]);
144        }
145
146        let buf = self.reader.fill_buf()?;
147        // Cast length to a u64 instead of casting `remaining` to a `usize`
148        // (in case `remaining > u32::MAX` and we are on a 32 bit machine).
149        let cap = cmp::min(buf.len() as u64, self.remaining) as usize;
150        Ok(&buf[..cap])
151    }
152
153    #[inline]
154    fn consume(&mut self, amount: usize) {
155        assert!(amount as u64 <= self.remaining);
156        self.remaining -= amount as u64;
157        self.reader.consume(amount);
158    }
159}
160
161impl Read for &[u8] {
162    #[inline]
163    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
164        let cnt = cmp::min(self.len(), buf.len());
165        buf[..cnt].copy_from_slice(&self[..cnt]);
166        *self = &self[cnt..];
167        Ok(cnt)
168    }
169}
170
171impl BufRead for &[u8] {
172    #[inline]
173    fn fill_buf(&mut self) -> Result<&[u8]> { Ok(self) }
174
175    // This panics if amount is out of bounds, same as the std version.
176    #[inline]
177    fn consume(&mut self, amount: usize) { *self = &self[amount..] }
178}
179
180/// Wraps an in memory reader providing the `position` function.
181pub struct Cursor<T> {
182    inner: T,
183    pos: u64,
184}
185
186impl<T: AsRef<[u8]>> Cursor<T> {
187    /// Creates a `Cursor` by wrapping `inner`.
188    #[inline]
189    pub fn new(inner: T) -> Self { Cursor { inner, pos: 0 } }
190
191    /// Returns the position read up to thus far.
192    #[inline]
193    pub fn position(&self) -> u64 { self.pos }
194
195    /// Sets the internal position.
196    ///
197    /// This method allows seeking within the wrapped memory by setting the position.
198    ///
199    /// Note that setting a position that is larger than the buffer length will cause reads to
200    /// return no bytes (EOF).
201    #[inline]
202    pub fn set_position(&mut self, position: u64) {
203        self.pos = position;
204    }
205
206    /// Returns the inner buffer.
207    ///
208    /// This is the whole wrapped buffer, including the bytes already read.
209    #[inline]
210    pub fn into_inner(self) -> T { self.inner }
211
212    /// Returns a reference to the inner buffer.
213    ///
214    /// This is the whole wrapped buffer, including the bytes already read.
215    #[inline]
216    pub fn inner(&self) -> &T { &self.inner }
217}
218
219impl<T: AsRef<[u8]>> Read for Cursor<T> {
220    #[inline]
221    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
222        let inner: &[u8] = self.inner.as_ref();
223        let start_pos = self.pos.try_into().unwrap_or(inner.len());
224        let read = core::cmp::min(inner.len().saturating_sub(start_pos), buf.len());
225        buf[..read].copy_from_slice(&inner[start_pos..start_pos + read]);
226        self.pos =
227            self.pos.saturating_add(read.try_into().unwrap_or(u64::MAX /* unreachable */));
228        Ok(read)
229    }
230}
231
232impl<T: AsRef<[u8]>> BufRead for Cursor<T> {
233    #[inline]
234    fn fill_buf(&mut self) -> Result<&[u8]> {
235        let inner: &[u8] = self.inner.as_ref();
236        Ok(&inner[self.pos as usize..])
237    }
238
239    #[inline]
240    fn consume(&mut self, amount: usize) {
241        assert!(amount <= self.inner.as_ref().len());
242        self.pos += amount as u64;
243    }
244}
245
246/// A generic trait describing an output stream. See [`std::io::Write`] for more info.
247pub trait Write {
248    /// Writes `buf` into this writer, returning how many bytes were written.
249    fn write(&mut self, buf: &[u8]) -> Result<usize>;
250
251    /// Flushes this output stream, ensuring that all intermediately buffered contents
252    /// reach their destination.
253    fn flush(&mut self) -> Result<()>;
254
255    /// Attempts to write an entire buffer into this writer.
256    #[inline]
257    fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
258        while !buf.is_empty() {
259            match self.write(buf) {
260                Ok(0) => return Err(ErrorKind::UnexpectedEof.into()),
261                Ok(len) => buf = &buf[len..],
262                Err(e) if e.kind() == ErrorKind::Interrupted => {}
263                Err(e) => return Err(e),
264            }
265        }
266        Ok(())
267    }
268}
269
270#[cfg(feature = "alloc")]
271impl Write for alloc::vec::Vec<u8> {
272    #[inline]
273    fn write(&mut self, buf: &[u8]) -> Result<usize> {
274        self.extend_from_slice(buf);
275        Ok(buf.len())
276    }
277
278    #[inline]
279    fn flush(&mut self) -> Result<()> { Ok(()) }
280}
281
282impl Write for &'_ mut [u8] {
283    #[inline]
284    fn write(&mut self, buf: &[u8]) -> Result<usize> {
285        let cnt = core::cmp::min(self.len(), buf.len());
286        self[..cnt].copy_from_slice(&buf[..cnt]);
287        *self = &mut core::mem::take(self)[cnt..];
288        Ok(cnt)
289    }
290
291    #[inline]
292    fn flush(&mut self) -> Result<()> { Ok(()) }
293}
294
295/// A sink to which all writes succeed. See [`std::io::Sink`] for more info.
296///
297/// Created using `io::sink()`.
298pub struct Sink;
299
300impl Write for Sink {
301    #[inline]
302    fn write(&mut self, buf: &[u8]) -> Result<usize> { Ok(buf.len()) }
303
304    #[inline]
305    fn write_all(&mut self, _: &[u8]) -> Result<()> { Ok(()) }
306
307    #[inline]
308    fn flush(&mut self) -> Result<()> { Ok(()) }
309}
310
311/// Returns a sink to which all writes succeed. See [`std::io::sink`] for more info.
312#[inline]
313pub fn sink() -> Sink { Sink }
314
315/// Wraps a `std` IO type to implement the traits from this crate.
316///
317/// All methods are passed through converting the errors.
318#[cfg(feature = "std")]
319#[inline]
320pub const fn from_std<T>(std_io: T) -> FromStd<T> {
321    FromStd::new(std_io)
322}
323
324/// Wraps a mutable reference to `std` IO type to implement the traits from this crate.
325///
326/// All methods are passed through converting the errors.
327#[cfg(feature = "std")]
328#[inline]
329pub fn from_std_mut<T>(std_io: &mut T) -> &mut FromStd<T> {
330    FromStd::new_mut(std_io)
331}
332
333/// An error that can occur when reading and decoding from a buffered reader.
334#[derive(Debug)]
335pub enum ReadError<D> {
336    /// An I/O error occurred while reading from the reader.
337    Io(Error),
338    /// The decoder encountered an error while parsing the data.
339    Decode(D),
340}
341
342impl<D: core::fmt::Display> core::fmt::Display for ReadError<D> {
343    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
344        match self {
345            Self::Io(e) => write!(f, "I/O error: {}", e),
346            Self::Decode(e) => write!(f, "decode error: {}", e),
347        }
348    }
349}
350
351#[cfg(feature = "std")]
352impl<D> std::error::Error for ReadError<D>
353where
354    D: core::fmt::Debug + core::fmt::Display + std::error::Error + 'static,
355{
356    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
357        match self {
358            Self::Io(e) => Some(e),
359            Self::Decode(e) => Some(e),
360        }
361    }
362}
363
364#[cfg(feature = "std")]
365impl<D> From<Error> for ReadError<D> {
366    fn from(e: Error) -> Self { Self::Io(e) }
367}
368
369/// Encodes a `consensus_encoding` object to an I/O writer.
370///
371/// # Errors
372///
373/// If an I/O error occurs while writing to the underlying writer.
374#[cfg(feature = "encoding")]
375pub fn encode_to_writer<T, W>(object: &T, writer: W) -> Result<()>
376where
377    T: encoding::Encode + ?Sized,
378    W: Write,
379{
380    let mut encoder = object.encoder();
381    drain_to_writer(&mut encoder, writer)
382}
383
384/// Drains the output of an [`encoding::Encoder`] to an I/O writer.
385///
386/// See [`encode_to_writer`] for more information.
387///
388/// # Errors
389///
390/// Returns any I/O error encountered while writing to the writer.
391#[cfg(feature = "encoding")]
392pub fn drain_to_writer<T, W>(encoder: &mut T, mut writer: W) -> Result<()>
393where
394    T: encoding::Encoder + ?Sized,
395    W: Write,
396{
397    loop {
398        writer.write_all(encoder.current_chunk())?;
399        if encoder.advance().has_finished() {
400            break;
401        }
402    }
403    Ok(())
404}
405
406/// Decodes an object from a buffered reader.
407///
408/// # Performance
409///
410/// For unbuffered readers (like [`std::fs::File`] or [`std::net::TcpStream`]), consider wrapping
411/// your reader with [`std::io::BufReader`] in order to use this function. This avoids frequent
412/// small reads, which can significantly impact performance.
413///
414/// # Errors
415///
416/// Returns [`ReadError::Decode`] if the decoder encounters an error while parsing
417/// the data, or [`ReadError::Io`] if an I/O error occurs while reading.
418#[cfg(feature = "encoding")]
419pub fn decode_from_read<T, R>(
420    reader: R,
421) -> core::result::Result<T, ReadError<<T::Decoder as Decoder>::Error>>
422where
423    T: encoding::Decode,
424    R: BufRead,
425{
426    decode_from_read_internal(reader, T::decoder())
427}
428
429/// Decodes an object from a buffered reader using a [`Decoder`] type.
430///
431/// Unlike [`decode_from_read`], this takes a generic [`Decoder`] parameter, allowing use with
432/// decoders which don't have a dedicated [`encoding::Decode`] implementer.
433///
434/// # Performance
435///
436/// For unbuffered readers (like [`std::fs::File`] or [`std::net::TcpStream`]), consider wrapping
437/// your reader with [`std::io::BufReader`] in order to use this function. This avoids frequent
438/// small reads, which can significantly impact performance.
439///
440/// # Errors
441///
442/// Returns [`ReadError::Decode`] if the decoder encounters an error while parsing
443/// the data, or [`ReadError::Io`] if an I/O error occurs while reading.
444#[cfg(feature = "encoding")]
445pub fn decode_from_read_with<D, R>(
446    reader: R,
447) -> core::result::Result<D::Output, ReadError<D::Error>>
448where
449    D: Decoder + Default,
450    R: BufRead,
451{
452    decode_from_read_internal(reader, D::default())
453}
454
455#[cfg(feature = "encoding")]
456fn decode_from_read_internal<D, R>(
457    mut reader: R,
458    mut decoder: D,
459) -> core::result::Result<D::Output, ReadError<D::Error>>
460where
461    D: Decoder + Default,
462    R: BufRead,
463{
464    loop {
465        let mut buffer = match reader.fill_buf() {
466            Ok(buffer) => buffer,
467            // Auto retry read for non-fatal error.
468            Err(error) if error.kind() == ErrorKind::Interrupted => continue,
469            Err(error) => return Err(ReadError::Io(error)),
470        };
471
472        if buffer.is_empty() {
473            // EOF, but still try to finalize the decoder.
474            return decoder.end().map_err(ReadError::Decode);
475        }
476
477        let original_len = buffer.len();
478        let status = decoder.push_bytes(&mut buffer).map_err(ReadError::Decode)?;
479        let consumed = original_len - buffer.len();
480        reader.consume(consumed);
481
482        if status.is_ready() {
483            return decoder.end().map_err(ReadError::Decode);
484        }
485    }
486
487}
488
489/// Decodes an object from an unbuffered reader using a fixed-size buffer.
490///
491/// For most use cases, prefer [`decode_from_read`] with a [`std::io::BufReader`].
492/// This function is only needed when you have an unbuffered reader which you
493/// cannot wrap. It will probably have worse performance.
494///
495/// # Buffer
496///
497/// Uses a fixed 4KB (4096 bytes) stack-allocated buffer that is reused across
498/// read operations. This size is a good balance between memory usage and
499/// system call efficiency for most use cases.
500///
501/// For different buffer sizes, use [`decode_from_read_unbuffered_with`].
502///
503/// # Errors
504///
505/// Returns [`ReadError::Decode`] if the decoder encounters an error while parsing
506/// the data, or [`ReadError::Io`] if an I/O error occurs while reading.
507#[cfg(feature = "encoding")]
508pub fn decode_from_read_unbuffered<T, R>(
509    reader: R,
510) -> core::result::Result<T, ReadError<<T::Decoder as Decoder>::Error>>
511where
512    T: encoding::Decode,
513    R: Read,
514{
515    decode_from_read_unbuffered_with::<T, R, 4096>(reader)
516}
517
518/// Decodes an object from an unbuffered reader using a custom-sized buffer.
519///
520/// For most use cases, prefer [`decode_from_read`] with a [`std::io::BufReader`].
521/// This function is only needed when you have an unbuffered reader which you
522/// cannot wrap. It will probably have worse performance.
523///
524/// # Buffer
525///
526/// The `BUFFER_SIZE` parameter controls the intermediate buffer size used for
527/// reading. The buffer is allocated on the stack (not heap) and reused across
528/// read operations. Larger buffers reduce the number of system calls, but use
529/// more memory.
530///
531/// # Errors
532///
533/// Returns [`ReadError::Decode`] if the decoder encounters an error while parsing
534/// the data, or [`ReadError::Io`] if an I/O error occurs while reading.
535#[cfg(feature = "encoding")]
536pub fn decode_from_read_unbuffered_with<T, R, const BUFFER_SIZE: usize>(
537    mut reader: R,
538) -> core::result::Result<T, ReadError<<T::Decoder as Decoder>::Error>>
539where
540    T: encoding::Decode,
541    R: Read,
542{
543    let mut decoder = T::decoder();
544    let mut buffer = [0u8; BUFFER_SIZE];
545
546    while decoder.read_limit() > 0 {
547        // Only read what we need, up to buffer size.
548        let clamped_buffer = &mut buffer[..decoder.read_limit().min(BUFFER_SIZE)];
549        match reader.read(clamped_buffer) {
550            Ok(0) => {
551                // EOF, but still try to finalize the decoder.
552                return decoder.end().map_err(ReadError::Decode);
553            }
554            Ok(bytes_read) => {
555                let mut to_push = &clamped_buffer[..bytes_read];
556                while !to_push.is_empty() {
557                    if decoder.push_bytes(&mut to_push).map_err(ReadError::Decode)?.is_ready() {
558                        return decoder.end().map_err(ReadError::Decode);
559                    }
560                }
561            }
562            Err(ref e) if e.kind() == ErrorKind::Interrupted => {
563                // Auto retry read for non-fatal error.
564            }
565            Err(e) => return Err(ReadError::Io(e)),
566        }
567    }
568
569    decoder.end().map_err(ReadError::Decode)
570}
571
572#[cfg(test)]
573mod tests {
574    use super::*;
575
576    #[cfg(all(not(feature = "std"), feature = "alloc"))]
577    use alloc::{string::ToString, vec};
578
579    #[test]
580    fn buf_read_fill_and_consume_slice() {
581        let data = [0_u8, 1, 2];
582
583        let mut slice = &data[..];
584
585        let fill = BufRead::fill_buf(&mut slice).unwrap();
586        assert_eq!(fill.len(), 3);
587        assert_eq!(fill, &[0_u8, 1, 2]);
588        slice.consume(2);
589
590        let fill = BufRead::fill_buf(&mut slice).unwrap();
591        assert_eq!(fill.len(), 1);
592        assert_eq!(fill, &[2_u8]);
593        slice.consume(1);
594
595        // checks we can attempt to read from a now-empty reader.
596        let fill = BufRead::fill_buf(&mut slice).unwrap();
597        assert_eq!(fill.len(), 0);
598        assert_eq!(fill, &[]);
599    }
600
601    #[test]
602    #[cfg(feature = "alloc")]
603    fn read_to_limit_greater_than_total_length() {
604        let s = "16-byte-string!!".to_string();
605        let mut reader = Cursor::new(&s);
606        let mut buf = vec![];
607
608        // 32 is greater than the reader length.
609        let read = reader.read_to_limit(&mut buf, 32).expect("failed to read to limit");
610        assert_eq!(read, s.len());
611        assert_eq!(&buf, s.as_bytes())
612    }
613
614    #[test]
615    #[cfg(feature = "alloc")]
616    fn read_to_limit_less_than_total_length() {
617        let s = "16-byte-string!!".to_string();
618        let mut reader = Cursor::new(&s);
619        let mut buf = vec![];
620
621        let read = reader.read_to_limit(&mut buf, 2).expect("failed to read to limit");
622        assert_eq!(read, 2);
623        assert_eq!(&buf, "16".as_bytes())
624    }
625
626    #[cfg(feature = "encoding")]
627    mod encoding_tests {
628        use super::*;
629
630        struct TestData(u32);
631
632        impl encoding::Encode for TestData {
633            type Encoder<'s: 's> = encoding::ArrayEncoder<4>;
634
635            fn encoder(&self) -> Self::Encoder<'_> {
636                encoding::ArrayEncoder::without_length_prefix(self.0.to_le_bytes())
637            }
638        }
639
640        struct TestArray([u8; 4]);
641
642        impl encoding::Decode for TestArray {
643            type Decoder = TestArrayDecoder;
644        }
645
646        #[derive(Default)]
647        struct TestArrayDecoder {
648            inner: encoding::ArrayDecoder<4>,
649        }
650
651        impl encoding::Decoder for TestArrayDecoder {
652            type Output = TestArray;
653            type Error = encoding::UnexpectedEofError;
654
655            fn push_bytes(
656                &mut self,
657                bytes: &mut &[u8],
658            ) -> core::result::Result<encoding::DecoderStatus, Self::Error> {
659                self.inner.push_bytes(bytes)
660            }
661
662            fn end(self) -> core::result::Result<Self::Output, Self::Error> {
663                self.inner.end().map(TestArray)
664            }
665
666            fn read_limit(&self) -> usize {
667                self.inner.read_limit()
668            }
669        }
670
671        #[test]
672        fn encode_to_writer() {
673            let data = TestData(0x1234_5678);
674
675            let mut buf = [0_u8; 4];
676            super::encode_to_writer(&data, buf.as_mut_slice()).unwrap();
677
678            assert_eq!(buf, [0x78, 0x56, 0x34, 0x12]);
679        }
680
681        #[test]
682        fn decode_from_read_success() {
683            let data = [1, 2, 3, 4];
684            let cursor = Cursor::new(&data);
685            let result: core::result::Result<TestArray, _> = super::decode_from_read(cursor);
686            assert!(result.is_ok());
687            let decoded = result.unwrap();
688            assert_eq!(decoded.0, [1, 2, 3, 4]);
689        }
690
691        #[test]
692        fn decode_from_read_unexpected_eof() {
693            let data = [1, 2, 3];
694            let cursor = Cursor::new(&data);
695            let result: core::result::Result<TestArray, _> = super::decode_from_read(cursor);
696            assert!(matches!(result, Err(ReadError::Decode(_))));
697        }
698
699        #[test]
700        fn decode_from_read_unbuffered_success() {
701            let data = [1, 2, 3, 4];
702            let cursor = Cursor::new(&data);
703            let result: core::result::Result<TestArray, _> =
704                super::decode_from_read_unbuffered(cursor);
705            assert!(result.is_ok());
706            let decoded = result.unwrap();
707            assert_eq!(decoded.0, [1, 2, 3, 4]);
708        }
709
710        #[test]
711        fn decode_from_read_unbuffered_unexpected_eof() {
712            let data = [1, 2, 3];
713            let cursor = Cursor::new(&data);
714            let result: core::result::Result<TestArray, _> =
715                super::decode_from_read_unbuffered(cursor);
716            assert!(matches!(result, Err(ReadError::Decode(_))));
717        }
718
719        #[test]
720        fn decode_from_read_unbuffered_empty() {
721            let data = [];
722            let cursor = Cursor::new(&data);
723            let result: core::result::Result<TestArray, _> =
724                super::decode_from_read_unbuffered(cursor);
725            assert!(matches!(result, Err(ReadError::Decode(_))));
726        }
727
728        #[test]
729        fn decode_from_read_unbuffered_extra_data() {
730            let data = [1, 2, 3, 4, 5, 6];
731            let cursor = Cursor::new(&data);
732            let result: core::result::Result<TestArray, _> =
733                super::decode_from_read_unbuffered(cursor);
734            assert!(result.is_ok());
735            let decoded = result.unwrap();
736            assert_eq!(decoded.0, [1, 2, 3, 4]);
737        }
738    }
739}