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
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use std::pin::Pin;
use std::task::{Context, Poll};

use futures::io::Result as IoResult;
use futures::prelude::*;

use super::*;
use crate::encode::{ArrayFuture, MsgPackWriter};

pub struct RpcSink<W> {
    writer: W,
}

impl<W: AsyncWrite + Unpin> AsyncWrite for RpcSink<W> {
    fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<IoResult<usize>> {
        W::poll_write(Pin::new(&mut self.as_mut().writer), cx, buf)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<IoResult<()>> {
        W::poll_flush(Pin::new(&mut self.as_mut().writer), cx)
    }

    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<IoResult<()>> {
        W::poll_close(Pin::new(&mut self.as_mut().writer), cx)
    }
}

impl<W: AsyncWrite + Unpin> RpcSink<W> {
    pub fn new(writer: W) -> Self {
        RpcSink { writer }
    }

    pub fn into_inner(self) -> W {
        self.writer
    }

    #[must_use = "dropping the writer may leave the message unfinished"]
    pub async fn write_request(
        self,
        msgid: MsgId,
        method: impl AsRef<str>,
        num_args: u32,
    ) -> IoResult<ArrayFuture<RpcSink<W>>> {
        // First, wrap our RpcSink in a MsgPackWriter rather than using the
        // underlying writer. When this message is fully written and its writer
        // is returned, the client will be left with this RpcSink pointing at
        // the next message.
        let args = MsgPackWriter::new(self)
            .write_array_len(4)
            .await?
            .next()
            .write_int(MsgType::Request)
            .await?
            .next()
            .write_int(msgid)
            .await?
            .next()
            .write_str(method.as_ref())
            .await?
            .last();
        args.write_array_len(num_args).await
    }

    pub async fn write_ok_response<F, Fut>(self, msgid: MsgId, write_ok: F) -> IoResult<RpcSink<W>>
    where
        F: FnOnce(MsgPackWriter<RpcSink<W>>) -> Fut,
        Fut: Future<Output = IoResult<RpcSink<W>>>,
    {
        let rsp = MsgPackWriter::new(self)
            .write_array_len(4)
            .await?
            .next()
            .write_int(MsgType::Response)
            .await?
            .next()
            .write_int(msgid)
            .await?
            .next()
            .write_nil()
            .await?
            .last();
        write_ok(rsp).await
    }

    pub async fn write_err_response<F, Fut>(
        self,
        msgid: MsgId,
        write_err: F,
    ) -> IoResult<RpcSink<W>>
    where
        F: FnOnce(MsgPackWriter<ArrayFuture<RpcSink<W>>>) -> Fut,
        Fut: Future<Output = IoResult<ArrayFuture<RpcSink<W>>>>,
    {
        let err = MsgPackWriter::new(self)
            .write_array_len(4)
            .await?
            .next()
            .write_int(MsgType::Response)
            .await?
            .next()
            .write_int(msgid)
            .await?
            .next();
        let ok = write_err(err).await?;
        ok.last().write_nil().await
    }

    #[must_use = "dropping the writer may leave the message unfinished"]
    pub async fn write_notification(
        self,
        method: impl AsRef<str>,
        num_args: u32,
    ) -> IoResult<ArrayFuture<RpcSink<W>>> {
        let args = MsgPackWriter::new(self)
            .write_array_len(3)
            .await?
            .next()
            .write_int(MsgType::Notification)
            .await?
            .next()
            .write_str(method.as_ref())
            .await?
            .last();
        args.write_array_len(num_args).await
    }
}

#[test]
fn write_request_response() {
    let sink = RpcSink::new(Vec::new());
    let f = async {
        sink.write_request(2.into(), "floop", 1)
            .await
            .unwrap()
            .last()
            .write_int(42)
            .await
            .unwrap()
    };

    let sink = futures::executor::LocalPool::new().run_until(f);
    let v1 = sink.into_inner();

    let mut v2 = Vec::new();
    rmp::encode::write_array_len(&mut v2, 4).unwrap();
    rmp::encode::write_uint(&mut v2, 0).unwrap();
    rmp::encode::write_uint(&mut v2, 2).unwrap();
    rmp::encode::write_str(&mut v2, "floop").unwrap();
    rmp::encode::write_array_len(&mut v2, 1).unwrap();
    rmp::encode::write_uint(&mut v2, 42).unwrap();
    assert_eq!(v1, v2);
}

#[test]
fn write_ok_response() {
    let sink = RpcSink::new(Vec::new());
    let f = sink.write_ok_response(2.into(), |rsp| rsp.write_int(42));

    let sink = futures::executor::LocalPool::new().run_until(f).unwrap();
    let v1 = sink.into_inner();

    let mut v2 = Vec::new();
    rmp::encode::write_array_len(&mut v2, 4).unwrap();
    rmp::encode::write_uint(&mut v2, 1).unwrap();
    rmp::encode::write_uint(&mut v2, 2).unwrap();
    rmp::encode::write_nil(&mut v2).unwrap();
    rmp::encode::write_uint(&mut v2, 42).unwrap();
    assert_eq!(v1, v2);
}

#[test]
fn write_err_response() {
    let sink = RpcSink::new(Vec::new());
    let f = sink.write_err_response(2.into(), |err| err.write_int(42));

    let sink = futures::executor::LocalPool::new().run_until(f).unwrap();
    let v1 = sink.into_inner();

    let mut v2 = Vec::new();
    rmp::encode::write_array_len(&mut v2, 4).unwrap();
    rmp::encode::write_uint(&mut v2, 1).unwrap();
    rmp::encode::write_uint(&mut v2, 2).unwrap();
    rmp::encode::write_uint(&mut v2, 42).unwrap();
    rmp::encode::write_nil(&mut v2).unwrap();
    assert_eq!(v1, v2);
}