我在Rust中有以下要从服务中返回的结构:
#[derive(PartialEq,Clone,Default)]
pub struct Response {
pub names: ::protobuf::RepeatedField<String>,
}
,然后通过以下方式设置其names
字段(有关其类型,请参见the doc):
use protobuf::{Message, RepeatedField};
use futures::future::Future;
use futures::Stream;
fn create_response(names: impl Stream<Item = String, Error = CustomError>) -> Result<Response, CustomError>
let names = names.collect().wait()?;
let mut response = Response::new();
response.set_names(RepeatedField::from_vec(names));
Ok(response)
}
现在,我想优化这段代码,避免阻塞collect
操作。有什么方法可以将names
直接流到response.names
字段中(即避免创建names
向量的步骤)?
答案 0 :(得分:1)
有来自protobuf来源的相关代码段:
/// Wrapper around vector to avoid deallocations on clear.
pub struct RepeatedField<T> {
vec: Vec<T>,
len: usize,
}
/// Create a contained with data from given vec.
#[inline]
pub fn from_vec(vec: Vec<T>) -> RepeatedField<T> {
let len = vec.len();
RepeatedField { vec: vec, len: len }
}
因此,不,您的代码已经很简单而且很优化:它创建了向量,然后将其移动到结构中而没有不必要的复制。