Vec
サポートstd::io::Write
のように、File
またはVec
のコードを書くことができます。 APIリファレンスから、Vec
とスライスのいずれもサポートされていないようです(std::io::Read
)。Vecまたはスライスから(std :: io :: Read)を読むには?
これを実現する便利な方法はありますか?それはラッパー構造体を書く必要がありますか?
ここでは、ファイルを読み書きするワーキングコードの例を示します.1行のコメントでベクトルを読み込む必要があります。
use ::std::io;
// Generic IO
fn write_4_bytes<W>(mut file: W) -> Result<usize, io::Error>
where W: io::Write,
{
let len = file.write(b"1234")?;
Ok(len)
}
fn read_4_bytes<R>(mut file: R) -> Result<[u8; 4], io::Error>
where R: io::Read,
{
let mut buf: [u8; 4] = [0; 4];
file.read(&mut buf)?;
Ok(buf)
}
// Type specific
fn write_read_vec() {
let mut vec_as_file: Vec<u8> = Vec::new();
{ // Write
println!("Writing Vec... {}", write_4_bytes(&mut vec_as_file).unwrap());
}
{ // Read
// println!("Reading File... {:?}", read_4_bytes(&vec_as_file).unwrap());
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Comment this line above to avoid an error!
}
}
fn write_read_file() {
let filepath = "temp.txt";
{ // Write
let mut file_as_file = ::std::fs::File::create(filepath).expect("open failed");
println!("Writing File... {}", write_4_bytes(&mut file_as_file).unwrap());
}
{ // Read
let mut file_as_file = ::std::fs::File::open(filepath).expect("open failed");
println!("Reading File... {:?}", read_4_bytes(&mut file_as_file).unwrap());
}
}
fn main() {
write_read_vec();
write_read_file();
}
これはエラーで失敗:
error[E0277]: the trait bound `std::vec::Vec<u8>: std::io::Read` is not satisfied
--> src/main.rs:29:42
|
29 | println!("Reading File... {:?}", read_4_bytes(&vec_as_file).unwrap());
| ^^^^^^^^^^^^ the trait `std::io::Read` is not implemented for `std::vec::Vec<u8>`
|
= note: required by `read_4_bytes`
Iは、ファイルシステムへの書き込みをすることなく、ファイルフォーマットエンコーダ/デコーダのためのテストを作成したいです。
私は自分の答えを削除しました。この質問は現在のところかなり大きく、最初に尋ねられたときよりも多くのcontext_を提供します。 –
@ simon-whitehead、最初は包括的な質問をしてくれなかったことに謝罪しましたが、作業コードの例を必要としなかった欠点がありました。 – ideasman42