Skip to main content

ax_io/utils/
repeat.rs

1#[cfg(feature = "alloc")]
2use alloc::{string::String, vec::Vec};
3use core::{fmt, io::BorrowedCursor};
4
5use crate::{IoBuf, Read, Result};
6
7/// A reader which yields one byte over and over and over and over and over and...
8///
9/// This struct is generally created by calling [`repeat()`]. Please
10/// see the documentation of [`repeat()`] for more details.
11pub struct Repeat {
12    byte: u8,
13}
14
15/// Creates an instance of a reader that infinitely repeats one byte.
16///
17/// All reads from this reader will succeed by filling the specified buffer with
18/// the given byte.
19///
20/// See [`std::io::repeat()`] for more details.
21#[must_use]
22pub const fn repeat(byte: u8) -> Repeat {
23    Repeat { byte }
24}
25
26impl Read for Repeat {
27    #[inline]
28    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
29        buf.fill(self.byte);
30        Ok(buf.len())
31    }
32
33    #[inline]
34    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
35        buf.fill(self.byte);
36        Ok(())
37    }
38
39    #[inline]
40    fn read_buf(&mut self, mut buf: BorrowedCursor<'_>) -> Result<()> {
41        // SAFETY: No uninit bytes are being written.
42        unsafe { buf.as_mut() }.write_filled(self.byte);
43        // SAFETY: the entire unfilled portion of buf has been initialized.
44        unsafe { buf.advance(buf.capacity()) };
45        Ok(())
46    }
47
48    #[inline]
49    fn read_buf_exact(&mut self, buf: BorrowedCursor<'_>) -> Result<()> {
50        self.read_buf(buf)
51    }
52
53    /// This function is not supported by `Repeat`, because there's no end of its data
54    #[cfg(feature = "alloc")]
55    fn read_to_end(&mut self, _: &mut Vec<u8>) -> Result<usize> {
56        Err(crate::Error::NoMemory)
57    }
58
59    /// This function is not supported by `Repeat`, because there's no end of its data
60    #[cfg(feature = "alloc")]
61    fn read_to_string(&mut self, _: &mut String) -> Result<usize> {
62        Err(crate::Error::NoMemory)
63    }
64}
65
66impl fmt::Debug for Repeat {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.debug_struct("Repeat").finish_non_exhaustive()
69    }
70}
71
72impl IoBuf for Repeat {
73    fn remaining(&self) -> usize {
74        usize::MAX
75    }
76}