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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! [`Protocol`] implementations for primitive and [`std`] types.

#![allow(missing_docs)]

use {
    std::{
        collections::{
            BTreeMap,
            HashMap,
        },
        convert::{
            TryFrom as _,
            TryInto as _,
        },
        fmt,
        future::Future,
        hash::Hash,
        io,
        pin::Pin,
        string::FromUtf8Error,
    },

    derive_more::From,
    tokio::io::{
        AsyncRead,
        AsyncReadExt as _,
        AsyncWrite,
        AsyncWriteExt as _,
    },
    crate::Protocol,
};
#[cfg(feature = "blocking")] use {
    std::io::prelude::*,
    byteorder::{
        NetworkEndian,
        ReadBytesExt as _,
        WriteBytesExt as _,
    },
};

macro_rules! impl_protocol_primitive {
    ($ty:ty, $read:ident, $write:ident$(, $endian:ty)?) => {
        impl Protocol for $ty {
            type ReadError = io::Error;

            fn read<'a, R: AsyncRead + Unpin + Send + 'a>(mut stream: R) -> Pin<Box<dyn Future<Output = io::Result<$ty>> + Send + 'a>> {
                Box::pin(async move {
                    stream.$read().await
                })
            }

            fn write<'a, W: AsyncWrite + Unpin + Send + 'a>(&'a self, mut sink: W) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>> {
                Box::pin(async move {
                    sink.$write(*self).await
                })
            }

            #[cfg(feature = "blocking")]
            fn read_sync<'a>(mut stream: impl Read + 'a) -> io::Result<$ty> {
                stream.$read$(::<$endian>)?()
            }

            #[cfg(feature = "blocking")]
            fn write_sync<'a>(&self, mut sink: impl Write + 'a) -> io::Result<()> {
                sink.$write$(::<$endian>)?(*self)
            }
        }
    };
}

impl_protocol_primitive!(u8, read_u8, write_u8);
impl_protocol_primitive!(i8, read_i8, write_i8);
impl_protocol_primitive!(u16, read_u16, write_u16, NetworkEndian);
impl_protocol_primitive!(i16, read_i16, write_i16, NetworkEndian);
impl_protocol_primitive!(u32, read_u32, write_u32, NetworkEndian);
impl_protocol_primitive!(i32, read_i32, write_i32, NetworkEndian);
impl_protocol_primitive!(u64, read_u64, write_u64, NetworkEndian);
impl_protocol_primitive!(i64, read_i64, write_i64, NetworkEndian);
impl_protocol_primitive!(u128, read_u128, write_u128, NetworkEndian);
impl_protocol_primitive!(i128, read_i128, write_i128, NetworkEndian);

#[derive(Debug, From)]
pub enum BoolReadError {
    InvalidValue(u8),
    #[from]
    Io(io::Error),
}

impl fmt::Display for BoolReadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BoolReadError::InvalidValue(n) => write!(f, "invalid Boolean value: {} (expected 0 or 1)", n),
            BoolReadError::Io(e) => write!(f, "I/O error: {}", e),
        }
    }
}

impl Protocol for bool {
    type ReadError = BoolReadError;

    fn read<'a, R: AsyncRead + Unpin + Send + 'a>(stream: R) -> Pin<Box<dyn Future<Output = Result<bool, BoolReadError>> + Send + 'a>> {
        Box::pin(async move {
            Ok(match u8::read(stream).await? {
                0 => false,
                1 => true,
                n => return Err(BoolReadError::InvalidValue(n)),
            })
        })
    }

    fn write<'a, W: AsyncWrite + Unpin + Send + 'a>(&'a self, sink: W) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>> {
        Box::pin(async move {
            if *self { 1u8 } else { 0 }.write(sink).await
        })
    }

    #[cfg(feature = "blocking")]
    fn read_sync<'a>(stream: impl Read + 'a) -> Result<bool, BoolReadError> {
        Ok(match u8::read_sync(stream)? {
            0 => false,
            1 => true,
            n => return Err(BoolReadError::InvalidValue(n)),
        })
    }

    #[cfg(feature = "blocking")]
    fn write_sync<'a>(&self, sink: impl Write + 'a) -> io::Result<()> {
        if *self { 1u8 } else { 0 }.write_sync(sink)
    }
}

