util.rs 5.6 KB

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