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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
use crate::{
    Error, CHECKSUM_DISABLED, CHECKSUM_ENABLED, PROTOCOL_VERSION, U16_MARKER, U32_MARKER,
    U64_MARKER, ZST_MARKER,
};
use bincode::Options;
use futures_io::AsyncWrite;
use futures_util::{Sink, SinkExt};
use serde::de::DeserializeOwned;
use serde::Serialize;
use siphasher::sip::SipHasher;
use std::collections::VecDeque;
use std::hash::Hasher;
use std::mem::size_of;
use std::pin::Pin;
use std::task::{Context, Poll};

/// Provides the ability to write `serde` compatible types to any type that implements `futures::io::AsyncWrite`.
#[derive(Debug)]
pub struct AsyncWriteTyped<W: AsyncWrite + Unpin, T: Serialize + DeserializeOwned + Unpin> {
    raw: Option<W>,
    write_buffer: Vec<u8>,
    state: AsyncWriteState,
    primed_values: VecDeque<T>,
    message_features: MessageFeatures,
}

#[derive(Debug)]
pub(crate) enum AsyncWriteState {
    WritingVersion {
        version: [u8; 8],
        len_sent: usize,
    },
    WritingChecksumEnabled,
    Idle,
    WritingLen {
        current_len: [u8; 9],
        len_to_be_sent: usize,
        len_sent: usize,
    },
    WritingValue {
        bytes_sent: usize,
    },
    WritingChecksum {
        checksum: [u8; 8],
        len_sent: usize,
    },
    Closing,
    Closed,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct MessageFeatures {
    pub size_limit: u64,
    pub checksum_enabled: bool,
}

impl<W: AsyncWrite + Unpin, T: Serialize + DeserializeOwned + Unpin> Sink<T>
    for AsyncWriteTyped<W, T>
{
    type Error = Error;

    fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn start_send(mut self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
        self.primed_values.push_front(item);
        Ok(())
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let Self {
            ref mut raw,
            ref mut write_buffer,
            ref mut state,
            ref mut primed_values,
            ref message_features,
        } = *self.as_mut();
        match futures_core::ready!(Self::maybe_send(
            raw.as_mut().expect("infallible"),
            state,
            write_buffer,
            primed_values,
            *message_features,
            cx,
            false,
        ))? {
            Some(()) => {
                // Send successful, poll_flush now
                Pin::new(raw.as_mut().expect("infallible"))
                    .poll_flush(cx)
                    .map(|r| r.map_err(Error::Io))
            }
            None => Poll::Ready(Ok(())),
        }
    }

    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        let Self {
            ref mut raw,
            ref mut state,
            ref mut write_buffer,
            ref mut primed_values,
            ref message_features,
        } = *self.as_mut();
        match futures_core::ready!(Self::maybe_send(
            raw.as_mut().expect("infallible"),
            state,
            write_buffer,
            primed_values,
            *message_features,
            cx,
            true,
        ))? {
            Some(()) => {
                // Send successful, poll_close now
                Pin::new(raw.as_mut().expect("infallible"))
                    .poll_close(cx)
                    .map(|r| r.map_err(Error::Io))
            }
            None => Poll::Ready(Ok(())),
        }
    }
}