#[derive(Debug)]
pub enum OptionReadError<T: Protocol> {
    Variant(BoolReadError),
    Content(T::ReadError),
}

impl<T: Protocol> fmt::Display for OptionReadError<T>
where T::ReadError: fmt::Display {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            OptionReadError::Variant(e) => e.fmt(f),
            OptionReadError::Content(e) => e.fmt(f),
        }
    }
}

impl<T: Protocol + Sync> Protocol for Option<T> {
    type ReadError = OptionReadError<T>;

    fn read<'a, R: AsyncRead + Unpin + Send + 'a>(mut stream: R) -> Pin<Box<dyn Future<Output = Result<Option<T>, OptionReadError<T>>> + Send + 'a>> {
        Box::pin(async move {
            Ok(if bool::read(&mut stream).await.map_err(OptionReadError::Variant)? {
                Some(T::read(stream).await.map_err(OptionReadError::Content)?)
            } else {
                None
            })
        })
    }

    fn write<'a, W: AsyncWrite + Unpin + Send + 'a>(&'a self, mut sink: W) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>> {
        Box::pin(async move {
            if let Some(value) = self {
                true.write(&mut sink).await?;
                value.write(sink).await?;
            } else {
                false.write(sink).await?;
            }
            Ok(())
        })
    }

    #[cfg(feature = "blocking")]
    fn read_sync<'a>(mut stream: impl Read + 'a) -> Result<Option<T>, OptionReadError<T>> {
        Ok(if bool::read_sync(&mut stream).map_err(OptionReadError::Variant)? {
            Some(T::read_sync(stream).map_err(OptionReadError::Content)?)
        } else {
            None
        })
    }

    #[cfg(feature = "blocking")]
    fn write_sync<'a>(&self, mut sink: impl Write + 'a) -> io::Result<()> {
        if let Some(value) = self {
            true.write_sync(&mut sink)?;
            value.write_sync(sink)?;
        } else {
            false.write_sync(sink)?;
        }
        Ok(())
    }
}

#[derive(Debug)]
pub enum VecReadError<T: Protocol> {
    Elt(T::ReadError),
    Io(io::Error),
}

impl<T: Protocol> fmt::Display for VecReadError<T>
where T::ReadError: fmt::Display {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            VecReadError::Elt(e) => e.fmt(f),
            VecReadError::Io(e) => write!(f, "I/O error: {}", e),
        }
    }
}

impl<T: Protocol + Send + Sync> Protocol for Vec<T> {
    type ReadError = VecReadError<T>;

    fn read<'a, R: AsyncRead + Unpin + Send + 'a>(mut stream: R) -> Pin<Box<dyn Future<Output = Result<Vec<T>, VecReadError<T>>> + Send + 'a>> {
        Box::pin(async move {
            let len = u64::read(&mut stream).await.map_err(VecReadError::Io)?;
            let mut buf = Vec::with_capacity(len.try_into().expect("tried to read vector longer than usize::MAX"));
            for _ in 0..len {
                buf.push(T::read(&mut stream).await.map_err(VecReadError::Elt)?);
            }
            Ok(buf)
        })
    }

    fn write<'a, W: AsyncWrite + Unpin + Send + 'a>(&'a self, mut sink: W) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>> {
        Box::pin(async move {
            u64::try_from(self.len()).expect("vector was longer than u64::MAX").write(&mut sink).await?;
            for elt in self {
                elt.write(&mut sink).await?;
            }
            Ok(())
        })
    }

    #[cfg(feature = "blocking")]
    fn read_sync<'a>(mut stream: impl Read + 'a) -> Result<Vec<T>, VecReadError<T>> {
        let len = u64::read_sync(&mut stream).map_err(VecReadError::Io)?;
        let mut buf = Vec::with_capacity(len.try_into().expect("tried to read vector longer than usize::MAX"));
        for _ in 0..len {
            buf.push(T::read_sync(&mut stream).map_err(VecReadError::Elt)?);
        }
        Ok(buf)
    }

    #[cfg(feature = "blocking")]
    fn write_sync<'a>(&self, mut sink: impl Write + 'a) -> io::Result<()> {
        u64::try_from(self.len()).expect("vector was longer than u32::MAX").write_sync(&mut sink)?;
        for elt in self {
            elt.write_sync(&mut sink)?;
        }
        Ok(())
    }
}

