ckb_rust_std/io/
util.rs

1#[cfg(test)]
2mod tests;
3
4use crate::io;
5use crate::io::{BorrowedCursor, BufRead, Read, Seek, SeekFrom, SizeHint, Write};
6use alloc::fmt;
7use alloc::string::String;
8use alloc::vec::Vec;
9
10/// `Empty` ignores any data written via [`Write`], and will always be empty
11/// (returning zero bytes) when read via [`Read`].
12///
13/// This struct is generally created by calling [`empty()`]. Please
14/// see the documentation of [`empty()`] for more details.
15#[non_exhaustive]
16#[derive(Copy, Clone, Debug, Default)]
17pub struct Empty;
18
19/// Creates a value that is always at EOF for reads, and ignores all data written.
20///
21/// All calls to [`write`] on the returned instance will return [`Ok(buf.len())`]
22/// and the contents of the buffer will not be inspected.
23///
24/// All calls to [`read`] from the returned reader will return [`Ok(0)`].
25///
26/// [`Ok(buf.len())`]: Ok
27/// [`Ok(0)`]: Ok
28///
29/// [`write`]: Write::write
30/// [`read`]: Read::read
31///
32/// # Examples
33///
34/// ```rust
35/// use std::io::{self, Write};
36///
37/// let buffer = vec![1, 2, 3, 5, 8];
38/// let num_bytes = io::empty().write(&buffer).unwrap();
39/// assert_eq!(num_bytes, 5);
40/// ```
41///
42///
43/// ```rust
44/// use std::io::{self, Read};
45///
46/// let mut buffer = String::new();
47/// io::empty().read_to_string(&mut buffer).unwrap();
48/// assert!(buffer.is_empty());
49/// ```
50#[must_use]
51pub const fn empty() -> Empty {
52    Empty
53}
54impl Read for Empty {
55    #[inline]
56    fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
57        Ok(0)
58    }
59
60    #[inline]
61    fn read_buf(&mut self, _cursor: BorrowedCursor<'_>) -> io::Result<()> {
62        Ok(())
63    }
64}
65impl BufRead for Empty {
66    #[inline]
67    fn fill_buf(&mut self) -> io::Result<&[u8]> {
68        Ok(&[])
69    }
70    #[inline]
71    fn consume(&mut self, _n: usize) {}
72}
73impl Seek for Empty {
74    fn seek(&mut self, _pos: SeekFrom) -> io::Result<u64> {
75        Ok(0)
76    }
77
78    fn stream_len(&mut self) -> io::Result<u64> {
79        Ok(0)
80    }
81
82    fn stream_position(&mut self) -> io::Result<u64> {
83        Ok(0)
84    }
85}
86
87impl SizeHint for Empty {
88    #[inline]
89    fn lower_bound(&self) -> usize {
90        0
91    }
92    #[inline]
93    fn upper_bound(&self) -> Option<usize> {
94        Some(0)
95    }
96}
97impl Write for Empty {
98    #[inline]
99    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
100        Ok(buf.len())
101    }
102    #[inline]
103    fn is_write_vectored(&self) -> bool {
104        true
105    }
106
107    #[inline]
108    fn flush(&mut self) -> io::Result<()> {
109        Ok(())
110    }
111}
112impl Write for &Empty {
113    #[inline]
114    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
115        Ok(buf.len())
116    }
117    #[inline]
118    fn is_write_vectored(&self) -> bool {
119        true
120    }
121
122    #[inline]
123    fn flush(&mut self) -> io::Result<()> {
124        Ok(())
125    }
126}
127
128/// A reader which yields one byte over and over and over and over and over and...
129///
130/// This struct is generally created by calling [`repeat()`]. Please
131/// see the documentation of [`repeat()`] for more details.
132pub struct Repeat {
133    byte: u8,
134}
135
136/// Creates an instance of a reader that infinitely repeats one byte.
137///
138/// All reads from this reader will succeed by filling the specified buffer with
139/// the given byte.
140///
141/// # Examples
142///
143/// ```
144/// use std::io::{self, Read};
145///
146/// let mut buffer = [0; 3];
147/// io::repeat(0b101).read_exact(&mut buffer).unwrap();
148/// assert_eq!(buffer, [0b101, 0b101, 0b101]);
149/// ```
150#[must_use]
151pub const fn repeat(byte: u8) -> Repeat {
152    Repeat { byte }
153}
154impl Read for Repeat {
155    #[inline]
156    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
157        for slot in &mut *buf {
158            *slot = self.byte;
159        }
160        Ok(buf.len())
161    }
162
163    fn read_buf(&mut self, mut buf: BorrowedCursor<'_>) -> io::Result<()> {
164        // SAFETY: No uninit bytes are being written
165        for slot in unsafe { buf.as_mut() } {
166            slot.write(self.byte);
167        }
168
169        let remaining = buf.capacity();
170
171        // SAFETY: the entire unfilled portion of buf has been initialized
172        unsafe {
173            buf.advance_unchecked(remaining);
174        }
175
176        Ok(())
177    }
178
179    /// This function is not supported by `io::Repeat`, because there's no end of its data
180    fn read_to_end(&mut self, _: &mut Vec<u8>) -> io::Result<usize> {
181        Err(io::Error::from(io::ErrorKind::OutOfMemory))
182    }
183
184    /// This function is not supported by `io::Repeat`, because there's no end of its data
185    fn read_to_string(&mut self, _: &mut String) -> io::Result<usize> {
186        Err(io::Error::from(io::ErrorKind::OutOfMemory))
187    }
188}
189
190impl SizeHint for Repeat {
191    #[inline]
192    fn lower_bound(&self) -> usize {
193        usize::MAX
194    }
195
196    #[inline]
197    fn upper_bound(&self) -> Option<usize> {
198        None
199    }
200}
201impl fmt::Debug for Repeat {
202    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203        f.debug_struct("Repeat").finish_non_exhaustive()
204    }
205}
206
207/// A writer which will move data into the void.
208///
209/// This struct is generally created by calling [`sink()`]. Please
210/// see the documentation of [`sink()`] for more details.
211#[non_exhaustive]
212#[derive(Copy, Clone, Debug, Default)]
213pub struct Sink;
214
215/// Creates an instance of a writer which will successfully consume all data.
216///
217/// All calls to [`write`] on the returned instance will return [`Ok(buf.len())`]
218/// and the contents of the buffer will not be inspected.
219///
220/// [`write`]: Write::write
221/// [`Ok(buf.len())`]: Ok
222///
223/// # Examples
224///
225/// ```rust
226/// use std::io::{self, Write};
227///
228/// let buffer = vec![1, 2, 3, 5, 8];
229/// let num_bytes = io::sink().write(&buffer).unwrap();
230/// assert_eq!(num_bytes, 5);
231/// ```
232#[must_use]
233pub const fn sink() -> Sink {
234    Sink
235}
236impl Write for Sink {
237    #[inline]
238    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
239        Ok(buf.len())
240    }
241
242    #[inline]
243    fn is_write_vectored(&self) -> bool {
244        true
245    }
246
247    #[inline]
248    fn flush(&mut self) -> io::Result<()> {
249        Ok(())
250    }
251}
252impl Write for &Sink {
253    #[inline]
254    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
255        Ok(buf.len())
256    }
257    #[inline]
258    fn is_write_vectored(&self) -> bool {
259        true
260    }
261
262    #[inline]
263    fn flush(&mut self) -> io::Result<()> {
264        Ok(())
265    }
266}