util.rs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 io::{self, Read, Write, ErrorKind, BufRead};
  12. /// Copies the entire contents of a reader into a writer.
  13. ///
  14. /// This function will continuously read data from `reader` and then
  15. /// write it into `writer` in a streaming fashion until `reader`
  16. /// returns EOF.
  17. ///
  18. /// On success, the total number of bytes that were copied from
  19. /// `reader` to `writer` is returned.
  20. ///
  21. /// # Errors
  22. ///
  23. /// This function will return an error immediately if any call to `read` or
  24. /// `write` returns an error. All instances of `ErrorKind::Interrupted` are
  25. /// handled by this function and the underlying operation is retried.
  26. ///
  27. /// # Examples
  28. ///
  29. /// ```
  30. /// use std::io;
  31. ///
  32. /// # fn foo() -> io::Result<()> {
  33. /// let mut reader: &[u8] = b"hello";
  34. /// let mut writer: Vec<u8> = vec![];
  35. ///
  36. /// try!(io::copy(&mut reader, &mut writer));
  37. ///
  38. /// assert_eq!(reader, &writer[..]);
  39. /// # Ok(())
  40. /// # }
  41. /// ```
  42. #[stable(feature = "rust1", since = "1.0.0")]
  43. pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<u64>
  44. where R: Read, W: Write
  45. {
  46. let mut buf = [0; super::DEFAULT_BUF_SIZE];
  47. let mut written = 0;
  48. loop {
  49. let len = match reader.read(&mut buf) {
  50. Ok(0) => return Ok(written),
  51. Ok(len) => len,
  52. Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
  53. Err(e) => return Err(e),
  54. };
  55. writer.write_all(&buf[..len])?;
  56. written += len as u64;
  57. }
  58. }
  59. /// A reader which is always at EOF.
  60. ///
  61. /// This struct is generally created by calling [`empty()`][empty]. Please see
  62. /// the documentation of `empty()` for more details.
  63. ///
  64. /// [empty]: fn.empty.html
  65. #[stable(feature = "rust1", since = "1.0.0")]
  66. pub struct Empty { _priv: () }
  67. /// Constructs a new handle to an empty reader.
  68. ///
  69. /// All reads from the returned reader will return `Ok(0)`.
  70. ///
  71. /// # Examples
  72. ///
  73. /// A slightly sad example of not reading anything into a buffer:
  74. ///
  75. /// ```
  76. /// use std::io;
  77. /// use std::io::Read;
  78. ///
  79. /// # fn foo() -> io::Result<String> {
  80. /// let mut buffer = String::new();
  81. /// try!(io::empty().read_to_string(&mut buffer));
  82. /// # Ok(buffer)
  83. /// # }
  84. /// ```
  85. #[stable(feature = "rust1", since = "1.0.0")]
  86. pub fn empty() -> Empty { Empty { _priv: () } }
  87. #[stable(feature = "rust1", since = "1.0.0")]
  88. impl Read for Empty {
  89. fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
  90. }
  91. #[stable(feature = "rust1", since = "1.0.0")]
  92. impl BufRead for Empty {
  93. fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) }
  94. fn consume(&mut self, _n: usize) {}
  95. }
  96. /// A reader which yields one byte over and over and over and over and over and...
  97. ///
  98. /// This struct is generally created by calling [`repeat()`][repeat]. Please
  99. /// see the documentation of `repeat()` for more details.
  100. ///
  101. /// [repeat]: fn.repeat.html
  102. #[stable(feature = "rust1", since = "1.0.0")]
  103. pub struct Repeat { byte: u8 }
  104. /// Creates an instance of a reader that infinitely repeats one byte.
  105. ///
  106. /// All reads from this reader will succeed by filling the specified buffer with
  107. /// the given byte.
  108. #[stable(feature = "rust1", since = "1.0.0")]
  109. pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } }
  110. #[stable(feature = "rust1", since = "1.0.0")]
  111. impl Read for Repeat {
  112. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
  113. for slot in &mut *buf {
  114. *slot = self.byte;
  115. }
  116. Ok(buf.len())
  117. }
  118. }
  119. /// A writer which will move data into the void.
  120. ///
  121. /// This struct is generally created by calling [`sink()`][sink]. Please
  122. /// see the documentation of `sink()` for more details.
  123. ///
  124. /// [sink]: fn.sink.html
  125. #[stable(feature = "rust1", since = "1.0.0")]
  126. pub struct Sink { _priv: () }
  127. /// Creates an instance of a writer which will successfully consume all data.
  128. ///
  129. /// All calls to `write` on the returned instance will return `Ok(buf.len())`
  130. /// and the contents of the buffer will not be inspected.
  131. #[stable(feature = "rust1", since = "1.0.0")]
  132. pub fn sink() -> Sink { Sink { _priv: () } }
  133. #[stable(feature = "rust1", since = "1.0.0")]
  134. impl Write for Sink {
  135. fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
  136. fn flush(&mut self) -> io::Result<()> { Ok(()) }
  137. }
  138. #[cfg(test)]
  139. mod tests {
  140. use prelude::v1::*;
  141. use io::prelude::*;
  142. use io::{copy, sink, empty, repeat};
  143. #[test]
  144. fn copy_copies() {
  145. let mut r = repeat(0).take(4);
  146. let mut w = sink();
  147. assert_eq!(copy(&mut r, &mut w).unwrap(), 4);
  148. let mut r = repeat(0).take(1 << 17);
  149. assert_eq!(copy(&mut r as &mut Read, &mut w as &mut Write).unwrap(), 1 << 17);
  150. }
  151. #[test]
  152. fn sink_sinks() {
  153. let mut s = sink();
  154. assert_eq!(s.write(&[]).unwrap(), 0);
  155. assert_eq!(s.write(&[0]).unwrap(), 1);
  156. assert_eq!(s.write(&[0; 1024]).unwrap(), 1024);
  157. assert_eq!(s.by_ref().write(&[0; 1024]).unwrap(), 1024);
  158. }
  159. #[test]
  160. fn empty_reads() {
  161. let mut e = empty();
  162. assert_eq!(e.read(&mut []).unwrap(), 0);
  163. assert_eq!(e.read(&mut [0]).unwrap(), 0);
  164. assert_eq!(e.read(&mut [0; 1024]).unwrap(), 0);
  165. assert_eq!(e.by_ref().read(&mut [0; 1024]).unwrap(), 0);
  166. }
  167. #[test]
  168. fn repeat_repeats() {
  169. let mut r = repeat(4);
  170. let mut b = [0; 1024];
  171. assert_eq!(r.read(&mut b).unwrap(), 1024);
  172. assert!(b.iter().all(|b| *b == 4));
  173. }
  174. #[test]
  175. fn take_some_bytes() {
  176. assert_eq!(repeat(4).take(100).bytes().count(), 100);
  177. assert_eq!(repeat(4).take(100).bytes().next().unwrap().unwrap(), 4);
  178. assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20);
  179. }
  180. }