efi/io/
util.rs

1// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11#![allow(missing_copy_implementations)]
12
13use core::fmt;
14use crate::io::{self, Read, Initializer, Write, ErrorKind};
15use core::mem;
16use crate::io::BufRead;
17
18/// Copies the entire contents of a reader into a writer.
19///
20/// This function will continuously read data from `reader` and then
21/// write it into `writer` in a streaming fashion until `reader`
22/// returns EOF.
23///
24/// On success, the total number of bytes that were copied from
25/// `reader` to `writer` is returned.
26///
27/// # Errors
28///
29/// This function will return an error immediately if any call to `read` or
30/// `write` returns an error. All instances of `ErrorKind::Interrupted` are
31/// handled by this function and the underlying operation is retried.
32///
33/// # Examples
34///
35/// ```
36/// use std::io;
37///
38/// # fn foo() -> io::Result<()> {
39/// let mut reader: &[u8] = b"hello";
40/// let mut writer: Vec<u8> = vec![];
41///
42/// io::copy(&mut reader, &mut writer)?;
43///
44/// assert_eq!(&b"hello"[..], &writer[..]);
45/// # Ok(())
46/// # }
47/// # foo().unwrap();
48/// ```
49pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<u64>
50    where R: Read, W: Write
51{
52    let mut buf = unsafe {
53        let mut buf = mem::MaybeUninit::<[u8; super::DEFAULT_BUF_SIZE]>::uninit();
54        reader.initializer().initialize(&mut *buf.as_mut_ptr());
55        buf.assume_init()
56    };
57
58    let mut written = 0;
59    loop {
60        let len = match reader.read(&mut buf) {
61            Ok(0) => return Ok(written),
62            Ok(len) => len,
63            Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
64            Err(e) => return Err(e),
65        };
66        writer.write_all(&buf[..len])?;
67        written += len as u64;
68    }
69}
70
71pub fn fill_buf<R: Read>(reader: &mut R, buf: &mut [u8]) -> io::Result<usize> {
72    let mut bytes_read = 0;
73    loop {
74        match reader.read(&mut buf[bytes_read..]) {
75            Ok(n) => {
76                bytes_read += n;
77                if n == 0 || bytes_read == buf.len() { // Either EOF or we filled the buf
78                    return Ok(bytes_read)
79                } else if bytes_read > buf.len() { // WTF. Should never happen 
80                    return Err(io::ErrorKind::Other.into())
81                }
82            },
83            Err(_) => return Err(io::ErrorKind::Other.into()) , // TODO: Do not swallow upstream error here
84        }
85    }
86}
87
88/// A reader which is always at EOF.
89///
90/// This struct is generally created by calling [`empty`]. Please see
91/// the documentation of [`empty()`][`empty`] for more details.
92///
93/// [`empty`]: fn.empty.html
94pub struct Empty { _priv: () }
95
96/// Constructs a new handle to an empty reader.
97///
98/// All reads from the returned reader will return [`Ok`]`(0)`.
99///
100/// [`Ok`]: ../result/enum.Result.html#variant.Ok
101///
102/// # Examples
103///
104/// A slightly sad example of not reading anything into a buffer:
105///
106/// ```
107/// use std::io::{self, Read};
108///
109/// let mut buffer = String::new();
110/// io::empty().read_to_string(&mut buffer).unwrap();
111/// assert!(buffer.is_empty());
112/// ```
113pub fn empty() -> Empty { Empty { _priv: () } }
114
115impl Read for Empty {
116    #[inline]
117    fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
118
119    #[inline]
120    unsafe fn initializer(&self) -> Initializer {
121        Initializer::nop()
122    }
123}
124
125impl BufRead for Empty {
126    #[inline]
127    fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) }
128    #[inline]
129    fn consume(&mut self, _n: usize) {}
130}
131
132impl fmt::Debug for Empty {
133    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
134        f.pad("Empty { .. }")
135    }
136}
137
138/// A reader which yields one byte over and over and over and over and over and...
139///
140/// This struct is generally created by calling [`repeat`][repeat]. Please
141/// see the documentation of `repeat()` for more details.
142///
143/// [repeat]: fn.repeat.html
144pub struct Repeat { byte: u8 }
145
146/// Creates an instance of a reader that infinitely repeats one byte.
147///
148/// All reads from this reader will succeed by filling the specified buffer with
149/// the given byte.
150///
151/// # Examples
152///
153/// ```
154/// use std::io::{self, Read};
155///
156/// let mut buffer = [0; 3];
157/// io::repeat(0b101).read_exact(&mut buffer).unwrap();
158/// assert_eq!(buffer, [0b101, 0b101, 0b101]);
159/// ```
160pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } }
161
162impl Read for Repeat {
163    #[inline]
164    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
165        for slot in &mut *buf {
166            *slot = self.byte;
167        }
168        Ok(buf.len())
169    }
170
171    #[inline]
172    unsafe fn initializer(&self) -> Initializer {
173        Initializer::nop()
174    }
175}
176
177impl fmt::Debug for Repeat {
178    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
179        f.pad("Repeat { .. }")
180    }
181}
182
183/// A writer which will move data into the void.
184///
185/// This struct is generally created by calling [`sink`][sink]. Please
186/// see the documentation of `sink()` for more details.
187///
188/// [sink]: fn.sink.html
189pub struct Sink { _priv: () }
190
191/// Creates an instance of a writer which will successfully consume all data.
192///
193/// All calls to `write` on the returned instance will return `Ok(buf.len())`
194/// and the contents of the buffer will not be inspected.
195///
196/// # Examples
197///
198/// ```rust
199/// use std::io::{self, Write};
200///
201/// let buffer = vec![1, 2, 3, 5, 8];
202/// let num_bytes = io::sink().write(&buffer).unwrap();
203/// assert_eq!(num_bytes, 5);
204/// ```
205pub fn sink() -> Sink { Sink { _priv: () } }
206
207impl Write for Sink {
208    #[inline]
209    fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
210    #[inline]
211    fn flush(&mut self) -> io::Result<()> { Ok(()) }
212}
213
214impl fmt::Debug for Sink {
215    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
216        f.pad("Sink { .. }")
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use io::prelude::*;
223    use io::{copy, sink, empty, repeat};
224
225    #[test]
226    fn copy_copies() {
227        let mut r = repeat(0).take(4);
228        let mut w = sink();
229        assert_eq!(copy(&mut r, &mut w).unwrap(), 4);
230
231        let mut r = repeat(0).take(1 << 17);
232        assert_eq!(copy(&mut r as &mut Read, &mut w as &mut Write).unwrap(), 1 << 17);
233    }
234
235    #[test]
236    fn sink_sinks() {
237        let mut s = sink();
238        assert_eq!(s.write(&[]).unwrap(), 0);
239        assert_eq!(s.write(&[0]).unwrap(), 1);
240        assert_eq!(s.write(&[0; 1024]).unwrap(), 1024);
241        assert_eq!(s.by_ref().write(&[0; 1024]).unwrap(), 1024);
242    }
243
244    #[test]
245    fn empty_reads() {
246        let mut e = empty();
247        assert_eq!(e.read(&mut []).unwrap(), 0);
248        assert_eq!(e.read(&mut [0]).unwrap(), 0);
249        assert_eq!(e.read(&mut [0; 1024]).unwrap(), 0);
250        assert_eq!(e.by_ref().read(&mut [0; 1024]).unwrap(), 0);
251    }
252
253    #[test]
254    fn repeat_repeats() {
255        let mut r = repeat(4);
256        let mut b = [0; 1024];
257        assert_eq!(r.read(&mut b).unwrap(), 1024);
258        assert!(b.iter().all(|b| *b == 4));
259    }
260
261    #[test]
262    fn take_some_bytes() {
263        assert_eq!(repeat(4).take(100).bytes().count(), 100);
264        assert_eq!(repeat(4).take(100).bytes().next().unwrap().unwrap(), 4);
265        assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20);
266    }
267}