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 {
45            #[cfg(borrowedbuf_init)]
46            buf.advance_unchecked(buf.capacity());
47            #[cfg(not(borrowedbuf_init))]
48            buf.advance(buf.capacity());
49        };
50        Ok(())
51    }
52
53    #[inline]
54    fn read_buf_exact(&mut self, buf: BorrowedCursor<'_>) -> Result<()> {
55        self.read_buf(buf)
56    }
57
58    /// This function is not supported by `Repeat`, because there's no end of its data
59    #[cfg(feature = "alloc")]
60    fn read_to_end(&mut self, _: &mut Vec<u8>) -> Result<usize> {
61        Err(crate::Error::NoMemory)
62    }
63
64    /// This function is not supported by `Repeat`, because there's no end of its data
65    #[cfg(feature = "alloc")]
66    fn read_to_string(&mut self, _: &mut String) -> Result<usize> {
67        Err(crate::Error::NoMemory)
68    }
69}
70
71impl fmt::Debug for Repeat {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.debug_struct("Repeat").finish_non_exhaustive()
74    }
75}
76
77impl IoBuf for Repeat {
78    fn remaining(&self) -> usize {
79        usize::MAX
80    }
81}