| 1 |
use crate::errors::{ErrorKind, Result}; |
| 2 |
use bytes::Buf; |
| 3 |
use paste::paste; |
| 4 |
use std::mem; |
| 5 |
|
| 6 |
macro_rules! try_get { |
| 7 |
($this:ident, $typ:tt) => {{ |
| 8 |
if $this.0.remaining() < mem::size_of::<$typ>() { |
| 9 |
Err(ErrorKind::UnexpectedEof.into()) |
| 10 |
} else { |
| 11 |
Ok(paste! {$this.0. [< get_ $typ >]()}) |
| 12 |
} |
| 13 |
}}; |
| 14 |
|
| 15 |
($this:ident, $typ:tt::$endian:tt) => {{ |
| 16 |
if $this.0.remaining() < mem::size_of::<$typ>() { |
| 17 |
Err(ErrorKind::UnexpectedEof.into()) |
| 18 |
} else { |
| 19 |
Ok(paste! {$this.0. [< get_ $typ _ $endian >]()}) |
| 20 |
} |
| 21 |
}}; |
| 22 |
} |
| 23 |
|
| 24 |
pub(crate) struct Reader<'a>(&'a [u8]); |
| 25 |
|
| 26 |
impl<'a> Reader<'a> { |
| 27 |
pub(crate) fn new(data: &'a [u8]) -> Reader<'a> { |
| 28 |
Reader(data) |
| 29 |
} |
| 30 |
|
| 31 |
pub(crate) fn read(&mut self, cnt: usize) -> Result<&[u8]> { |
| 32 |
if self.remaining() < cnt { |
| 33 |
return Err(ErrorKind::UnexpectedEof.into()); |
| 34 |
} |
| 35 |
|
| 36 |
let data = &self.0[0..cnt]; |
| 37 |
self.0.advance(cnt); |
| 38 |
|
| 39 |
Ok(data) |
| 40 |
} |
| 41 |
|
| 42 |
pub(crate) fn bytes(&self) -> &[u8] { |
| 43 |
self.0.chunk() |
| 44 |
} |
| 45 |
|
| 46 |
pub(crate) fn remaining(&self) -> usize { |
| 47 |
self.0.remaining() |
| 48 |
} |
| 49 |
|
| 50 |
pub(crate) fn advance(&mut self, cnt: usize) -> Result<()> { |
| 51 |
if self.remaining() < cnt { |
| 52 |
return Err(ErrorKind::UnexpectedEof.into()); |
| 53 |
} |
| 54 |
|
| 55 |
self.0.advance(cnt); |
| 56 |
|
| 57 |
Ok(()) |
| 58 |
} |
| 59 |
|
| 60 |
pub(crate) fn get_u8(&mut self) -> Result<u8> { |
| 61 |
try_get!(self, u8) |
| 62 |
} |
| 63 |
|
| 64 |
pub(crate) fn get_u16(&mut self) -> Result<u16> { |
| 65 |
try_get!(self, u16::le) |
| 66 |
} |
| 67 |
|
| 68 |
pub(crate) fn get_u32(&mut self) -> Result<u32> { |
| 69 |
try_get!(self, u32::le) |
| 70 |
} |
| 71 |
|
| 72 |
pub(crate) fn get_u64(&mut self) -> Result<u64> { |
| 73 |
try_get!(self, u64::le) |
| 74 |
} |
| 75 |
|
| 76 |
pub(crate) fn get_u128(&mut self) -> Result<u128> { |
| 77 |
try_get!(self, u128::le) |
| 78 |
} |
| 79 |
|
| 80 |
pub(crate) fn get_f32(&mut self) -> Result<f32> { |
| 81 |
try_get!(self, f32::le) |
| 82 |
} |
| 83 |
} |