rust - 如何即时从 hyper::Response 解压缩 XZ 数据?
问题描述
我正在下载一个带有hyper的 XZ 文件,我想通过从每个传入的文件中尽可能多地提取Chunk
并立即将结果写入磁盘,而不是先下载整个文件然后解压缩,从而将其以解压缩的形式保存到磁盘。
有实现 XZ 格式的xz2 crate。但是,它XzDecoder
似乎不支持类似Python 的decompressobj
模型,在这种模型中,调用者反复提供部分输入并获得部分输出。
相反,XzDecoder
通过Read
参数接收输入字节,我不知道如何将这两个东西粘合在一起。有没有办法喂Response
到XzDecoder
?
到目前为止我发现的唯一线索是这个问题,它包含对私有ReadableChunks
类型的引用,理论上我可以在我的代码中复制它 - 但也许有更简单的方法?
解决方案
根据@Laney 的回答,我想出了以下工作代码:
extern crate failure;
extern crate hyper;
extern crate tokio;
extern crate xz2;
use std::fs::File;
use std::io::Write;
use std::u64;
use failure::Error;
use futures::future::done;
use futures::stream::Stream;
use hyper::{Body, Chunk, Response};
use hyper::rt::Future;
use hyper_tls::HttpsConnector;
use tokio::runtime::Runtime;
fn decode_chunk(file: &mut File, xz: &mut xz2::stream::Stream, chunk: &Chunk)
-> Result<(), Error> {
let end = xz.total_in() as usize + chunk.len();
let mut buf = Vec::with_capacity(8192);
while (xz.total_in() as usize) < end {
buf.clear();
xz.process_vec(
&chunk[chunk.len() - (end - xz.total_in() as usize)..],
&mut buf,
xz2::stream::Action::Run)?;
file.write_all(&buf)?;
}
Ok(())
}
fn decode_response(mut file: File, response: Response<Body>)
-> impl Future<Item=(), Error=Error> {
done(xz2::stream::Stream::new_stream_decoder(u64::MAX, 0)
.map_err(Error::from))
.and_then(|mut xz| response
.into_body()
.map_err(Error::from)
.for_each(move |chunk| done(
decode_chunk(&mut file, &mut xz, &chunk))))
}
fn main() -> Result<(), Error> {
let client = hyper::Client::builder().build::<_, hyper::Body>(
HttpsConnector::new(1)?);
let file = File::create("hello-2.7.tar")?;
let mut runtime = Runtime::new()?;
runtime.block_on(client
.get("https://ftp.gnu.org/gnu/hello/hello-2.7.tar.xz".parse()?)
.map_err(Error::from)
.and_then(|response| decode_response(file, response)))?;
runtime.shutdown_now();
Ok(())
}
推荐阅读
- ocaml - 此表达式具有字符串类型,但表达式应为“列表”类型
- pojo - 哪个版本的 H2O gen-model maven 库支持 XGBoost MOJO?
- javascript - 如何在动态构建的 html 中包含 weatherwidget.io
- python - 抓取多个页面时出现重复的 HTTP 错误 413
- cypress - 如何使用 Cypress 监听全球事件?
- haskell - 函数错误中的 Haskell 函数非详尽模式
- mysql - 案例然后使用 CONCAT()
- android - Lottie 动画在 Android 中自动取消
- html - 如何将此按钮移动到我的 div 的右上角?
- python - 如何使用 marshmallow 和 flask_restful 加载参数?