impl<W: AsyncWrite + Unpin, T: Serialize + DeserializeOwned + Unpin> AsyncWriteTyped<W, T> {
    pub(crate) fn maybe_send(
        raw: &mut W,
        state: &mut AsyncWriteState,
        write_buffer: &mut Vec<u8>,
        primed_values: &mut VecDeque<T>,
        message_features: MessageFeatures,
        cx: &mut Context<'_>,
        closing: bool,
    ) -> Poll<Result<Option<()>, Error>> {
        let MessageFeatures {
            checksum_enabled,
            size_limit,
        } = message_features;
        loop {
            return match state {
                AsyncWriteState::WritingVersion { version, len_sent } => {
                    while *len_sent < size_of::<u64>() {
                        let len = futures_core::ready!(
                            Pin::new(&mut *raw).poll_write(cx, &version[(*len_sent)..])
                        )?;
                        *len_sent += len;
                    }
                    *state = AsyncWriteState::WritingChecksumEnabled;
                    continue;
                }
                AsyncWriteState::WritingChecksumEnabled => {
                    let to_send = if checksum_enabled {
                        CHECKSUM_ENABLED
                    } else {
                        CHECKSUM_DISABLED
                    };
                    if futures_core::ready!(Pin::new(&mut *raw).poll_write(cx, &[to_send]))? == 1 {
                        *state = AsyncWriteState::Idle;
                    }
                    continue;
                }
                AsyncWriteState::Idle => {
                    if let Some(item) = primed_values.pop_back() {
                        write_buffer.clear();
                        crate::bincode_options(size_limit)
                            .serialize_into(&mut *write_buffer, &item)
                            .map_err(Error::Bincode)?;
                        if write_buffer.len() as u64 > size_limit {
                            return Poll::Ready(Err(Error::SentMessageTooLarge));
                        }
                        let (new_current_len, to_be_sent) = if write_buffer.is_empty() {
                            ([ZST_MARKER, 0, 0, 0, 0, 0, 0, 0, 0], 1)
                        } else if write_buffer.len() < U16_MARKER as usize {
                            let bytes = (write_buffer.len() as u8).to_le_bytes();
                            ([bytes[0], 0, 0, 0, 0, 0, 0, 0, 0], 1)
                        } else if (write_buffer.len() as u64) < 2_u64.pow(16) {
                            let bytes = (write_buffer.len() as u16).to_le_bytes();
                            ([U16_MARKER, bytes[0], bytes[1], 0, 0, 0, 0, 0, 0], 3)
                        } else if (write_buffer.len() as u64) < 2_u64.pow(32) {
                            let bytes = (write_buffer.len() as u32).to_le_bytes();
                            (
                                [
                                    U32_MARKER, bytes[0], bytes[1], bytes[2], bytes[3], 0, 0, 0, 0,
                                ],
                                5,
                            )
                        } else {
                            let bytes = (write_buffer.len() as u64).to_le_bytes();
                            (
                                [
                                    U64_MARKER, bytes[0], bytes[1], bytes[2], bytes[3], bytes[4],
                                    bytes[5], bytes[6], bytes[7],
                                ],
                                9,
                            )
                        };
                        *state = AsyncWriteState::WritingLen {
                            current_len: new_current_len,
                            len_to_be_sent: to_be_sent,
                            len_sent: 0,
                        };
                        let len = futures_core::ready!(
                            Pin::new(&mut *raw).poll_write(cx, &new_current_len[0..to_be_sent])
                        )?;
                        *state = if len == to_be_sent {
                            AsyncWriteState::WritingValue { bytes_sent: 0 }
                        } else {
                            AsyncWriteState::WritingLen {
                                current_len: new_current_len,
                                len_to_be_sent: to_be_sent,
                                len_sent: len,
                            }
                        };
                        continue;
                    } else if closing {
                        *state = AsyncWriteState::Closing;
                        continue;
                    } else {
                        Poll::Ready(Ok(Some(())))
                    }
                }
                AsyncWriteState::WritingLen {
                    ref current_len,
                    ref len_to_be_sent,
                    ref mut len_sent,
                } => {
                    while *len_sent < *len_to_be_sent {
                        let len = futures_core::ready!(Pin::new(&mut *raw)
                            .poll_write(cx, &current_len[(*len_sent)..(*len_to_be_sent)]))?;
                        *len_sent += len;
                    }
                    *state = AsyncWriteState::WritingValue { bytes_sent: 0 };
                    continue;
                }
                AsyncWriteState::WritingValue { bytes_sent } => {
                    while *bytes_sent < write_buffer.len() {
                        let len = futures_core::ready!(
                            Pin::new(&mut *raw).poll_write(cx, &write_buffer[*bytes_sent..])
                        )?;
                        *bytes_sent += len;
                    }
                    if checksum_enabled {
                        let mut hasher = SipHasher::new();
                        hasher.write(write_buffer);
                        let checksum = hasher.finish();
                        *state = AsyncWriteState::WritingChecksum {
                            checksum: checksum.to_le_bytes(),
                            len_sent: 0,
                        };
                    } else {
                        *state = AsyncWriteState::Idle;
                        if primed_values.is_empty() {
                            return Poll::Ready(Ok(Some(())));
                        }
                    }
                    continue;
                }
                AsyncWriteState::WritingChecksum { checksum, len_sent } => {
                    while *len_sent < size_of::<u64>() {
                        let len = futures_core::ready!(
                            Pin::new(&mut *raw).poll_write(cx, &checksum[*len_sent..])
                        )?;
                        *len_sent += len;
                    }
                    *state = AsyncWriteState::Idle;
                    if primed_values.is_empty() {
                        return Poll::Ready(Ok(Some(())));
                    }
                    continue;
                }
                AsyncWriteState::Closing => {
                    let len = futures_core::ready!(Pin::new(&mut *raw).poll_write(cx, &[0]))?;
                    if len == 1 {
                        *state = AsyncWriteState::Closed;
                        Poll::Ready(Ok(Some(())))
                    } else {
                        continue;
                    }
                }
                AsyncWriteState::Closed => Poll::Ready(Ok(None)),
            };
        }
    }
}

