如何在Rust中将Stream转换为RepeatedField?

时间:2019-02-22 14:36:51

标签: stream rust protocol-buffers

我在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向量的步骤)?

1 个答案:

答案 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 }
}

因此,不,您的代码已经很简单而且很优化:它创建了向量,然后将其移动到结构中而没有不必要的复制。