本文簡要介紹rust語言中 Struct std::io::Cursor
的用法。
用法
pub struct Cursor<T> { /* fields omitted */ }
Cursor
包裝內存緩衝區並為其提供 Seek
實現。
Cursor
與內存緩衝區(任何實現 AsRef<[u8]>
的東西)一起使用,以允許它們實現 Read
和/或 Write
,允許這些緩衝區在您可能使用實際執行操作的讀取器或寫入器的任何地方使用輸入/輸出。
標準庫在通常用作緩衝區的各種類型上實現了一些 I/O 特征,例如 Cursor<Vec<u8>>
和 Cursor<&[u8]>
。
例子
我們可能想在生產代碼中將字節寫入 File
,但在測試中使用內存緩衝區。我們可以使用 Cursor
來做到這一點:
use std::io::prelude::*;
use std::io::{self, SeekFrom};
use std::fs::File;
// a library function we've written
fn write_ten_bytes_at_end<W: Write + Seek>(writer: &mut W) -> io::Result<()> {
writer.seek(SeekFrom::End(-10))?;
for i in 0..10 {
writer.write(&[i])?;
}
// all went well
Ok(())
}
// Here's some code that uses this library function.
//
// We might want to use a BufReader here for efficiency, but let's
// keep this example focused.
let mut file = File::create("foo.txt")?;
write_ten_bytes_at_end(&mut file)?;
// now let's write a test
#[test]
fn test_writes_bytes() {
// setting up a real File is much slower than an in-memory buffer,
// let's use a cursor instead
use std::io::Cursor;
let mut buff = Cursor::new(vec![0; 15]);
write_ten_bytes_at_end(&mut buff).unwrap();
assert_eq!(&buff.get_ref()[5..15], &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
}
相關用法
- Rust Cursor.new用法及代碼示例
- Rust Cursor.remaining_slice用法及代碼示例
- Rust Cursor.position用法及代碼示例
- Rust CursorMut.back_mut用法及代碼示例
- Rust Cursor.set_position用法及代碼示例
- Rust Cursor.get_ref用法及代碼示例
- Rust Cursor.get_mut用法及代碼示例
- Rust Cursor.is_empty用法及代碼示例
- Rust Cursor.into_inner用法及代碼示例
- Rust CStr.into_c_string用法及代碼示例
- Rust Condvar.notify_all用法及代碼示例
- Rust Command.args用法及代碼示例
- Rust Condvar.wait用法及代碼示例
- Rust Chars.as_str用法及代碼示例
- Rust CString.into_bytes用法及代碼示例
- Rust CStr.from_bytes_with_nul用法及代碼示例
- Rust Cow.is_owned用法及代碼示例
- Rust Cow用法及代碼示例
- Rust Condvar.wait_timeout用法及代碼示例
- Rust Condvar.wait_timeout_while用法及代碼示例
- Rust Command.env用法及代碼示例
- Rust CStr.from_bytes_with_nul_unchecked用法及代碼示例
- Rust Command.env_remove用法及代碼示例
- Rust Child用法及代碼示例
- Rust Command.get_args用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Struct std::io::Cursor。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。