1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
use crate::error::Error;
use crate::grpc::convert::{error_from_grpc, FromProtobuf};
use futures::prelude::*;
use pin_project::pin_project;
use tonic::Streaming;

use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};

#[must_use = "streams do nothing unless polled"]
#[pin_project]
pub struct InboundStream<P, T> {
    #[pin]
    inner: Streaming<P>,
    _phantom: PhantomData<T>,
}

impl<P, T> InboundStream<P, T> {
    pub(crate) fn new(inner: Streaming<P>) -> Self {
        InboundStream {
            inner,
            _phantom: PhantomData,
        }
    }
}

impl<P, T> Stream for InboundStream<P, T>
where
    T: FromProtobuf<P>,
{
    type Item = Result<T, Error>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        let this = self.project();
        this.inner.poll_next(cx).map(|opt| {
            opt.map(|item| match item {
                Ok(msg) => {
                    let item = T::from_message(msg)?;
                    Ok(item)
                }
                Err(e) => Err(error_from_grpc(e)),
            })
        })
    }
}