1 // Copyright 2015 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.
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.
15 use io::{self, SeekFrom, Error, ErrorKind};
17 /// A `Cursor` wraps another type and provides it with a
18 /// [`Seek`](trait.Seek.html) implementation.
20 /// Cursors are typically used with in-memory buffers to allow them to
21 /// implement `Read` and/or `Write`, allowing these buffers to be used
22 /// anywhere you might use a reader or writer that does actual I/O.
24 /// The standard library implements some I/O traits on various types which
25 /// are commonly used as a buffer, like `Cursor<Vec<u8>>` and `Cursor<&[u8]>`.
29 /// We may want to write bytes to a [`File`][file] in our production
30 /// code, but use an in-memory buffer in our tests. We can do this with
33 /// [file]: ../fs/struct.File.html
36 /// use std::io::prelude::*;
37 /// use std::io::{self, SeekFrom};
38 /// use std::fs::File;
40 /// // a library function we've written
41 /// fn write_ten_bytes_at_end<W: Write + Seek>(writer: &mut W) -> io::Result<()> {
42 /// try!(writer.seek(SeekFrom::End(-10)));
45 /// try!(writer.write(&[i]));
52 /// # fn foo() -> io::Result<()> {
53 /// // Here's some code that uses this library function.
55 /// // We might want to use a BufReader here for efficiency, but let's
56 /// // keep this example focused.
57 /// let mut file = try!(File::create("foo.txt"));
59 /// try!(write_ten_bytes_at_end(&mut file));
63 /// // now let's write a test
65 /// fn test_writes_bytes() {
66 /// // setting up a real File is much more slow than an in-memory buffer,
67 /// // let's use a cursor instead
68 /// use std::io::Cursor;
69 /// let mut buff = Cursor::new(vec![0; 15]);
71 /// write_ten_bytes_at_end(&mut buff).unwrap();
73 /// assert_eq!(&buff.get_ref()[5..15], &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
76 #[stable(feature = "rust1", since = "1.0.0")]
77 #[derive(Clone, Debug)]
78 pub struct Cursor<T> {
84 /// Creates a new cursor wrapping the provided underlying I/O object.
89 /// use std::io::Cursor;
91 /// let buff = Cursor::new(Vec::new());
92 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
93 /// # force_inference(&buff);
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub fn new(inner: T) -> Cursor<T> {
97 Cursor { pos: 0, inner: inner }
100 /// Consumes this cursor, returning the underlying value.
105 /// use std::io::Cursor;
107 /// let buff = Cursor::new(Vec::new());
108 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
109 /// # force_inference(&buff);
111 /// let vec = buff.into_inner();
113 #[stable(feature = "rust1", since = "1.0.0")]
114 pub fn into_inner(self) -> T { self.inner }
116 /// Gets a reference to the underlying value in this cursor.
121 /// use std::io::Cursor;
123 /// let buff = Cursor::new(Vec::new());
124 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
125 /// # force_inference(&buff);
127 /// let reference = buff.get_ref();
129 #[stable(feature = "rust1", since = "1.0.0")]
130 pub fn get_ref(&self) -> &T { &self.inner }
132 /// Gets a mutable reference to the underlying value in this cursor.
134 /// Care should be taken to avoid modifying the internal I/O state of the
135 /// underlying value as it may corrupt this cursor's position.
140 /// use std::io::Cursor;
142 /// let mut buff = Cursor::new(Vec::new());
143 /// # fn force_inference(_: &Cursor<Vec<u8>>) {}
144 /// # force_inference(&buff);
146 /// let reference = buff.get_mut();
148 #[stable(feature = "rust1", since = "1.0.0")]
149 pub fn get_mut(&mut self) -> &mut T { &mut self.inner }
151 /// Returns the current position of this cursor.
156 /// use std::io::Cursor;
157 /// use std::io::prelude::*;
158 /// use std::io::SeekFrom;
160 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
162 /// assert_eq!(buff.position(), 0);
164 /// buff.seek(SeekFrom::Current(2)).unwrap();
165 /// assert_eq!(buff.position(), 2);
167 /// buff.seek(SeekFrom::Current(-1)).unwrap();
168 /// assert_eq!(buff.position(), 1);
170 #[stable(feature = "rust1", since = "1.0.0")]
171 pub fn position(&self) -> u64 { self.pos }
173 /// Sets the position of this cursor.
178 /// use std::io::Cursor;
180 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
182 /// assert_eq!(buff.position(), 0);
184 /// buff.set_position(2);
185 /// assert_eq!(buff.position(), 2);
187 /// buff.set_position(4);
188 /// assert_eq!(buff.position(), 4);
190 #[stable(feature = "rust1", since = "1.0.0")]
191 pub fn set_position(&mut self, pos: u64) { self.pos = pos; }
194 #[stable(feature = "rust1", since = "1.0.0")]
195 impl<T> io::Seek for Cursor<T> where T: AsRef<[u8]> {
196 fn seek(&mut self, style: SeekFrom) -> io::Result<u64> {
197 let pos = match style {
198 SeekFrom::Start(n) => { self.pos = n; return Ok(n) }
199 SeekFrom::End(n) => self.inner.as_ref().len() as i64 + n,
200 SeekFrom::Current(n) => self.pos as i64 + n,
204 Err(Error::new(ErrorKind::InvalidInput,
205 "invalid seek to a negative position"))
207 self.pos = pos as u64;
213 #[stable(feature = "rust1", since = "1.0.0")]
214 impl<T> Read for Cursor<T> where T: AsRef<[u8]> {
215 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
216 let n = try!(Read::read(&mut try!(self.fill_buf()), buf));
217 self.pos += n as u64;
222 #[stable(feature = "rust1", since = "1.0.0")]
223 impl<T> BufRead for Cursor<T> where T: AsRef<[u8]> {
224 fn fill_buf(&mut self) -> io::Result<&[u8]> {
225 let amt = cmp::min(self.pos, self.inner.as_ref().len() as u64);
226 Ok(&self.inner.as_ref()[(amt as usize)..])
228 fn consume(&mut self, amt: usize) { self.pos += amt as u64; }
231 #[stable(feature = "rust1", since = "1.0.0")]
232 impl<'a> Write for Cursor<&'a mut [u8]> {
233 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
234 let pos = cmp::min(self.pos, self.inner.len() as u64);
235 let amt = try!((&mut self.inner[(pos as usize)..]).write(data));
236 self.pos += amt as u64;
239 fn flush(&mut self) -> io::Result<()> { Ok(()) }
242 #[stable(feature = "rust1", since = "1.0.0")]
243 impl Write for Cursor<Vec<u8>> {
244 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
245 // Make sure the internal buffer is as least as big as where we
247 let pos = self.position();
248 let amt = pos.saturating_sub(self.inner.len() as u64);
249 // use `resize` so that the zero filling is as efficient as possible
250 let len = self.inner.len();
251 self.inner.resize(len + amt as usize, 0);
253 // Figure out what bytes will be used to overwrite what's currently
254 // there (left), and what will be appended on the end (right)
256 let pos = pos as usize;
257 let space = self.inner.len() - pos;
258 let (left, right) = buf.split_at(cmp::min(space, buf.len()));
259 self.inner[pos..pos + left.len()].copy_from_slice(left);
260 self.inner.extend_from_slice(right);
264 self.set_position(pos + buf.len() as u64);
267 fn flush(&mut self) -> io::Result<()> { Ok(()) }
270 #[stable(feature = "cursor_box_slice", since = "1.5.0")]
271 impl Write for Cursor<Box<[u8]>> {
272 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
273 let pos = cmp::min(self.pos, self.inner.len() as u64);
274 let amt = try!((&mut self.inner[(pos as usize)..]).write(buf));
275 self.pos += amt as u64;
278 fn flush(&mut self) -> io::Result<()> { Ok(()) }
284 use io::{Cursor, SeekFrom};
288 fn test_vec_writer() {
289 let mut writer = Vec::new();
290 assert_eq!(writer.write(&[0]).unwrap(), 1);
291 assert_eq!(writer.write(&[1, 2, 3]).unwrap(), 3);
292 assert_eq!(writer.write(&[4, 5, 6, 7]).unwrap(), 4);
293 let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
294 assert_eq!(writer, b);
298 fn test_mem_writer() {
299 let mut writer = Cursor::new(Vec::new());
300 assert_eq!(writer.write(&[0]).unwrap(), 1);
301 assert_eq!(writer.write(&[1, 2, 3]).unwrap(), 3);
302 assert_eq!(writer.write(&[4, 5, 6, 7]).unwrap(), 4);
303 let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
304 assert_eq!(&writer.get_ref()[..], b);
308 fn test_box_slice_writer() {
309 let mut writer = Cursor::new(vec![0u8; 9].into_boxed_slice());
310 assert_eq!(writer.position(), 0);
311 assert_eq!(writer.write(&[0]).unwrap(), 1);
312 assert_eq!(writer.position(), 1);
313 assert_eq!(writer.write(&[1, 2, 3]).unwrap(), 3);
314 assert_eq!(writer.write(&[4, 5, 6, 7]).unwrap(), 4);
315 assert_eq!(writer.position(), 8);
316 assert_eq!(writer.write(&[]).unwrap(), 0);
317 assert_eq!(writer.position(), 8);
319 assert_eq!(writer.write(&[8, 9]).unwrap(), 1);
320 assert_eq!(writer.write(&[10]).unwrap(), 0);
321 let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8];
322 assert_eq!(&**writer.get_ref(), b);
326 fn test_buf_writer() {
327 let mut buf = [0 as u8; 9];
329 let mut writer = Cursor::new(&mut buf[..]);
330 assert_eq!(writer.position(), 0);
331 assert_eq!(writer.write(&[0]).unwrap(), 1);
332 assert_eq!(writer.position(), 1);
333 assert_eq!(writer.write(&[1, 2, 3]).unwrap(), 3);
334 assert_eq!(writer.write(&[4, 5, 6, 7]).unwrap(), 4);
335 assert_eq!(writer.position(), 8);
336 assert_eq!(writer.write(&[]).unwrap(), 0);
337 assert_eq!(writer.position(), 8);
339 assert_eq!(writer.write(&[8, 9]).unwrap(), 1);
340 assert_eq!(writer.write(&[10]).unwrap(), 0);
342 let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8];
347 fn test_buf_writer_seek() {
348 let mut buf = [0 as u8; 8];
350 let mut writer = Cursor::new(&mut buf[..]);
351 assert_eq!(writer.position(), 0);
352 assert_eq!(writer.write(&[1]).unwrap(), 1);
353 assert_eq!(writer.position(), 1);
355 assert_eq!(writer.seek(SeekFrom::Start(2)).unwrap(), 2);
356 assert_eq!(writer.position(), 2);
357 assert_eq!(writer.write(&[2]).unwrap(), 1);
358 assert_eq!(writer.position(), 3);
360 assert_eq!(writer.seek(SeekFrom::Current(-2)).unwrap(), 1);
361 assert_eq!(writer.position(), 1);
362 assert_eq!(writer.write(&[3]).unwrap(), 1);
363 assert_eq!(writer.position(), 2);
365 assert_eq!(writer.seek(SeekFrom::End(-1)).unwrap(), 7);
366 assert_eq!(writer.position(), 7);
367 assert_eq!(writer.write(&[4]).unwrap(), 1);
368 assert_eq!(writer.position(), 8);
371 let b: &[_] = &[1, 3, 2, 0, 0, 0, 0, 4];
376 fn test_buf_writer_error() {
377 let mut buf = [0 as u8; 2];
378 let mut writer = Cursor::new(&mut buf[..]);
379 assert_eq!(writer.write(&[0]).unwrap(), 1);
380 assert_eq!(writer.write(&[0, 0]).unwrap(), 1);
381 assert_eq!(writer.write(&[0, 0]).unwrap(), 0);
385 fn test_mem_reader() {
386 let mut reader = Cursor::new(vec!(0, 1, 2, 3, 4, 5, 6, 7));
388 assert_eq!(reader.read(&mut buf).unwrap(), 0);
389 assert_eq!(reader.position(), 0);
391 assert_eq!(reader.read(&mut buf).unwrap(), 1);
392 assert_eq!(reader.position(), 1);
395 let mut buf = [0; 4];
396 assert_eq!(reader.read(&mut buf).unwrap(), 4);
397 assert_eq!(reader.position(), 5);
398 let b: &[_] = &[1, 2, 3, 4];
400 assert_eq!(reader.read(&mut buf).unwrap(), 3);
401 let b: &[_] = &[5, 6, 7];
402 assert_eq!(&buf[..3], b);
403 assert_eq!(reader.read(&mut buf).unwrap(), 0);
407 fn test_boxed_slice_reader() {
408 let mut reader = Cursor::new(vec!(0, 1, 2, 3, 4, 5, 6, 7).into_boxed_slice());
410 assert_eq!(reader.read(&mut buf).unwrap(), 0);
411 assert_eq!(reader.position(), 0);
413 assert_eq!(reader.read(&mut buf).unwrap(), 1);
414 assert_eq!(reader.position(), 1);
417 let mut buf = [0; 4];
418 assert_eq!(reader.read(&mut buf).unwrap(), 4);
419 assert_eq!(reader.position(), 5);
420 let b: &[_] = &[1, 2, 3, 4];
422 assert_eq!(reader.read(&mut buf).unwrap(), 3);
423 let b: &[_] = &[5, 6, 7];
424 assert_eq!(&buf[..3], b);
425 assert_eq!(reader.read(&mut buf).unwrap(), 0);
430 let mut reader = Cursor::new(vec!(0, 1, 2, 3, 4, 5, 6, 7));
431 let mut v = Vec::new();
432 reader.read_to_end(&mut v).unwrap();
433 assert_eq!(v, [0, 1, 2, 3, 4, 5, 6, 7]);
437 fn test_slice_reader() {
438 let in_buf = vec![0, 1, 2, 3, 4, 5, 6, 7];
439 let mut reader = &mut &in_buf[..];
441 assert_eq!(reader.read(&mut buf).unwrap(), 0);
443 assert_eq!(reader.read(&mut buf).unwrap(), 1);
444 assert_eq!(reader.len(), 7);
446 assert_eq!(&buf[..], b);
447 let mut buf = [0; 4];
448 assert_eq!(reader.read(&mut buf).unwrap(), 4);
449 assert_eq!(reader.len(), 3);
450 let b: &[_] = &[1, 2, 3, 4];
451 assert_eq!(&buf[..], b);
452 assert_eq!(reader.read(&mut buf).unwrap(), 3);
453 let b: &[_] = &[5, 6, 7];
454 assert_eq!(&buf[..3], b);
455 assert_eq!(reader.read(&mut buf).unwrap(), 0);
459 fn test_buf_reader() {
460 let in_buf = vec![0, 1, 2, 3, 4, 5, 6, 7];
461 let mut reader = Cursor::new(&in_buf[..]);
463 assert_eq!(reader.read(&mut buf).unwrap(), 0);
464 assert_eq!(reader.position(), 0);
466 assert_eq!(reader.read(&mut buf).unwrap(), 1);
467 assert_eq!(reader.position(), 1);
470 let mut buf = [0; 4];
471 assert_eq!(reader.read(&mut buf).unwrap(), 4);
472 assert_eq!(reader.position(), 5);
473 let b: &[_] = &[1, 2, 3, 4];
475 assert_eq!(reader.read(&mut buf).unwrap(), 3);
476 let b: &[_] = &[5, 6, 7];
477 assert_eq!(&buf[..3], b);
478 assert_eq!(reader.read(&mut buf).unwrap(), 0);
482 fn test_read_char() {
483 let b = &b"Vi\xE1\xBB\x87t"[..];
484 let mut c = Cursor::new(b).chars();
485 assert_eq!(c.next().unwrap().unwrap(), 'V');
486 assert_eq!(c.next().unwrap().unwrap(), 'i');
487 assert_eq!(c.next().unwrap().unwrap(), 'ệ');
488 assert_eq!(c.next().unwrap().unwrap(), 't');
489 assert!(c.next().is_none());
493 fn test_read_bad_char() {
494 let b = &b"\x80"[..];
495 let mut c = Cursor::new(b).chars();
496 assert!(c.next().unwrap().is_err());
502 let mut r = Cursor::new(&buf[..]);
503 assert_eq!(r.seek(SeekFrom::Start(10)).unwrap(), 10);
504 assert_eq!(r.read(&mut [0]).unwrap(), 0);
506 let mut r = Cursor::new(vec!(10));
507 assert_eq!(r.seek(SeekFrom::Start(10)).unwrap(), 10);
508 assert_eq!(r.read(&mut [0]).unwrap(), 0);
511 let mut r = Cursor::new(&mut buf[..]);
512 assert_eq!(r.seek(SeekFrom::Start(10)).unwrap(), 10);
513 assert_eq!(r.write(&[3]).unwrap(), 0);
515 let mut r = Cursor::new(vec![10].into_boxed_slice());
516 assert_eq!(r.seek(SeekFrom::Start(10)).unwrap(), 10);
517 assert_eq!(r.write(&[3]).unwrap(), 0);
523 let mut r = Cursor::new(&buf[..]);
524 assert!(r.seek(SeekFrom::End(-2)).is_err());
526 let mut r = Cursor::new(vec!(10));
527 assert!(r.seek(SeekFrom::End(-2)).is_err());
530 let mut r = Cursor::new(&mut buf[..]);
531 assert!(r.seek(SeekFrom::End(-2)).is_err());
533 let mut r = Cursor::new(vec!(10).into_boxed_slice());
534 assert!(r.seek(SeekFrom::End(-2)).is_err());
538 fn test_seekable_mem_writer() {
539 let mut writer = Cursor::new(Vec::<u8>::new());
540 assert_eq!(writer.position(), 0);
541 assert_eq!(writer.write(&[0]).unwrap(), 1);
542 assert_eq!(writer.position(), 1);
543 assert_eq!(writer.write(&[1, 2, 3]).unwrap(), 3);
544 assert_eq!(writer.write(&[4, 5, 6, 7]).unwrap(), 4);
545 assert_eq!(writer.position(), 8);
546 let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
547 assert_eq!(&writer.get_ref()[..], b);
549 assert_eq!(writer.seek(SeekFrom::Start(0)).unwrap(), 0);
550 assert_eq!(writer.position(), 0);
551 assert_eq!(writer.write(&[3, 4]).unwrap(), 2);
552 let b: &[_] = &[3, 4, 2, 3, 4, 5, 6, 7];
553 assert_eq!(&writer.get_ref()[..], b);
555 assert_eq!(writer.seek(SeekFrom::Current(1)).unwrap(), 3);
556 assert_eq!(writer.write(&[0, 1]).unwrap(), 2);
557 let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7];
558 assert_eq!(&writer.get_ref()[..], b);
560 assert_eq!(writer.seek(SeekFrom::End(-1)).unwrap(), 7);
561 assert_eq!(writer.write(&[1, 2]).unwrap(), 2);
562 let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2];
563 assert_eq!(&writer.get_ref()[..], b);
565 assert_eq!(writer.seek(SeekFrom::End(1)).unwrap(), 10);
566 assert_eq!(writer.write(&[1]).unwrap(), 1);
567 let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2, 0, 1];
568 assert_eq!(&writer.get_ref()[..], b);
572 fn vec_seek_past_end() {
573 let mut r = Cursor::new(Vec::new());
574 assert_eq!(r.seek(SeekFrom::Start(10)).unwrap(), 10);
575 assert_eq!(r.write(&[3]).unwrap(), 1);
579 fn vec_seek_before_0() {
580 let mut r = Cursor::new(Vec::new());
581 assert!(r.seek(SeekFrom::End(-2)).is_err());