Avoid an intermediary buffer in LZMA decoder

This commit is contained in:
Benoît du Garreau 2024-07-12 10:05:42 +02:00
parent e9b13121cc
commit 2e679997b0

View file

@ -1,8 +1,6 @@
use lzma_rs::decompress::{Options, Stream, UnpackedSize}; use lzma_rs::decompress::{Options, Stream, UnpackedSize};
use std::collections::VecDeque; use std::collections::VecDeque;
use std::io::{Read, Result, Write}; use std::io::{BufRead, Read, Result, Write};
const COMPRESSED_BYTES_TO_BUFFER: usize = 4096;
const OPTIONS: Options = Options { const OPTIONS: Options = Options {
unpacked_size: UnpackedSize::ReadFromHeader, unpacked_size: UnpackedSize::ReadFromHeader,
@ -29,17 +27,15 @@ impl<R: Read> LzmaDecoder<R> {
} }
} }
impl<R: Read> Read for LzmaDecoder<R> { impl<R: BufRead> Read for LzmaDecoder<R> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> { fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let mut bytes_read = self.stream.get_output_mut().unwrap().read(buf)?; let mut bytes_read = self.stream.get_output_mut().unwrap().read(buf)?;
while bytes_read < buf.len() { while bytes_read < buf.len() {
let mut next_compressed = [0u8; COMPRESSED_BYTES_TO_BUFFER]; let compressed_bytes = self.compressed_reader.fill_buf()?;
let compressed_bytes_read = self.compressed_reader.read(&mut next_compressed)?; if compressed_bytes.is_empty() {
if compressed_bytes_read == 0 {
break; break;
} }
self.stream self.stream.write_all(compressed_bytes)?;
.write_all(&next_compressed[..compressed_bytes_read])?;
bytes_read += self bytes_read += self
.stream .stream
.get_output_mut() .get_output_mut()