impl<W: AsyncWrite + Unpin, T: Serialize + DeserializeOwned + Unpin> AsyncWriteTyped<W, T> {
    /// Creates a typed writer, initializing it with the given size limit specified in bytes.
    /// Checksums are used to validate that messages arrived without corruption. **The checksum will only be used
    /// if both the reader and the writer enable it. If either one disables it, then no checking is performed.**
    ///
    /// Be careful, large size limits might create a vulnerability to a Denial of Service attack.
    pub fn new_with_limit(raw: W, size_limit: u64, checksum_enabled: bool) -> Self {
        Self {
            raw: Some(raw),
            write_buffer: Vec::new(),
            state: AsyncWriteState::WritingVersion {
                version: PROTOCOL_VERSION.to_le_bytes(),
                len_sent: 0,
            },
            message_features: MessageFeatures {
                size_limit,
                checksum_enabled,
            },
            primed_values: VecDeque::new(),
        }
    }

    /// Creates a typed writer, initializing it with a default size limit of 1 MB per message.
    /// Checksums are used to validate that messages arrived without corruption. **The checksum will only be used
    /// if both the reader and the writer enable it. If either one disables it, then no checking is performed.**
    pub fn new(raw: W, checksum_enabled: bool) -> Self {
        Self::new_with_limit(raw, 1024u64.pow(2), checksum_enabled)
    }

    /// Returns a reference to the raw I/O primitive that this type is using.
    pub fn inner(&self) -> &W {
        self.raw.as_ref().expect("infallible")
    }

    /// Consumes this `AsyncWriteTyped` and returns the raw I/O primitive that was being used.
    pub fn into_inner(mut self) -> W {
        self.raw.take().expect("infallible")
    }

    /// `AsyncWriteTyped` keeps a memory buffer for sending values which is the same size as the largest
    /// message that's been sent. If the message size varies a lot, you might find yourself wasting
    /// memory space. This function will reduce the memory usage as much as is possible without impeding
    /// functioning. Overuse of this function may cause excessive memory allocations when the buffer
    /// needs to grow.
    pub fn optimize_memory_usage(&mut self) {
        match self.state {
            AsyncWriteState::WritingLen { .. } | AsyncWriteState::WritingValue { .. } => {
                self.write_buffer.shrink_to_fit()
            }
            _ => {
                self.write_buffer = Vec::new();
            }
        }
    }

    /// Reports the size of the memory buffer used for sending values. You can shrink this buffer as much as
    /// possible with [`Self::optimize_memory_usage`].
    pub fn current_memory_usage(&self) -> usize {
        self.write_buffer.capacity()
    }

    /// Returns true if checksums are enabled for this channel. This does not guarantee that the reader is
    /// actually using those checksum values, it only reflects whether checksums are being sent.
    pub fn checksum_enabled(&self) -> bool {
        self.message_features.checksum_enabled
    }
}

impl<W: AsyncWrite + Unpin, T: Serialize + DeserializeOwned + Unpin> Drop
    for AsyncWriteTyped<W, T>
{
    fn drop(&mut self) {
        // This will panic if raw was already taken.
        if self.raw.is_some() {
            let _ = futures_executor::block_on(SinkExt::close(self));
        }
    }
}