2015-11-01 13 views
7

Giriş dosyasındaki rastgele konumlardan veri almak ve bunları çıkış dosyasına sırayla göndermek istiyorum. Tercihen, gereksiz tahsisler olmadan. Verileri + Yazmaya + Yazmaya?

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(()) 
} 

en/Ç gecikme burada I dert etmeyelim.

Sorular:

  1. istikrarlı Pas x bayt akıştan alıp başka akışa onları itmek için bazı yardımcı var mı? Yoksa kendi başıma mı dönmeliyim?
  2. Kendi başıma dönmem gerekirse, belki daha iyi bir yol var mı?
+2

İlişkisiz: ' 'komutunu kullanmak için birleşim oluşturun ve daha geneldir (özellik nesnelere izin verir). – bluss

cevap

4

Sen io::copy arıyoruz: Eğer the implementation of io::copy bakarsak, bu uygulamanın koduna benzer olduğunu görebilirsiniz

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(()) 
} 

. Ancak, daha fazla hata davalarına bakacak ilgilenir:

  1. write her zaman bunu sormak her şeyi yazmayınyapar!
  2. Bir "kesilen" yazma genellikle ölümcül değildir.

Ayrıca, daha büyük bir arabellek boyutu kullanır, ancak yine de yığına ayırır.

İlgili konular