#[derive(Debug, From)]
pub enum StringReadError {
    Utf8(FromUtf8Error),
    Vec(VecReadError<u8>),
}

impl fmt::Display for StringReadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StringReadError::Utf8(e) => e.fmt(f),
            StringReadError::Vec(e) => e.fmt(f),
        }
    }
}

impl Protocol for String {
    type ReadError = StringReadError;

    fn read<'a, R: AsyncRead + Unpin + Send + 'a>(stream: R) -> Pin<Box<dyn Future<Output = Result<String, StringReadError>> + Send + 'a>> {
        Box::pin(async move {
            let buf = Vec::read(stream).await?;
            Ok(String::from_utf8(buf)?)
        })
    }

    fn write<'a, W: AsyncWrite + Unpin + Send + 'a>(&'a self, mut sink: W) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>> {
        Box::pin(async move {
            u32::try_from(self.len()).expect("string was longer than u32::MAX bytes").write(&mut sink).await?;
            sink.write(self.as_bytes()).await?;
            Ok(())
        })
    }

    #[cfg(feature = "blocking")]
    fn read_sync<'a>(stream: impl Read + 'a) -> Result<String, StringReadError> {
        let buf = Vec::read_sync(stream)?;
        Ok(String::from_utf8(buf)?)
    }

    #[cfg(feature = "blocking")]
    fn write_sync<'a>(&self, mut sink: impl Write + 'a) -> io::Result<()> {
        u32::try_from(self.len()).expect("string was longer than u32::MAX bytes").write_sync(&mut sink)?;
        sink.write(self.as_bytes())?;
        Ok(())
    }
}

#[derive(Debug)]
pub enum MapReadError<K: Protocol, V: Protocol> {
    Io(io::Error),
    Key(K::ReadError),
    Value(V::ReadError),
}

impl<K: Protocol, V: Protocol> fmt::Display for MapReadError<K, V>
where K::ReadError: fmt::Display, V::ReadError: fmt::Display {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MapReadError::Io(e) => write!(f, "I/O error: {}", e),
            MapReadError::Key(e) => e.fmt(f),
            MapReadError::Value(e) => e.fmt(f),
        }
    }
}

impl<K: Protocol + Ord + Send + Sync + 'static, V: Protocol + Send + Sync + 'static> Protocol for BTreeMap<K, V>
where K::ReadError: Send, V::ReadError: Send {
    type ReadError = MapReadError<K, V>;

    fn read<'a, R: AsyncRead + Unpin + Send + 'a>(mut stream: R) -> Pin<Box<dyn Future<Output = Result<BTreeMap<K, V>, MapReadError<K, V>>> + Send + 'a>> {
        Box::pin(async move {
            let len = u64::read(&mut stream).await.map_err(MapReadError::Io)?;
            let mut map = BTreeMap::default();
            for _ in 0..len {
                map.insert(K::read(&mut stream).await.map_err(MapReadError::Key)?, V::read(&mut stream).await.map_err(MapReadError::Value)?);
            }
            Ok(map)
        })
    }

    fn write<'a, W: AsyncWrite + Unpin + Send + 'a>(&'a self, mut sink: W) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>> {
        Box::pin(async move {
            u64::try_from(self.len()).expect("map was longer than u64::MAX").write(&mut sink).await?;
            for (k, v) in self {
                k.write(&mut sink).await?;
                v.write(&mut sink).await?;
            }
            Ok(())
        })
    }

    #[cfg(feature = "blocking")]
    fn read_sync<'a>(mut stream: impl Read + 'a) -> Result<BTreeMap<K, V>, MapReadError<K, V>> {
        let len = u64::read_sync(&mut stream).map_err(MapReadError::Io)?;
        let mut map = BTreeMap::default();
        for _ in 0..len {
            map.insert(K::read_sync(&mut stream).map_err(MapReadError::Key)?, V::read_sync(&mut stream).map_err(MapReadError::Value)?);
        }
        Ok(map)
    }

    #[cfg(feature = "blocking")]
    fn write_sync<'a>(&self, mut sink: impl Write + 'a) -> io::Result<()> {
        u64::try_from(self.len()).expect("map was longer than u64::MAX").write_sync(&mut sink)?;
        for (k, v) in self {
            k.write_sync(&mut sink)?;
            v.write_sync(&mut sink)?;
        }
        Ok(())
    }
}

