bitreader_async/
byte_reader.rs

1use async_std::io::{Read, BufReader};
2use async_std::prelude::*;
3use std::mem;
4use async_trait::async_trait;
5use super::error::Result;
6
7#[async_trait]
8pub trait ReadFromBigEndian : Sized
9{
10    //make sure that input is the same size as self before calling
11    async fn read_be<R : Read + std::marker::Unpin + std::marker::Send>(reader: &mut BufReader<R>) -> Result<Self>;
12}
13
14pub trait FromBigEndian : Sized
15{
16    fn from_be(int_bytes : Self) -> Self;
17}
18
19pub trait FromLittleEndian : Sized
20{
21    fn from_le(int_bytes : Self) -> Self;
22}
23
24 
25
26macro_rules! be_impl {
27    ($ty: ty, $size: tt) => {
28        #[async_trait]
29        impl ReadFromBigEndian for $ty {
30            #[inline]
31            async fn read_be<R : Read + std::marker::Unpin + std::marker::Send>(reader: &mut BufReader<R>) -> Result<Self>
32            {
33                let mut int_bytes = [0u8; $size];
34                let _result = reader.read_exact(&mut int_bytes).await?;
35                Ok(<$ty>::from_be_bytes(int_bytes))
36            }
37        }
38
39        impl FromBigEndian for $ty {
40            #[inline]
41            fn from_be(int_bytes : $ty) -> Self
42            {
43                <$ty>::from_be(int_bytes)
44            }
45        }
46        
47        impl FromLittleEndian for $ty {
48            #[inline]
49            fn from_le(int_bytes : $ty) -> Self
50            {
51                <$ty>::from_le(int_bytes)
52            }
53        }
54    }
55}
56
57
58
59be_impl!(u8, (mem::size_of::<u8>()));
60be_impl!(u16, (mem::size_of::<u16>()));
61be_impl!(u32, (mem::size_of::<u32>()));
62be_impl!(u64, (mem::size_of::<u64>()));
63be_impl!(i8,  (mem::size_of::<i8>()));
64be_impl!(i16, (mem::size_of::<i16>()));
65be_impl!(i32, (mem::size_of::<i32>()));
66be_impl!(i64, (mem::size_of::<i64>()));
67be_impl!(usize, (mem::size_of::<usize>()));
68be_impl!(isize, (mem::size_of::<isize>()));
69