maraiah: make checkdata not a macro

master
an 2019-06-18 01:42:17 -04:00
parent 17b5456aca
commit 92aea23e04
3 changed files with 22 additions and 14 deletions

View File

@ -160,6 +160,9 @@ macro_rules! rd_impl {
/// ```
/// # #[macro_use] extern crate maraiah;
/// # use maraiah::err::*;
/// #
/// # fn main() -> ResultS<()>
/// # {
/// let buffer = &[4, 0, 2, 0, 0, 0, 6];
///
/// read_data! {
@ -176,6 +179,7 @@ macro_rules! rd_impl {
/// assert_eq!(six, 6_u8);
/// assert_eq!(byte, &[2, 0, 0, 0]);
/// # Ok(())
/// # }
/// ```
#[macro_export]
macro_rules! read_data {
@ -185,20 +189,24 @@ macro_rules! read_data {
$($ex:ident$(::$exc:ident)*)*;)*
}
) => {
$crate::check_data!($at + $sz, $b);
$crate::bin::check_data($b, $at + $sz)?;
$($crate::rd_impl!($e, $b, $at, $n;
$($rn;)? $nam, $($ex$(::$exc)*,)* $t$(::$tc)*);)*
};
}
/// Checks if there is enough data in `b`.
#[macro_export]
macro_rules! check_data {
($sz:expr, $b:expr) => {
if $b.len() < $sz {
return Err(err_msg("not enough data"));
}
};
///
/// # Errors
///
/// Returns `Err` if `b.len()` is less than `sz`.
pub fn check_data(b: &[u8], sz: usize) -> ResultS<()>
{
if b.len() < sz {
Err(err_msg("not enough data"))
} else {
Ok(())
}
}
/// Casts a `u32` to a `usize`.
@ -417,7 +425,7 @@ pub fn rd_ofstable<T, F>(b: &[u8],
for _ in 0..num {
let ofs = usize_from_u32(u32b(&b[p..p + 4]));
check_data!(ofs, b);
check_data(b, ofs)?;
v.push(read(&b[ofs..])?);
p += 4;
}

View File

@ -1,6 +1,6 @@
//! DEFLATE loader.
use crate::{bit::*, err::*};
use crate::{bin::check_data, bit::*, err::*};
use std::cmp::Ordering;
/// Loads a ZLIB file header.
@ -76,7 +76,7 @@ pub fn load_gzip_header(b: &[u8]) -> ResultS<usize>
p += 2 + xlen;
check_data!(p, b);
check_data(b, p)?;
}
if fl & FNAME != 0 {
@ -90,7 +90,7 @@ pub fn load_gzip_header(b: &[u8]) -> ResultS<usize>
if fl & FHCRC != 0 {
p += 2;
check_data!(p, b);
check_data(b, p)?;
}
Ok(p)

View File

@ -1,11 +1,11 @@
//! `iidx` chunk.
use crate::{bin::u16b, err::*};
use crate::{bin::{check_data, u16b}, err::*};
/// Reads an `iidx` chunk.
pub fn read(b: &[u8]) -> ResultS<(u16, usize)>
{
check_data!(2, b);
check_data(b, 2)?;
Ok((u16b(b), 2))
}