关于rust:直接从文件读取到BufReader或Cursor的基础缓冲区

Directly reading from a file to BufReader's or Cursor's underlying buffer

我试图找出Rust中的一些基本知识。

我想创建一个从文件中读取512字节并将这些字节复制到另一个文件的工具。然后从输入文件中提取下一个8个字节,并跳过它们。然后从输入文件中提取下一个512字节,并将其复制到输出文件,然后跳过8个字节,依此类推...

我需要这个工具要快,所以我不能只是每512个字节执行一次I / O调用。我认为我需要先读取几兆字节的输入文件,然后通过有选择地将其复制到另一个内存块中来删除内存中不需要的8字节块,然后调用I / O写入以将更大的内存块转储到一旦。

所以,我想做这样的事情(伪代码):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let buffer = buffer of 'u8' of size 4MB;
let buffer_out = buffer of 'u8' of size 4MB;

// both buffers above take 8MB of memory

let input_stream = InputStream(buffer);
let output_stream = OutputStream(buffer_out);

for(every 4MB block in the input file) {
    input.read(buffer); // read the 4MB block into 'buffer'
    input_stream.seek(0); // reset the input stream's cursor to offset 0

    for(every 520 byte inside the 4MB block in 'buffer') {
        output_stream.write(input_stream.read(512)); // copy important 512 bytes
        input_stream.read(8);                        // skip superfluous 8 bytes
    }

    output.write(buffer_out);
}

我遇到的Rust中的问题是我试图使用Cursor对象来实现对两个缓冲区的流式访问。例如,我正在像这样在堆上分配缓冲区:

1
let mut buf: Box<[u8; BUF_SIZE]> = Box::new([0; BUF_SIZE]);

然后,我创建一个游标以流模式访问此数组:

1
let mut rd_cursor: Cursor<&[u8]> = Cursor::new(buf.as_slice());

但是,我不知道如何现在从输入文件中读取数据。 bufCursor使用,所以我无法访问它。在C ++中,我只是将数据读取到buf并完成它。而且Cursor似乎没有实现BufReader.read()可以直接使用的任何东西,我用它来从输入文件中读取数据。

也许我可以通过创建另一个缓冲区来使其工作,通过"游标"将数据从"输入"读取到临时缓冲区,从临时缓冲区读取到" buf",但这将导致不断地重新复制内存,我想避免这种情况。

我可以看到Cursor中有一个fill_buf函数,但似乎它仅返回对底层缓冲区的只读引用,因此我无法修改该缓冲区,因此对我的情况无用。

我也尝试使用BufReader而不是Cursor。这是我的第二次尝试:

1
let mut rd_cursor: BufReader<&[u8]> = BufReader::new(&*buf);

BufReader包含get_mut返回R,因此我认为它应该返回&[u8],这听起来不错。但是通过使用&[u8]get_mut抱怨我需要传递一个可变的东西作为R。所以我要像这样更改它:

1
let mut rd_cursor: BufReader<&mut [u8]> = BufReader::new(&mut *buf);

但是Rust不会让我:

1
2
src\\main.rs|88 col 47| 88:61 error: the trait `std::io::Read` is not implemented for the type `[u8]` [E0277]
|| src\\main.rs:88     let mut rd_cursor: BufReader<&mut [u8]> = BufReader::new(&mut *buf);

有人可以打我的头来固定我对这里发生的事情的理解吗?


BufReader已缓冲读取。 引用文档:

Wraps a Read and buffers input from it

It can be excessively inefficient to work directly with a Read instance. For example, every call to read on TcpStream results in a system call. A BufReader performs large, infrequent reads on the underlying Read and maintains an in-memory buffer of the results.

您可以简单地将容量设置为几兆字节,然后以512 + 8字节的读取周期工作。 BufReader仅在用完缓冲区时才进行实际的系统调用。

以下错误

error: the trait std::io::Read is not implemented for the type [u8] [E0277]

是由于事实,锈不知道您想要多少个字节。 [u8]是未调整大小的数组。 我不确定是否可以执行&mut [u8, BUF_SIZE],但是您是否需要遵循这些原则