2015-11-01 18 views
7

入力ファイルのランダムな場所からデータを取り出し、順次出力ファイルに出力したいと考えています。好ましくは、不要な割り当ては不要である。イディオム/効率的にデータを読み込み+シークからパイプライトする方法は?

This is one kind of solution I have figured out

use std::io::{ self, SeekFrom, Cursor, Read, Write, Seek }; 

#[test] 
fn read_write() { 
    // let's say this is input file 
    let mut input_file = Cursor::new(b"worldhello"); 
    // and this is output file 
    let mut output_file = Vec::<u8>::new(); 

    assemble(&mut input_file, &mut output_file).unwrap(); 

    assert_eq!(b"helloworld", &output_file[..]); 
} 

// I want to take data from random locations in input file 
// and output them sequentially to output file 
pub fn assemble<I, O>(input: &mut I, output: &mut O) -> Result<(), io::Error> 
    where I: Read + Seek, O: Write 
{ 
    // first seek and output "hello" 
    try!(input.seek(SeekFrom::Start(5))); 
    let mut hello_buf = [0u8; 5]; 
    try!(input.take(5).read(&mut hello_buf)); 
    try!(output.write(&hello_buf)); 

    // then output "world" 
    try!(input.seek(SeekFrom::Start(0))); 
    let mut world_buf = [0u8; 5]; 
    try!(input.take(5).read(&mut world_buf)); 
    try!(output.write(&world_buf)); 

    Ok(()) 
} 

のは、ここにI/Oレイテンシーを心配しないようにしましょう。

質問:

  1. 安定した錆は、1つのストリームからxバイトを取り、別のストリームにプッシュするためにいくつかのヘルパーを持っていますか?それとも、自分自身をロールバックする必要がありますか?
  2. 私が自分のロールをしなければならない場合は、おそらくもっと良い方法がありますか?
+2

関連性がありません: ' 'を使用するようにアセンブルを変更し、より一般的です(特性オブジェクトを許可します)。 – bluss

答えて

4

あなたはio::copyを探しています:

pub fn assemble<I, O>(input: &mut I, output: &mut O) -> Result<(), io::Error> 
    where I: Read + Seek, O: Write 
{ 
    // first seek and output "hello" 
    try!(input.seek(SeekFrom::Start(5))); 
    try!(io::copy(&mut input.take(5), output)); 

    // then output "world" 
    try!(input.seek(SeekFrom::Start(0))); 
    try!(io::copy(&mut input.take(5), output)); 

    Ok(()) 
} 

あなたはthe implementation of io::copyを見れば、あなたはそれがあなたのコードに似ていることがわかります。しかし、それはより多くのエラーケースを処理するために世話をする:

  1. writeはない常にあなたがそれを聞いて、すべてを書きません!
  2. "中断"書き込みは通常致命的ではありません。

また、より大きなバッファサイズを使用しますが、それでもスタック割り当てを行います。

関連する問題