Add try_read_u32 function to read 4 u8s to a u32
This commit is contained in:
@@ -18,14 +18,20 @@ pub fn try_read_magic<I: Iterator<Item=u8>>(bytes: &mut I) -> Result<(), DecodeE
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn try_read_u32<I: Iterator<Item=u8>>(bytes: &mut I) -> Result<u32, DecodeError> {
|
fn try_read_u32<I: Iterator<Item=u8>>(bytes: &mut I) -> Result<u32, DecodeError> {
|
||||||
let mut res: u32 = 0;
|
let mut repacker = || {
|
||||||
let i = bytes.take(4)
|
if let Some(next_byte) = bytes.next() {
|
||||||
.enumerate()
|
return Result::<u32, DecodeError>::Ok(next_byte as u32);
|
||||||
.reduce(|acc, (idx, val)| {
|
} else {
|
||||||
(0, 0)
|
return Err(DecodeError::EarlyIteratorExhaustion);
|
||||||
});
|
}
|
||||||
|
};
|
||||||
|
|
||||||
Ok(res)
|
Ok(
|
||||||
|
(repacker()? << 24)
|
||||||
|
+ (repacker()? << 16)
|
||||||
|
+ (repacker()? << 8)
|
||||||
|
+ (repacker()?)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
mod codec_utils {
|
mod codec_utils {
|
||||||
@@ -603,4 +609,21 @@ mod test {
|
|||||||
iters += 1;
|
iters += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_try_read_u32() {
|
||||||
|
let input = [10u8, 200u8, 255u8, 1u8, 254u8, 123u8, 45u8];
|
||||||
|
let expected = 180_944_641;
|
||||||
|
assert_eq!(
|
||||||
|
try_read_u32(&mut input.into_iter()).expect("Couldn't read u32 from byte array"),
|
||||||
|
expected
|
||||||
|
);
|
||||||
|
|
||||||
|
let too_short = [0u8];
|
||||||
|
let expected = Result::<u32, DecodeError>::Err(DecodeError::EarlyIteratorExhaustion);
|
||||||
|
assert_eq!(
|
||||||
|
try_read_u32(&mut too_short.into_iter()),
|
||||||
|
expected
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, PartialEq)]
|
||||||
pub enum DecodeError {
|
pub enum DecodeError {
|
||||||
Magic,
|
Magic,
|
||||||
Channels,
|
Channels,
|
||||||
|
|||||||
Reference in New Issue
Block a user