async_bincode/writer.rs
1macro_rules! make_writer {
2 ($write_trait:path, $poll_close_method:ident) => {
3 pub use crate::writer::{AsyncDestination, BincodeWriterFor, SyncDestination};
4
5 /// A wrapper around an asynchronous sink that accepts, serializes, and sends bincode-encoded
6 /// values.
7 ///
8 /// To use, provide a reader that implements
9 #[doc=concat!("[`", stringify!($write_trait), "`],")]
10 /// and then use [`futures_sink::Sink`] to send values.
11 ///
12 /// Important: Only one element at a time is written to the output writer. It is recommended
13 /// to use a `BufWriter` in front of the output to batch write operations to the underlying writer.
14 ///
15 /// Note that an `AsyncBincodeWriter` must be of the type [`AsyncDestination`] in order to be
16 /// compatible with an [`AsyncBincodeReader`] on the remote end (recall that it requires the
17 /// serialized size prefixed to the serialized data). The default is [`SyncDestination`], but these
18 /// can be easily toggled between using [`AsyncBincodeWriter::for_async`].
19 #[derive(Debug)]
20 pub struct AsyncBincodeWriter<W, T, D> {
21 pub(crate) writer: W,
22 pub(crate) written: usize,
23 pub(crate) buffer: Vec<u8>,
24 pub(crate) from: std::marker::PhantomData<T>,
25 pub(crate) dest: std::marker::PhantomData<D>,
26 }
27
28 impl<W, T, D> Unpin for AsyncBincodeWriter<W, T, D> where W: Unpin {}
29
30 impl<W, T> Default for AsyncBincodeWriter<W, T, SyncDestination>
31 where
32 W: Default,
33 {
34 fn default() -> Self {
35 Self::from(W::default())
36 }
37 }
38
39 impl<W, T, D> AsyncBincodeWriter<W, T, D> {
40 /// Gets a reference to the underlying writer.
41 ///
42 /// It is inadvisable to directly write to the underlying writer.
43 pub fn get_ref(&self) -> &W {
44 &self.writer
45 }
46
47 /// Gets a mutable reference to the underlying writer.
48 ///
49 /// It is inadvisable to directly write to the underlying writer.
50 pub fn get_mut(&mut self) -> &mut W {
51 &mut self.writer
52 }
53
54 /// Unwraps this `AsyncBincodeWriter`, returning the underlying writer.
55 ///
56 /// Note that any leftover serialized data that has not yet been sent is lost.
57 pub fn into_inner(self) -> W {
58 self.writer
59 }
60 }
61
62 impl<W, T> From<W> for AsyncBincodeWriter<W, T, SyncDestination> {
63 fn from(writer: W) -> Self {
64 Self {
65 buffer: Vec::new(),
66 writer,
67 written: 0,
68 from: std::marker::PhantomData,
69 dest: std::marker::PhantomData,
70 }
71 }
72 }
73
74 impl<W, T> AsyncBincodeWriter<W, T, SyncDestination> {
75 /// Make this writer include the serialized data's size before each serialized value.
76 ///
77 /// This is necessary for compatibility with [`AsyncBincodeReader`].
78 pub fn for_async(self) -> AsyncBincodeWriter<W, T, AsyncDestination> {
79 self.make_for()
80 }
81 }
82
83 impl<W, T> AsyncBincodeWriter<W, T, AsyncDestination> {
84 /// Make this writer only send bincode-encoded values.
85 ///
86 /// This is necessary for compatibility with stock `bincode` receivers.
87 pub fn for_sync(self) -> AsyncBincodeWriter<W, T, SyncDestination> {
88 self.make_for()
89 }
90 }
91
92 impl<W, T, D> AsyncBincodeWriter<W, T, D> {
93 pub(crate) fn make_for<D2>(self) -> AsyncBincodeWriter<W, T, D2> {
94 AsyncBincodeWriter {
95 buffer: self.buffer,
96 writer: self.writer,
97 written: self.written,
98 from: self.from,
99 dest: std::marker::PhantomData,
100 }
101 }
102 }
103
104 impl<W, T> BincodeWriterFor<T> for AsyncBincodeWriter<W, T, AsyncDestination>
105 where
106 T: serde::Serialize,
107 {
108 fn append(&mut self, item: T) -> Result<(), bincode::Error> {
109 use bincode::Options;
110 use byteorder::{NetworkEndian, WriteBytesExt};
111 let c = bincode::options()
112 .with_limit(u32::max_value() as u64)
113 .allow_trailing_bytes();
114 let size = c.serialized_size(&item)? as u32;
115 self.buffer.write_u32::<NetworkEndian>(size)?;
116 c.serialize_into(&mut self.buffer, &item)
117 }
118 }
119
120 impl<W, T> BincodeWriterFor<T> for AsyncBincodeWriter<W, T, SyncDestination>
121 where
122 T: serde::Serialize,
123 {
124 fn append(&mut self, item: T) -> Result<(), bincode::Error> {
125 use bincode::Options;
126 let c = bincode::options().allow_trailing_bytes();
127 c.serialize_into(&mut self.buffer, &item)
128 }
129 }
130
131 impl<W, T, D> futures_sink::Sink<T> for AsyncBincodeWriter<W, T, D>
132 where
133 T: serde::Serialize,
134 W: $write_trait + Unpin,
135 Self: BincodeWriterFor<T>,
136 {
137 type Error = bincode::Error;
138
139 fn poll_ready(
140 self: std::pin::Pin<&mut Self>,
141 cx: &mut std::task::Context,
142 ) -> std::task::Poll<Result<(), Self::Error>> {
143 // allow us to borrow fields separately
144 let this = self.get_mut();
145
146 // write stuff out if we need to
147 while this.written != this.buffer.len() {
148 let n = futures_core::ready!(std::pin::Pin::new(&mut this.writer)
149 .poll_write(cx, &this.buffer[this.written..]))?;
150 this.written += n;
151 }
152
153 // cleanup the buffer
154 this.buffer.clear();
155 this.written = 0;
156 std::task::Poll::Ready(Ok(()))
157 }
158
159 fn start_send(mut self: std::pin::Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
160 // NOTE: in theory we could have a short-circuit here that tries to have bincode write
161 // directly into self.writer. this would be way more efficient in the common case as we
162 // don't have to do the extra buffering. the idea would be to serialize fist, and *if*
163 // it errors, see how many bytes were written, serialize again into a Vec, and then
164 // keep only the bytes following the number that were written in our buffer.
165 // unfortunately, bincode will not tell us that number at the moment, and instead just
166 // fail.
167
168 self.append(item)?;
169 Ok(())
170 }
171
172 fn poll_flush(
173 mut self: std::pin::Pin<&mut Self>,
174 cx: &mut std::task::Context,
175 ) -> std::task::Poll<Result<(), Self::Error>> {
176 futures_core::ready!(self.as_mut().poll_ready(cx))?;
177 std::pin::Pin::new(&mut self.writer)
178 .poll_flush(cx)
179 .map_err(bincode::Error::from)
180 }
181
182 fn poll_close(
183 mut self: std::pin::Pin<&mut Self>,
184 cx: &mut std::task::Context,
185 ) -> std::task::Poll<Result<(), Self::Error>> {
186 // in order to get to the first call to `poll_close`, `poll_ready` must have already
187 // finished and emptied the buffer. thus the call to `poll_ready` will no longer be calling
188 // `poll_write` on the underlying writer on re-entry.
189 futures_core::ready!(self.as_mut().poll_ready(cx))?;
190
191 // `futures::Sink:poll_close` documentation states that calling `poll_close` implies
192 // `poll_flush`, so explicitly calling `poll_flush` is not needed here.
193 std::pin::Pin::new(&mut self.writer)
194 .$poll_close_method(cx)
195 .map_err(bincode::Error::from)
196 }
197 }
198 };
199}
200
201/// A marker that indicates that the wrapping type is compatible with `AsyncBincodeReader`.
202#[derive(Debug)]
203pub struct AsyncDestination;
204
205/// A marker that indicates that the wrapping type is compatible with stock `bincode` receivers.
206#[derive(Debug)]
207pub struct SyncDestination;
208
209#[doc(hidden)]
210pub trait BincodeWriterFor<T> {
211 fn append(&mut self, item: T) -> Result<(), bincode::Error>;
212}