1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
use {Read, Write, Split, Bytes, Error, ErrorKind, copy, copy_until, Result}; use std; /// Alternative to `std::io::BufRead` /// /// This trait is automatically implemented for all types that implement `std::io::BufRead`. /// /// Differences to [`std::io::BufRead`] /// =================================== /// Methods that are just wrappers around the equivalent methods of [`std::io::BufRead`]: /// /// - `fill_buf` /// - `consume` /// /// Methods that provide a slightly different functionality than their counterparts in /// [`std::io::BufRead`]: /// /// - `read_until` /// - `split` /// /// Methods originally implemented in a different place: /// /// - `read_to_end` ← [`std::io::Read::read_to_end`] /// - `read_exact` ← [`std::io::Read::read_exact`] /// - `bytes` ← [`std::io::Read::bytes`] /// /// New methods that have no counterpart in `std::io`: /// /// - `skip_to_end` /// - `skip_until` /// /// Functions that were removed or moved to a different trait, /// because they cannot be implemented with providing all desired guarantees: /// /// - `read_line` → [`Utf8Reader::read_line`] /// /// [`Utf8Reader::read_line`]: ./struct.Utf8Reader.html#method.read_line /// [`std::io::Read::read_to_end`]: /// https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_to_end /// [`std::io::Read::read_exact`]: /// https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_exact /// [`std::io::Read::bytes`]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.bytes /// [`std::io::Read`]: https://doc.rust-lang.org/nightly/std/io/trait.Read.html pub trait BufRead: Read { /// Fills the internal buffer of this object, returning the buffer contents. /// /// This method is equivalent to [`std::io::BufRead::fill_buf`]. /// /// [`std::io::BufRead::fill_buf`]: /// https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.fill_buf fn fill_buf(&mut self) -> Result<&[u8]>; /// Tells this buffer that `amt` bytes have been consumed from the buffer, /// so they should no longer be returned in calls to `read`. /// /// This method is equivalent to [`std::io::BufRead::consume`]. /// /// [`std::io::BufRead::consume`]: /// https://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#tymethod.consume #[inline] fn consume(&mut self, amt: usize); /// Read all bytes until EOF in this source, placing them into `buf`. /// /// Similar to [`std::io::Read::read_to_end`], all bytes read from this source will /// be appended to the specified buffer `buf`. /// /// This function will continuously call [`fill_buf`] and [`consume`] to /// append more data to `buf` until [`fill_buf`] returns either `Ok(&[])` or any kind of error. /// /// Errors /// ====== /// This function will return an error immediately if any call to [`fill_buf`] returns /// any kind of error. /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function. /// /// All bytes consumed from the reader will be written to the buffer and vice versa. /// It is guaranteed that no data is lost in case of error. /// /// Differences to `std::io::Read::read_to_end` /// =========================================== /// - Does not retry on [`ErrorKind`]`::Interrupted`. /// - Uses [`BufRead`] instead of [`Read`]. /// - Does not return the number of bytes that are copied. /// - Works with all kind of writers, not just `Vec<u8>` /// /// Advantages /// ---------- /// - Function is interruptable, e.g. to allow graceful shutdown for server applications. /// - Avoids double buffering if the source already implements [`BufRead`]. /// - Allows different buffer sizes by using [`BufReader::with_capacity`]. /// /// Disadvantages /// ------------- /// The fact that it does not return the number of bytes copied stems from the fact that it /// cannot return this information in case of error. /// This would go against the goal of allowing reliable retry. /// /// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf /// [`consume`]: ./trait.BufRead.html#tymethod.consume /// [`BufRead`]: ./trait.BufRead.html /// [`Read`]: ./trait.Read.html /// [`BufReader::with_capacity`]: /// ./buf_redux_reexport/struct.BufReader.html#method.with_capacity /// [`std::io::Read::read_to_end`]: /// https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_to_end /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html #[inline] fn read_to_end<B: ?Sized>(&mut self, buf: &mut B) -> Result<()> where Self: Sized, B: Write { copy(self, buf) } /// Skip all bytes until EOF in this source. /// /// Acts like [`read_to_end`], but all bytes read from this source are /// discarded. /// /// This function will continuously call [`fill_buf`] and [`consume`] until /// [`fill_buf`] returns either `Ok(&[])` or any kind of error. /// /// Errors /// ====== /// This function will return an error immediately if any call to [`fill_buf`] returns /// any kind of error. /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function. /// /// [`read_to_end`]: #method.read_to_end /// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf /// [`consume`]: ./trait.BufRead.html#tymethod.consume /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html #[inline] fn skip_to_end(&mut self) -> Result<()> { copy(self, &mut std::io::sink()) } /// Read the exact number of bytes required to fill `buf`. /// /// Similarliy to [`std::io::Read::read_exact`], this function reads as many bytes /// as necessary to completely fill the specified buffer `buf`. /// /// No guarantees are provided about the contents of `buf` when this /// function is called, implementations cannot rely on any property of the /// contents of `buf` being true. It is recommended that implementations /// only write data to `buf` instead of reading its contents. /// /// Errors /// ====== /// This function will return an error immediately if any call to [`fill_buf`] returns /// any kind of error. /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function. /// /// If this function encounters an "end of file" before completely filling /// the buffer, it returns an error of the kind [`ErrorKind`]`::UnexpectedEof`. /// /// If this function returns an error, the buffer will contain all bytes read up to that point. /// The position of the cursor will point one byte past the last read byte. /// /// All bytes consumed from the reader will be written to the buffer and vice versa. /// It is guaranteed that no data is lost in case of error. /// /// Differences to `std::io::Read::read_exact` /// ========================================== /// - Does not retry on [`ErrorKind`]`::Interrupted`. /// - Uses [`BufRead`] instead of [`Read`]. /// - In case of error the buffer contains all bytes read up to that point. /// - Takes a [`Cursor`] instead of plain buffer to track the current position. /// /// Advantages /// ---------- /// - Function is interruptable, e.g. to allow graceful shutdown for server applications. /// - No data ist lost on error. /// /// Disadvantages /// ------------- /// The function is slightly less ergonomic to use. /// /// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf /// [`BufRead`]: ./trait.BufRead.html /// [`Read`]: ./trait.Read.html /// [`Cursor`]: https://doc.rust-lang.org/nightly/std/io/struct.Cursor.html /// [`std::io::Read::read_exact`]: /// https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.read_exact /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html fn read_exact(&mut self, buf: &mut std::io::Cursor<&mut [u8]>) -> Result<()> { let mut remaining = buf.get_ref().len() - buf.position() as usize; while remaining > 0 { let written = { let available = try!(BufRead::fill_buf(self)); if available.len() == 0 { return Err(Error::new(ErrorKind::UnexpectedEof, "Stream is already at EOF")); } try!(buf.write(available)) }; remaining -= written; BufRead::consume(self, written); } Ok(()) } /// Transforms this buffered reader into an iterator over its bytes. /// /// This method is approximately equivalent to [`std::io::Read::bytes`]. /// /// The returned type implements [`std::iter::Iterator`] /// where the `Item` is `Result<u8, R::Err>`. /// The yielded item is `Ok` if a byte was successfully read and /// `Err` otherwise for I/O errors. EOF is mapped to returning `None` from /// this iterator. /// /// Errors /// ====== /// If fill_buf returns any kind of error, the iterator yields `Some(Err)`. In case of error /// it is safe to iterate further to retry the reading operation. /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by the iterator. /// /// Differences to `std::io::Read::bytes` /// ===================================== /// - Uses [`BufRead`] instead of [`Read`]. /// /// Advantages /// ---------- /// - No accidentialy unbuffered reading of single bytes /// /// [`Read`]: ./trait.Read.html /// [`BufRead`]: ./trait.BufRead.html /// [`std::io::Read::bytes`]: /// https://doc.rust-lang.org/nightly/std/io/trait.Read.html#method.bytes /// [`std::iter::Iterator`]: https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html #[inline] fn bytes(self) -> Bytes<Self> where Self: Sized { Bytes::new(self) } /// Read all bytes into a buffer until a delimiter is reached. /// /// Similar to [`std::io::BufRead::read_until`] ,this function will read bytes from /// the underlying stream and push them to the specified buffer `buf`, until the delimiter /// `delim` is found. If the delimiter is found, it is also part of the result. /// /// Errors /// ====== /// This function will return an error immediately if any call to [`fill_buf`] returns /// any kind of error. /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function. /// /// If this reader has reached EOF then this function will return /// [`ErrorKind`]`::UnexpectedEof`. /// /// All bytes consumed from the buffered reader will be written to the specified buffer and /// vice versa. /// It is guaranteed that no data is lost in case of error. /// /// Differences to `std::io::BufRead::read_until` /// ============================================= /// - Does not retry on [`ErrorKind`]`::Interrupted`. /// - Does not return the number of bytes that are read. /// - Returns an error on EOF instead of success. /// - Works with all kind of writers, not just `Vec<u8>` /// /// Advantages /// ---------- /// - Function is interruptable, e.g. to allow graceful shutdown for server applications. /// /// Disadvantages /// ------------- /// The fact that it does not return the number of bytes copied stems from the fact that it /// cannot return this information in case of error. /// This would go against the goal of allowing reliable retry. /// /// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf /// [`std::io::BufRead::read_until`]: /// http://doc.rust-lang.org/nightly/std/io/trait.BufRead.html#method.read_until /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html #[inline] fn read_until<W: ?Sized>(&mut self, delim: u8, buf: &mut W) -> Result<()> where Self: Sized, W: Write { copy_until(self, buf, delim) } /// Skips all bytes until a delimiter is reached. /// /// This function will discard bytes from the underlying stream until the delimiter `delim` is /// found. /// /// Acts like [`read_until`], but all bytes read from this source are /// discarded. /// /// Errors /// ====== /// This function will return an error immediately if any call to [`fill_buf`] returns /// any kind of error. /// Instances of [`ErrorKind`]`::Interrupted` are *not* handled by this function. /// /// If this reader has reached EOF then this function will return /// [`ErrorKind`]`::UnexpectedEof`. /// /// [`read_until`]: #method.read_until /// [`fill_buf`]: ./trait.BufRead.html#tymethod.fill_buf /// [`ErrorKind`]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html #[inline] fn skip_until(&mut self, delim: u8) -> Result<()> { copy_until(self, &mut std::io::sink(), delim) } /// Returns an iterator over the contents of this reader split on a delimiter. /// /// The iterator returned from this function will return instances of /// `io::Result<Vec<u8>>`. Each vector returned will *not* have the /// delimiter byte at the end. /// /// Errors /// ====== /// The iterator will yield an error whenever [`read_until`] would have also /// returned an error. /// /// [`read_until`]: #method.read_until #[inline] fn split(self, byte: u8) -> Split<Self> where Self: Sized { Split::new(self, byte) } } #[cfg(test)] mod tests { use std::io; use {Read, BufRead}; #[test] fn read_until() { let mut buf = io::Cursor::new(&b"12"[..]); let mut v = Vec::new(); assert_eq!(buf.read_until(b'3', &mut v).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); assert_eq!(v, b"12"); let mut buf = io::Cursor::new(&b"1233"[..]); let mut v = Vec::new(); buf.read_until(b'3', &mut v).unwrap(); assert_eq!(v, b"123"); v.truncate(0); buf.read_until(b'3', &mut v).unwrap(); assert_eq!(v, b"3"); v.truncate(0); assert_eq!(buf.read_until(b'3', &mut v).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); assert_eq!(v, b""); } #[test] fn read_to_end() { let mut c = io::Cursor::new(&b""[..]); let mut v = Vec::new(); c.read_to_end(&mut v).unwrap(); assert_eq!(v, b""); let mut c = io::Cursor::new(&b"1"[..]); let mut v = Vec::new(); c.read_to_end(&mut v).unwrap(); assert_eq!(v, b"1"); let cap = 1024 * 1024; let data = (0..cap).map(|i| (i / 3) as u8).collect::<Vec<_>>(); let mut v = Vec::new(); let (a, b) = data.split_at(data.len() / 2); io::Cursor::new(a).read_to_end(&mut v).unwrap(); io::Cursor::new(b).read_to_end(&mut v).unwrap(); assert_eq!(v, data); } #[test] fn read_exact() { let mut buf = [0; 4]; let mut buf = io::Cursor::new(&mut buf[..]); let mut c = io::Cursor::new(&b""[..]); assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); assert_eq!(buf.position(), 0); let mut c = io::Cursor::new(&b"123"[..]).chain(io::Cursor::new(&b"456789"[..])); buf.set_position(0); c.read_exact(&mut buf).unwrap(); assert_eq!(buf.position(), 4); assert_eq!(buf.get_ref(), b"1234"); buf.set_position(0); c.read_exact(&mut buf).unwrap(); assert_eq!(buf.position(), 4); assert_eq!(buf.get_ref(), b"5678"); buf.set_position(0); assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); assert_eq!(buf.position(), 1); } #[test] fn read_exact_slice() { let mut buf = [0; 4]; let mut buf = io::Cursor::new(&mut buf[..]); let mut c = &b""[..]; assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); let mut c = &b"123"[..]; buf.set_position(0); assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); assert_eq!(buf.position(), 3); assert_eq!(buf.get_ref(), b"123\0"); let mut c = &b"1234"[..]; buf.set_position(0); c.read_exact(&mut buf).unwrap(); assert_eq!(buf.position(), 4); assert_eq!(buf.get_ref(), b"1234"); let mut c = &b"56789"[..]; buf.set_position(0); c.read_exact(&mut buf).unwrap(); assert_eq!(buf.position(), 4); assert_eq!(buf.get_ref(), b"5678"); assert_eq!(c, b"9"); } }