ckb_rust_std/io/
impls.rs

1use crate::io::{self, BorrowedCursor, BufRead, Read, Seek, SeekFrom, Write};
2use alloc::boxed::Box;
3use alloc::collections::VecDeque;
4use alloc::fmt;
5use alloc::str;
6use alloc::string::String;
7use alloc::vec::Vec;
8use core::cmp;
9use core::mem;
10impl<R: Read + ?Sized> Read for &mut R {
11    #[inline]
12    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
13        (**self).read(buf)
14    }
15
16    #[inline]
17    fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
18        (**self).read_buf(cursor)
19    }
20    #[inline]
21    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
22        (**self).read_to_end(buf)
23    }
24
25    #[inline]
26    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
27        (**self).read_to_string(buf)
28    }
29
30    #[inline]
31    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
32        (**self).read_exact(buf)
33    }
34    #[inline]
35    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
36        (**self).read_buf_exact(cursor)
37    }
38}
39impl<W: Write + ?Sized> Write for &mut W {
40    #[inline]
41    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
42        (**self).write(buf)
43    }
44    #[inline]
45    fn flush(&mut self) -> io::Result<()> {
46        (**self).flush()
47    }
48
49    #[inline]
50    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
51        (**self).write_all(buf)
52    }
53
54    #[inline]
55    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
56        (**self).write_fmt(fmt)
57    }
58}
59impl<S: Seek + ?Sized> Seek for &mut S {
60    #[inline]
61    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
62        (**self).seek(pos)
63    }
64    #[inline]
65    fn stream_position(&mut self) -> io::Result<u64> {
66        (**self).stream_position()
67    }
68}
69impl<B: BufRead + ?Sized> BufRead for &mut B {
70    #[inline]
71    fn fill_buf(&mut self) -> io::Result<&[u8]> {
72        (**self).fill_buf()
73    }
74
75    #[inline]
76    fn consume(&mut self, amt: usize) {
77        (**self).consume(amt)
78    }
79
80    #[inline]
81    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
82        (**self).read_until(byte, buf)
83    }
84
85    #[inline]
86    fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
87        (**self).read_line(buf)
88    }
89}
90impl<R: Read + ?Sized> Read for Box<R> {
91    #[inline]
92    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
93        (**self).read(buf)
94    }
95
96    #[inline]
97    fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
98        (**self).read_buf(cursor)
99    }
100
101    #[inline]
102    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
103        (**self).read_to_end(buf)
104    }
105
106    #[inline]
107    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
108        (**self).read_to_string(buf)
109    }
110
111    #[inline]
112    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
113        (**self).read_exact(buf)
114    }
115    #[inline]
116    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
117        (**self).read_buf_exact(cursor)
118    }
119}
120impl<W: Write + ?Sized> Write for Box<W> {
121    #[inline]
122    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
123        (**self).write(buf)
124    }
125    #[inline]
126    fn flush(&mut self) -> io::Result<()> {
127        (**self).flush()
128    }
129    #[inline]
130    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
131        (**self).write_all(buf)
132    }
133
134    #[inline]
135    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
136        (**self).write_fmt(fmt)
137    }
138}
139impl<S: Seek + ?Sized> Seek for Box<S> {
140    #[inline]
141    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
142        (**self).seek(pos)
143    }
144
145    #[inline]
146    fn stream_position(&mut self) -> io::Result<u64> {
147        (**self).stream_position()
148    }
149}
150impl<B: BufRead + ?Sized> BufRead for Box<B> {
151    #[inline]
152    fn fill_buf(&mut self) -> io::Result<&[u8]> {
153        (**self).fill_buf()
154    }
155
156    #[inline]
157    fn consume(&mut self, amt: usize) {
158        (**self).consume(amt)
159    }
160
161    #[inline]
162    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
163        (**self).read_until(byte, buf)
164    }
165
166    #[inline]
167    fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
168        (**self).read_line(buf)
169    }
170}
171
172// =============================================================================
173// In-memory buffer implementations
174
175/// Read is implemented for `&[u8]` by copying from the slice.
176///
177/// Note that reading updates the slice to point to the yet unread part.
178/// The slice will be empty when EOF is reached.
179impl Read for &[u8] {
180    #[inline]
181    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
182        let amt = cmp::min(buf.len(), self.len());
183        let (a, b) = self.split_at(amt);
184
185        // First check if the amount of bytes we want to read is small:
186        // `copy_from_slice` will generally expand to a call to `memcpy`, and
187        // for a single byte the overhead is significant.
188        if amt == 1 {
189            buf[0] = a[0];
190        } else {
191            buf[..amt].copy_from_slice(a);
192        }
193
194        *self = b;
195        Ok(amt)
196    }
197
198    #[inline]
199    fn read_buf(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
200        let amt = cmp::min(cursor.capacity(), self.len());
201        let (a, b) = self.split_at(amt);
202
203        cursor.append(a);
204
205        *self = b;
206        Ok(())
207    }
208    #[inline]
209    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
210        if buf.len() > self.len() {
211            // `read_exact` makes no promise about the content of `buf` if it
212            // fails so don't bother about that.
213            *self = &self[self.len()..];
214            return Err(io::Error::READ_EXACT_EOF);
215        }
216        let (a, b) = self.split_at(buf.len());
217
218        // First check if the amount of bytes we want to read is small:
219        // `copy_from_slice` will generally expand to a call to `memcpy`, and
220        // for a single byte the overhead is significant.
221        if buf.len() == 1 {
222            buf[0] = a[0];
223        } else {
224            buf.copy_from_slice(a);
225        }
226
227        *self = b;
228        Ok(())
229    }
230
231    #[inline]
232    fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
233        if cursor.capacity() > self.len() {
234            // Append everything we can to the cursor.
235            cursor.append(self);
236            *self = &self[self.len()..];
237            return Err(io::Error::READ_EXACT_EOF);
238        }
239        let (a, b) = self.split_at(cursor.capacity());
240
241        cursor.append(a);
242
243        *self = b;
244        Ok(())
245    }
246
247    #[inline]
248    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
249        let len = self.len();
250        buf.try_reserve(len)?;
251        buf.extend_from_slice(self);
252        *self = &self[len..];
253        Ok(len)
254    }
255
256    #[inline]
257    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
258        let content = str::from_utf8(self).map_err(|_| io::Error::INVALID_UTF8)?;
259        let len = self.len();
260        buf.try_reserve(len)?;
261        buf.push_str(content);
262        *self = &self[len..];
263        Ok(len)
264    }
265}
266impl BufRead for &[u8] {
267    #[inline]
268    fn fill_buf(&mut self) -> io::Result<&[u8]> {
269        Ok(*self)
270    }
271
272    #[inline]
273    fn consume(&mut self, amt: usize) {
274        *self = &self[amt..];
275    }
276}
277
278/// Write is implemented for `&mut [u8]` by copying into the slice, overwriting
279/// its data.
280///
281/// Note that writing updates the slice to point to the yet unwritten part.
282/// The slice will be empty when it has been completely overwritten.
283///
284/// If the number of bytes to be written exceeds the size of the slice, write operations will
285/// return short writes: ultimately, `Ok(0)`; in this situation, `write_all` returns an error of
286/// kind `ErrorKind::WriteZero`.
287impl Write for &mut [u8] {
288    #[inline]
289    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
290        let amt = cmp::min(data.len(), self.len());
291        let (a, b) = mem::take(self).split_at_mut(amt);
292        a.copy_from_slice(&data[..amt]);
293        *self = b;
294        Ok(amt)
295    }
296    #[inline]
297    fn is_write_vectored(&self) -> bool {
298        true
299    }
300    #[inline]
301    fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
302        if self.write(data)? == data.len() {
303            Ok(())
304        } else {
305            Err(crate::io::Error::WRITE_ALL_EOF)
306        }
307    }
308    #[inline]
309    fn flush(&mut self) -> io::Result<()> {
310        Ok(())
311    }
312}
313
314/// Write is implemented for `Vec<u8>` by appending to the vector.
315/// The vector will grow as needed.
316impl Write for Vec<u8> {
317    #[inline]
318    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
319        self.extend_from_slice(buf);
320        Ok(buf.len())
321    }
322    #[inline]
323    fn is_write_vectored(&self) -> bool {
324        true
325    }
326
327    #[inline]
328    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
329        self.extend_from_slice(buf);
330        Ok(())
331    }
332
333    #[inline]
334    fn flush(&mut self) -> io::Result<()> {
335        Ok(())
336    }
337}
338/// Read is implemented for `VecDeque<u8>` by consuming bytes from the front of the `VecDeque`.
339impl Read for VecDeque<u8> {
340    /// Fill `buf` with the contents of the "front" slice as returned by
341    /// [`as_slices`][`VecDeque::as_slices`]. If the contained byte slices of the `VecDeque` are
342    /// discontiguous, multiple calls to `read` will be needed to read the entire content.
343    #[inline]
344    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
345        let (ref mut front, _) = self.as_slices();
346        let n = Read::read(front, buf)?;
347        self.drain(..n);
348        Ok(n)
349    }
350
351    #[inline]
352    fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
353        let (ref mut front, _) = self.as_slices();
354        let n = cmp::min(cursor.capacity(), front.len());
355        Read::read_buf(front, cursor)?;
356        self.drain(..n);
357        Ok(())
358    }
359
360    #[inline]
361    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
362        // The total len is known upfront so we can reserve it in a single call.
363        let len = self.len();
364        buf.try_reserve(len)?;
365
366        let (front, back) = self.as_slices();
367        buf.extend_from_slice(front);
368        buf.extend_from_slice(back);
369        self.clear();
370        Ok(len)
371    }
372
373    #[inline]
374    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
375        // SAFETY: We only append to the buffer
376        unsafe { io::append_to_string(buf, |buf| self.read_to_end(buf)) }
377    }
378}
379/// BufRead is implemented for `VecDeque<u8>` by reading bytes from the front of the `VecDeque`.
380impl BufRead for VecDeque<u8> {
381    /// Returns the contents of the "front" slice as returned by
382    /// [`as_slices`][`VecDeque::as_slices`]. If the contained byte slices of the `VecDeque` are
383    /// discontiguous, multiple calls to `fill_buf` will be needed to read the entire content.
384    #[inline]
385    fn fill_buf(&mut self) -> io::Result<&[u8]> {
386        let (front, _) = self.as_slices();
387        Ok(front)
388    }
389    #[inline]
390    fn consume(&mut self, amt: usize) {
391        self.drain(..amt);
392    }
393}
394
395/// Write is implemented for `VecDeque<u8>` by appending to the `VecDeque`, growing it as needed.
396impl Write for VecDeque<u8> {
397    #[inline]
398    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
399        self.extend(buf);
400        Ok(buf.len())
401    }
402    #[inline]
403    fn is_write_vectored(&self) -> bool {
404        true
405    }
406    #[inline]
407    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
408        self.extend(buf);
409        Ok(())
410    }
411
412    #[inline]
413    fn flush(&mut self) -> io::Result<()> {
414        Ok(())
415    }
416}
417impl<'a> io::Write for io::BorrowedCursor<'a> {
418    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
419        let amt = cmp::min(buf.len(), self.capacity());
420        self.append(&buf[..amt]);
421        Ok(amt)
422    }
423
424    #[inline]
425    fn flush(&mut self) -> io::Result<()> {
426        Ok(())
427    }
428}