impl<K: Protocol + Eq + Hash + Send + Sync, V: Protocol + Send + Sync> Protocol for HashMap<K, V>
where K::ReadError: Send, V::ReadError: Send {
    type ReadError = MapReadError<K, V>;

    fn read<'a, R: AsyncRead + Unpin + Send + 'a>(mut stream: R) -> Pin<Box<dyn Future<Output = Result<HashMap<K, V>, MapReadError<K, V>>> + Send + 'a>> {
        Box::pin(async move {
            let len = u64::read(&mut stream).await.map_err(MapReadError::Io)?;
            let mut map = HashMap::with_capacity(len.try_into().expect("tried to read map longer than usize::MAX"));
            for _ in 0..len {
                map.insert(K::read(&mut stream).await.map_err(MapReadError::Key)?, V::read(&mut stream).await.map_err(MapReadError::Value)?);
            }
            Ok(map)
        })
    }

    fn write<'a, W: AsyncWrite + Unpin + Send + 'a>(&'a self, mut sink: W) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>> {
        Box::pin(async move {
            u64::try_from(self.len()).expect("map was longer than u64::MAX").write(&mut sink).await?;
            for (k, v) in self {
                k.write(&mut sink).await?;
                v.write(&mut sink).await?;
            }
            Ok(())
        })
    }

    #[cfg(feature = "blocking")]
    fn read_sync<'a>(mut stream: impl Read + 'a) -> Result<HashMap<K, V>, MapReadError<K, V>> {
        let len = u64::read_sync(&mut stream).map_err(MapReadError::Io)?;
        let mut map = HashMap::with_capacity(len.try_into().expect("tried to read map longer than usize::MAX"));
        for _ in 0..len {
            map.insert(K::read_sync(&mut stream).map_err(MapReadError::Key)?, V::read_sync(&mut stream).map_err(MapReadError::Value)?);
        }
        Ok(map)
    }

    #[cfg(feature = "blocking")]
    fn write_sync<'a>(&self, mut sink: impl Write + 'a) -> io::Result<()> {
        u64::try_from(self.len()).expect("map was longer than u64::MAX").write_sync(&mut sink)?;
        for (k, v) in self {
            k.write_sync(&mut sink)?;
            v.write_sync(&mut sink)?;
        }
        Ok(())
    }
}

impl Protocol for std::time::Duration {
    type ReadError = io::Error;

    fn read<'a, R: AsyncRead + Unpin + Send + 'a>(mut stream: R) -> Pin<Box<dyn Future<Output = io::Result<std::time::Duration>> + Send + 'a>> {
        Box::pin(async move {
            Ok(std::time::Duration::new(u64::read(&mut stream).await?, u32::read(&mut stream).await?))
        })
    }

    fn write<'a, W: AsyncWrite + Unpin + Send + 'a>(&'a self, mut sink: W) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'a>> {
        Box::pin(async move {
            self.as_secs().write(&mut sink).await?;
            self.subsec_nanos().write(sink).await?;
            Ok(())
        })
    }

    #[cfg(feature = "blocking")]
    fn read_sync<'a>(mut stream: impl Read + 'a) -> io::Result<std::time::Duration> {
        Ok(std::time::Duration::new(u64::read_sync(&mut stream)?, u32::read_sync(&mut stream)?))
    }

    #[cfg(feature = "blocking")]
    fn write_sync<'a>(&self, mut sink: impl Write + 'a) -> io::Result<()> {
        self.as_secs().write_sync(&mut sink)?;
        self.subsec_nanos().write_sync(sink)?;
        Ok(())
    }
}