unsigned_varint/
aio.rs

1// Copyright 2020 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy of
4// this software and associated documentation files (the "Software"), to deal in
5// the Software without restriction, including without limitation the rights to
6// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7// the Software, and to permit persons to whom the Software is furnished to do so,
8// subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
16// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
17// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
20//! Decode using [`futures_io::AsyncRead`] types.
21
22use crate::{decode, encode, io::ReadError};
23use futures_io::AsyncRead;
24use futures_util::io::AsyncReadExt;
25use std::io;
26
27macro_rules! gen {
28    ($($name:ident, $d:expr, $t:ident, $b:ident);*) => {
29        $(
30            #[doc = " Try to read and decode a "]
31            #[doc = $d]
32            #[doc = " from the given `AsyncRead` type."]
33            pub async fn $name<R: AsyncRead + Unpin>(mut reader: R) -> Result<$t, ReadError> {
34                let mut b = encode::$b();
35                for i in 0 .. b.len() {
36                    let n = reader.read(&mut b[i .. i + 1]).await?;
37                    if n == 0 {
38                        return Err(ReadError::Io(io::ErrorKind::UnexpectedEof.into()))
39                    }
40                    if decode::is_last(b[i]) {
41                        return Ok(decode::$t(&b[..= i])?.0)
42                    }
43                }
44                Err(decode::Error::Overflow)?
45            }
46        )*
47    }
48}
49
50gen! {
51    read_u8,    "`u8`",    u8,    u8_buffer;
52    read_u16,   "`u16`",   u16,   u16_buffer;
53    read_u32,   "`u32`",   u32,   u32_buffer;
54    read_u64,   "`u64`",   u64,   u64_buffer;
55    read_u128,  "`u128`",  u128,  u128_buffer;
56    read_usize, "`usize`", usize, usize_buffer
57}
58