如何解决尝试使用 hyper 返回分块响应时“无法推断适当的生命周期”
我想以特定大小的块返回二进制数据。这是一个 minimal example。
我为 hyper::Response
创建了一个包装结构来保存我的数据,如状态、状态文本、标题和要返回的资源:
pub struct Response<'a> {
pub resource: Option<&'a Resource>
}
这个结构体有一个 build
方法来创建 hyper::Response
:
impl<'a> Response<'a> {
pub fn build(&mut self) -> Result<hyper::Response<hyper::Body>,hyper::http::Error> {
let mut response = hyper::Response::builder();
match self.resource {
Some(r) => {
let chunks = r.data
.chunks(100)
.map(Result::<_,std::convert::Infallible>::Ok);
response.body(hyper::Body::wrap_stream(stream::iter(chunks)))
},None => response.body(hyper::Body::from("")),}
}
}
还有另一个结构体保存数据库内容:
pub struct Resource {
pub data: Vec<u8>
}
一切正常,直到我尝试创建分块响应。 Rust 编译器给了我以下错误:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:14:15
|
14 | match self.resource {
| ^^^^^^^^^^^^^
|
note: first,the lifetime cannot outlive the lifetime `'a` as defined on the impl at 11:6...
--> src/main.rs:11:6
|
11 | impl<'a> Response<'a> {
| ^^
note: ...so that the types are compatible
--> src/main.rs:14:15
|
14 | match self.resource {
| ^^^^^^^^^^^^^
= note: expected `Option<&Resource>`
found `Option<&'a Resource>`
= note: but,the lifetime must be valid for the static lifetime...
note: ...so that the types are compatible
--> src/main.rs:19:31
|
19 | response.body(hyper::Body::wrap_stream(stream::iter(chunks)))
| ^^^^^^^^^^^^^^^^^^^^^^^^
= note: expected `From<&[u8]>`
found `From<&'static [u8]>`
我不知道如何满足这些生命周期要求。我该如何正确执行此操作?
解决方法
问题不在于 'a
本身,而在于 std::slice::chunks()
函数返回一个借用原始切片的迭代器。您正在尝试根据此 Chunks<'_,u8>
值创建流未来,但流要求它是 'static
。即使您的 Resource
没有 'a
的生命周期,您仍然会借用 r.data
,并且它仍然会失败。
请记住,此处的 'static
并不意味着该值会永远存在,而是可以根据需要使其持续存在。也就是说,未来不得持有任何(非'static
)借款。
您可以克隆所有数据,但如果数据非常大,则成本可能很高。如果是这样,您可以尝试使用 Bytes
,这就像 Vec<u8>
一样,但引用计数。
看起来没有 Bytes::chunks()
函数返回 Bytes
的迭代器。幸运的是,手工操作很容易。
最后,请记住 Rust 中的迭代器是惰性的,因此它们保留借用的原始数据,即使它是 Bytes
。因此,我们需要将它们收集到 Vec
中以实际拥有数据 (playground):
pub struct Resource {
pub data: Bytes,}
impl<'a> Response<'a> {
pub fn build(&mut self) -> Result<hyper::Response<hyper::Body>,hyper::http::Error> {
let mut response = hyper::Response::builder();
match self.resource {
Some(r) => {
let len = r.data.len();
let chunks = (0..len)
.step_by(100)
.map(|x| {
let range = x..len.min(x + 100);
Ok(r.data.slice(range))
})
.collect::<Vec<Result<Bytes,std::convert::Infallible>>>();
response.body(hyper::Body::wrap_stream(stream::iter(chunks)))
}
None => response.body(hyper::Body::from("")),}
}
}
更新:如果我们注意到 collect()
拥有可以惰性求值的 stream::iter()
的所有权,我们可以避免调用 IntoIterator
,只要我们让它 {{1} }.如果我们对 'static
进行(廉价的)克隆并将其移动到 lambda (playground) 中,则可以实现:
r.data
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。