util.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. #![allow(missing_copy_implementations)]
  11. use core::fmt;
  12. use io::{self, Read, Initializer, Write, ErrorKind};
  13. use core::mem;
  14. #[cfg(feature="alloc")] use io::BufRead;
  15. /// Copies the entire contents of a reader into a writer.
  16. ///
  17. /// This function will continuously read data from `reader` and then
  18. /// write it into `writer` in a streaming fashion until `reader`
  19. /// returns EOF.
  20. ///
  21. /// On success, the total number of bytes that were copied from
  22. /// `reader` to `writer` is returned.
  23. ///
  24. /// If you’re wanting to copy the contents of one file to another and you’re
  25. /// working with filesystem paths, see the [`fs::copy`] function.
  26. ///
  27. /// [`fs::copy`]: ../fs/fn.copy.html
  28. ///
  29. /// # Errors
  30. ///
  31. /// This function will return an error immediately if any call to `read` or
  32. /// `write` returns an error. All instances of `ErrorKind::Interrupted` are
  33. /// handled by this function and the underlying operation is retried.
  34. ///
  35. /// # Examples
  36. ///
  37. /// ```
  38. /// use std::io;
  39. ///
  40. /// fn main() -> io::Result<()> {
  41. /// let mut reader: &[u8] = b"hello";
  42. /// let mut writer: Vec<u8> = vec![];
  43. ///
  44. /// io::copy(&mut reader, &mut writer)?;
  45. ///
  46. /// assert_eq!(&b"hello"[..], &writer[..]);
  47. /// Ok(())
  48. /// }
  49. /// ```
  50. pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<u64>
  51. where R: Read, W: Write
  52. {
  53. let mut buf = unsafe {
  54. let mut buf: [u8; super::DEFAULT_BUF_SIZE] = mem::uninitialized();
  55. reader.initializer().initialize(&mut buf);
  56. buf
  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. /// A reader which is always at EOF.
  71. ///
  72. /// This struct is generally created by calling [`empty`]. Please see
  73. /// the documentation of [`empty()`][`empty`] for more details.
  74. ///
  75. /// [`empty`]: fn.empty.html
  76. pub struct Empty { _priv: () }
  77. /// Constructs a new handle to an empty reader.
  78. ///
  79. /// All reads from the returned reader will return [`Ok`]`(0)`.
  80. ///
  81. /// [`Ok`]: ../result/enum.Result.html#variant.Ok
  82. ///
  83. /// # Examples
  84. ///
  85. /// A slightly sad example of not reading anything into a buffer:
  86. ///
  87. /// ```
  88. /// use std::io::{self, Read};
  89. ///
  90. /// let mut buffer = String::new();
  91. /// io::empty().read_to_string(&mut buffer).unwrap();
  92. /// assert!(buffer.is_empty());
  93. /// ```
  94. pub fn empty() -> Empty { Empty { _priv: () } }
  95. impl Read for Empty {
  96. #[inline]
  97. fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
  98. #[inline]
  99. unsafe fn initializer(&self) -> Initializer {
  100. Initializer::nop()
  101. }
  102. }
  103. #[cfg(feature="alloc")]
  104. impl BufRead for Empty {
  105. #[inline]
  106. fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) }
  107. #[inline]
  108. fn consume(&mut self, _n: usize) {}
  109. }
  110. impl fmt::Debug for Empty {
  111. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  112. f.pad("Empty { .. }")
  113. }
  114. }
  115. /// A reader which yields one byte over and over and over and over and over and...
  116. ///
  117. /// This struct is generally created by calling [`repeat`][repeat]. Please
  118. /// see the documentation of `repeat()` for more details.
  119. ///
  120. /// [repeat]: fn.repeat.html
  121. pub struct Repeat { byte: u8 }
  122. /// Creates an instance of a reader that infinitely repeats one byte.
  123. ///
  124. /// All reads from this reader will succeed by filling the specified buffer with
  125. /// the given byte.
  126. ///
  127. /// # Examples
  128. ///
  129. /// ```
  130. /// use std::io::{self, Read};
  131. ///
  132. /// let mut buffer = [0; 3];
  133. /// io::repeat(0b101).read_exact(&mut buffer).unwrap();
  134. /// assert_eq!(buffer, [0b101, 0b101, 0b101]);
  135. /// ```
  136. pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } }
  137. impl Read for Repeat {
  138. #[inline]
  139. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
  140. for slot in &mut *buf {
  141. *slot = self.byte;
  142. }
  143. Ok(buf.len())
  144. }
  145. #[inline]
  146. unsafe fn initializer(&self) -> Initializer {
  147. Initializer::nop()
  148. }
  149. }
  150. impl fmt::Debug for Repeat {
  151. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  152. f.pad("Repeat { .. }")
  153. }
  154. }
  155. /// A writer which will move data into the void.
  156. ///
  157. /// This struct is generally created by calling [`sink`][sink]. Please
  158. /// see the documentation of `sink()` for more details.
  159. ///
  160. /// [sink]: fn.sink.html
  161. pub struct Sink { _priv: () }
  162. /// Creates an instance of a writer which will successfully consume all data.
  163. ///
  164. /// All calls to `write` on the returned instance will return `Ok(buf.len())`
  165. /// and the contents of the buffer will not be inspected.
  166. ///
  167. /// # Examples
  168. ///
  169. /// ```rust
  170. /// use std::io::{self, Write};
  171. ///
  172. /// let buffer = vec![1, 2, 3, 5, 8];
  173. /// let num_bytes = io::sink().write(&buffer).unwrap();
  174. /// assert_eq!(num_bytes, 5);
  175. /// ```
  176. pub fn sink() -> Sink { Sink { _priv: () } }
  177. impl Write for Sink {
  178. #[inline]
  179. fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
  180. #[inline]
  181. fn flush(&mut self) -> io::Result<()> { Ok(()) }
  182. }
  183. impl fmt::Debug for Sink {
  184. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  185. f.pad("Sink { .. }")
  186. }
  187. }
  188. #[cfg(test)]
  189. mod tests {
  190. use io::prelude::*;
  191. use io::{copy, sink, empty, repeat};
  192. #[test]
  193. fn copy_copies() {
  194. let mut r = repeat(0).take(4);
  195. let mut w = sink();
  196. assert_eq!(copy(&mut r, &mut w).unwrap(), 4);
  197. let mut r = repeat(0).take(1 << 17);
  198. assert_eq!(copy(&mut r as &mut dyn Read, &mut w as &mut dyn Write).unwrap(), 1 << 17);
  199. }
  200. #[test]
  201. fn sink_sinks() {
  202. let mut s = sink();
  203. assert_eq!(s.write(&[]).unwrap(), 0);
  204. assert_eq!(s.write(&[0]).unwrap(), 1);
  205. assert_eq!(s.write(&[0; 1024]).unwrap(), 1024);
  206. assert_eq!(s.by_ref().write(&[0; 1024]).unwrap(), 1024);
  207. }
  208. #[test]
  209. fn empty_reads() {
  210. let mut e = empty();
  211. assert_eq!(e.read(&mut []).unwrap(), 0);
  212. assert_eq!(e.read(&mut [0]).unwrap(), 0);
  213. assert_eq!(e.read(&mut [0; 1024]).unwrap(), 0);
  214. assert_eq!(e.by_ref().read(&mut [0; 1024]).unwrap(), 0);
  215. }
  216. #[test]
  217. fn repeat_repeats() {
  218. let mut r = repeat(4);
  219. let mut b = [0; 1024];
  220. assert_eq!(r.read(&mut b).unwrap(), 1024);
  221. assert!(b.iter().all(|b| *b == 4));
  222. }
  223. #[test]
  224. fn take_some_bytes() {
  225. assert_eq!(repeat(4).take(100).bytes().count(), 100);
  226. assert_eq!(repeat(4).take(100).bytes().next().unwrap().unwrap(), 4);
  227. assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20);
  228. }
  229. }