cursor.rs - source
Skip to main content core/io/ cursor.rs 1 use crate ::cmp ; 2 use crate ::io::{ self , ErrorKind , IoSlice , SeekFrom , Write }; 3 4 /// A `Cursor` wraps an in-memory buffer and provides it with a 5 /// [`Seek`] implementation. 6 /// 7 /// `Cursor`s are used with in-memory buffers, anything implementing 8 /// <code>[AsRef]<\[u8]></code>, to allow them to implement [`Read`] and/or [`Write`], 9 /// allowing these buffers to be used anywhere you might use a reader or writer 10 /// that does actual I/O.
11 /// 12 /// The standard library implements some I/O traits on various types which 13 /// are commonly used as a buffer, like <code>Cursor<[Vec]\<u8>></code> and 14 /// <code>Cursor<[&\[u8\]][bytes]></code>. 15 /// 16 /// # Examples 17 /// 18 /// We may want to write bytes to a [`File`] in our production 19 /// code, but use an in-memory buffer in our tests. We can do this with 20 /// `Cursor`: 21 /// 22 // FIXME(#74481): Hard-links required to link from `core` to `std` 23 /// [bytes]: crate::slice "slice" 24 /// [`File`]: ../../std/fs/struct.File.html 25 /// [`Read`]: ../../std/io/trait.Read.html 26 /// [`Write`]: crate::io::Write 27 /// [`Seek`]: crate::io::Seek 28 /// [Vec]: ../../alloc/vec/struct.Vec.html 29 /// 30 /// ```no_run 31 /// use std::io::prelude::*; 32 /// use std::io::{self, SeekFrom}; 33 /// use std::fs::File; 34 /// 35 /// // a library function we've written 36 /// fn write_ten_bytes_at_end<W: Write + Seek>(mut writer: W) -> io::Result<()> { 37 /// writer.seek(SeekFrom::End(-10))?; 38 /// 39 /// for i in 0..10 { 40 /// writer.write(&[i])?; 41 /// } 42 /// 43 /// // all went well 44 /// Ok(()) 45 /// } 46 /// 47 /// # fn foo() -> io::Result<()> { 48 /// // Here's some code that uses this library function.
49 /// // 50 /// // We might want to use a BufReader here for efficiency, but let's 51 /// // keep this example focused. 52 /// let mut file = File::create("foo.txt")?; 53 /// // First, we need to allocate 10 bytes to be able to write into. 54 /// file.set_len(10)?; 55 /// 56 /// write_ten_bytes_at_end(&mut file)?; 57 /// # Ok(()) 58 /// # } 59 /// 60 /// // now let's write a test 61 /// #[test] 62 /// fn test_writes_bytes() { 63 /// // setting up a real File is much slower than an in-memory buffer, 64 /// // let's use a cursor instead 65 /// use std::io::Cursor; 66 /// let mut buff = Cursor::new(vec![0; 15]); 67 /// 68 /// write_ten_bytes_at_end(&mut buff).unwrap(); 69 /// 70 /// assert_eq!(&buff.get_ref()[5..15], &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); 71 /// } 72 /// ``` 73 #[stable(feature = "rust1" , since = "1.0.0" )] 74 #[derive( Debug , Default , Eq , PartialEq )] 75 pub struct Cursor <T> { 76 inner: T, 77 pos: u64 , 78 } 79 80 impl <T> Cursor <T> { 81 /// Creates a new cursor wrapping the provided underlying in-memory buffer.
82 /// 83 /// Cursor initial position is `0` even if underlying buffer (e.g., [`Vec`]) 84 /// is not empty. So writing to cursor starts with overwriting [`Vec`] 85 /// content, not with appending to it. 86 /// 87 // FIXME(#74481): Hard-links required to link from `core` to `alloc` 88 /// [`Vec`]: ../../alloc/vec/struct.Vec.html 89 /// 90 /// # Examples 91 /// 92 /// ``` 93 /// use std::io::Cursor; 94 /// 95 /// let buff = Cursor::new(Vec::new()); 96 /// # fn force_inference(_: &Cursor<Vec<u8>>) {} 97 /// # force_inference(&buff); 98 /// ``` 99 #[stable(feature = "rust1" , since = "1.0.0" )] 100 #[rustc_const_stable(feature = "const_io_structs" , since = "1.79.0" )] 101 pub const fn new(inner: T) -> Cursor <T> { 102 Cursor { pos: 0 , inner } 103 } 104 105 /// Consumes this cursor, returning the underlying value.
106 /// 107 /// # Examples 108 /// 109 /// ``` 110 /// use std::io::Cursor; 111 /// 112 /// let buff = Cursor::new(Vec::new()); 113 /// # fn force_inference(_: &Cursor<Vec<u8>>) {} 114 /// # force_inference(&buff); 115 /// 116 /// let vec = buff.into_inner(); 117 /// ``` 118 #[stable(feature = "rust1" , since = "1.0.0" )] 119 pub fn into_inner( self ) -> T { 120 self .inner 121 } 122 123 /// Gets a reference to the underlying value in this cursor.
124 /// 125 /// # Examples 126 /// 127 /// ``` 128 /// use std::io::Cursor; 129 /// 130 /// let buff = Cursor::new(Vec::new()); 131 /// # fn force_inference(_: &Cursor<Vec<u8>>) {} 132 /// # force_inference(&buff); 133 /// 134 /// let reference = buff.get_ref(); 135 /// ``` 136 #[stable(feature = "rust1" , since = "1.0.0" )] 137 #[rustc_const_stable(feature = "const_io_structs" , since = "1.79.0" )] 138 pub const fn get_ref( & self ) -> & T { 139 & self .inner 140 } 141 142 /// Gets a mutable reference to the underlying value in this cursor.
143 /// 144 /// Care should be taken to avoid modifying the internal I/O state of the 145 /// underlying value as it may corrupt this cursor's position. 146 /// 147 /// # Examples 148 /// 149 /// ``` 150 /// use std::io::Cursor; 151 /// 152 /// let mut buff = Cursor::new(Vec::new()); 153 /// # fn force_inference(_: &Cursor<Vec<u8>>) {} 154 /// # force_inference(&buff); 155 /// 156 /// let reference = buff.get_mut(); 157 /// ``` 158 #[stable(feature = "rust1" , since = "1.0.0" )] 159 #[rustc_const_stable(feature = "const_mut_cursor" , since = "1.86.0" )] 160 pub const fn get_mut( &mut self ) -> &mut T { 161 &mut self .inner 162 } 163 164 /// Returns the current position of this cursor.
165 /// 166 /// # Examples 167 /// 168 /// ``` 169 /// use std::io::Cursor; 170 /// use std::io::prelude::*; 171 /// use std::io::SeekFrom; 172 /// 173 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); 174 /// 175 /// assert_eq!(buff.position(), 0); 176 /// 177 /// buff.seek(SeekFrom::Current(2)).unwrap(); 178 /// assert_eq!(buff.position(), 2); 179 /// 180 /// buff.seek(SeekFrom::Current(-1)).unwrap(); 181 /// assert_eq!(buff.position(), 1); 182 /// ``` 183 #[stable(feature = "rust1" , since = "1.0.0" )] 184 #[rustc_const_stable(feature = "const_io_structs" , since = "1.79.0" )] 185 pub const fn position( & self ) -> u64 { 186 self .pos 187 } 188 189 /// Sets the position of this cursor.
190 /// 191 /// # Examples 192 /// 193 /// ``` 194 /// use std::io::Cursor; 195 /// 196 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); 197 /// 198 /// assert_eq!(buff.position(), 0); 199 /// 200 /// buff.set_position(2); 201 /// assert_eq!(buff.position(), 2); 202 /// 203 /// buff.set_position(4); 204 /// assert_eq!(buff.position(), 4); 205 /// ``` 206 #[stable(feature = "rust1" , since = "1.0.0" )] 207 #[rustc_const_stable(feature = "const_mut_cursor" , since = "1.86.0" )] 208 pub const fn set_position( &mut self , pos: u64 ) { 209 self .pos = pos ; 210 } 211 212 #[doc(hidden)] 213 #[unstable(feature = "core_io_internals" , reason = "exposed only for libstd" , issue = "none" )] 214 #[inline] 215 pub const fn into_parts_mut( &mut self ) -> ( &mut u64 , &mut T) { 216 ( &mut self .pos, &mut self .inner) 217 } 218 } 219 220 impl <T> Cursor <T> 221 where 222 T: AsRef <[ u8 ]>, 223 { 224 /// Splits the underlying slice at the cursor position and returns them.
225 /// 226 /// # Examples 227 /// 228 /// ``` 229 /// #![feature(cursor_split)] 230 /// use std::io::Cursor; 231 /// 232 /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); 233 /// 234 /// assert_eq!(buff.split(), ([].as_slice(), [1, 2, 3, 4, 5].as_slice())); 235 /// 236 /// buff.set_position(2); 237 /// assert_eq!(buff.split(), ([1, 2].as_slice(), [3, 4, 5].as_slice())); 238 /// 239 /// buff.set_position(6); 240 /// assert_eq!(buff.split(), ([1, 2, 3, 4, 5].as_slice(), [].as_slice())); 241 /// ``` 242 #[unstable(feature = "cursor_split" , issue = "86369" )] 243 pub fn split( & self ) -> ( & [ u8 ], & [ u8 ]) { 244 let slice = self .inner. as_ref (); 245 let pos = self .pos. min ( slice . len () as u64 ); 246 slice . split_at ( pos as usize ) 247 } 248 } 249 250 impl <T> Cursor <T> 251 where 252 T: AsMut <[ u8 ]>, 253 { 254 /// Splits the underlying slice at the cursor position and returns them 255 /// mutably.
256 /// 257 /// # Examples 258 /// 259 /// ``` 260 /// #![feature(cursor_split)] 261 /
The rest of this page is on the live site.