binread/helpers.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
use crate::{
io::{ErrorKind::UnexpectedEof, Read, Seek},
BinRead, BinReaderExt, BinResult, ReadOptions,
};
#[cfg(not(feature = "std"))]
use alloc::{vec, vec::Vec};
/// A helper for more efficiently mass-reading bytes
///
///## Example:
///
/// ```rust
/// # use binread::{BinRead, helpers::read_bytes, io::Cursor, BinReaderExt};
/// #[derive(BinRead)]
/// struct BunchaBytes {
/// #[br(count = 5)]
/// data: Vec<u8>
/// }
///
/// # let mut x = Cursor::new(b"\0\x01\x02\x03\x04");
/// # let x: BunchaBytes = x.read_be().unwrap();
/// # assert_eq!(x.data, &[0, 1, 2, 3, 4]);
/// ```
pub fn read_bytes<R: Read + Seek>(
reader: &mut R,
options: &ReadOptions,
_: (),
) -> BinResult<Vec<u8>> {
let count = match options.count {
Some(x) => x,
None => panic!("Missing count for read_bytes"),
};
let mut buf = vec![0; count];
reader.read_exact(&mut buf)?;
Ok(buf)
}
/// Read items until a condition is met. The final item will be included.
///
/// # Examples
///
/// ```
/// # use binread::{BinRead, helpers::until, io::Cursor, BinReaderExt};
/// #[derive(BinRead)]
/// struct NullTerminated {
/// #[br(parse_with = until(|&byte| byte == 0))]
/// data: Vec<u8>,
/// }
///
/// # let mut x = Cursor::new(b"\x01\x02\x03\x04\0");
/// # let x: NullTerminated = x.read_be().unwrap();
/// # assert_eq!(x.data, &[1, 2, 3, 4, 0]);
/// ```
pub fn until<Reader, T, CondFn, Arg, Ret>(
cond: CondFn,
) -> impl Fn(&mut Reader, &ReadOptions, Arg) -> BinResult<Ret>
where
T: BinRead<Args = Arg>,
Reader: Read + Seek,
CondFn: Fn(&T) -> bool,
Arg: Clone,
Ret: core::iter::FromIterator<T>,
{
move |reader, ro, args| {
let mut result = Vec::new();
let mut last = reader.read_type_args(ro.endian, args.clone())?;
while !cond(&last) {
result.push(last);
last = reader.read_type_args(ro.endian, args.clone())?;
}
result.push(last);
Ok(result.into_iter().collect())
}
}
/// Read items until a condition is met. The last item will *not* be named.
///
/// # Examples
///
/// ```
/// # use binread::{BinRead, helpers::until_exclusive, io::Cursor, BinReaderExt};
/// #[derive(BinRead)]
/// struct NullTerminated {
/// #[br(parse_with = until_exclusive(|&byte| byte == 0))]
/// data: Vec<u8>,
/// }
///
/// # let mut x = Cursor::new(b"\x01\x02\x03\x04\0");
/// # let x: NullTerminated = x.read_be().unwrap();
/// # assert_eq!(x.data, &[1, 2, 3, 4]);
/// ```
pub fn until_exclusive<Reader, T, CondFn, Arg, Ret>(
cond: CondFn,
) -> impl Fn(&mut Reader, &ReadOptions, Arg) -> BinResult<Ret>
where
T: BinRead<Args = Arg>,
Reader: Read + Seek,
CondFn: Fn(&T) -> bool,
Arg: Clone,
Ret: core::iter::FromIterator<T>,
{
move |reader, ro, args| {
let mut result = Vec::new();
let mut last = reader.read_type_args(ro.endian, args.clone())?;
while !cond(&last) {
result.push(last);
last = reader.read_type_args(ro.endian, args.clone())?;
}
Ok(result.into_iter().collect())
}
}
/// Read items until the end of the file is hit.
///
/// # Examples
///
/// ```
/// # use binread::{BinRead, helpers::until_eof, io::Cursor, BinReaderExt};
/// #[derive(BinRead)]
/// struct EntireFile {
/// #[br(parse_with = until_eof)]
/// data: Vec<u8>,
/// }
///
/// # let mut x = Cursor::new(b"\x01\x02\x03\x04");
/// # let x: EntireFile = x.read_be().unwrap();
/// # assert_eq!(x.data, &[1, 2, 3, 4]);
/// ```
pub fn until_eof<R, T, Arg, Ret>(reader: &mut R, ro: &ReadOptions, args: Arg) -> BinResult<Ret>
where
T: BinRead<Args = Arg>,
R: Read + Seek,
Arg: Clone,
Ret: core::iter::FromIterator<T>,
{
let mut result = Vec::new();
let mut last = reader.read_type_args(ro.endian, args.clone());
while !matches!(&last, Err(crate::Error::Io(err)) if err.kind() == UnexpectedEof) {
last = match last {
Ok(x) => {
result.push(x);
reader.read_type_args(ro.endian, args.clone())
}
Err(err) => return Err(err),
}
}
Ok(result.into_iter().collect())
}
/// A helper equivelant to `#[br(count = N)]` which can be used with any collection.
///
/// # Examples
///
/// ```
/// # use binread::{BinRead, helpers::count, io::Cursor, BinReaderExt};
/// #[derive(BinRead)]
/// struct CountBytes {
/// len: u8,
///
/// #[br(parse_with = count(len as usize))]
/// data: Vec<u8>,
/// }
///
/// # let mut x = Cursor::new(b"\x03\x01\x02\x03");
/// # let x: CountBytes = x.read_be().unwrap();
/// # assert_eq!(x.data, &[1, 2, 3]);
/// ```
pub fn count<R, T, Arg, Ret>(n: usize) -> impl Fn(&mut R, &ReadOptions, Arg) -> BinResult<Ret>
where
T: BinRead<Args = Arg>,
R: Read + Seek,
Arg: Clone,
Ret: core::iter::FromIterator<T>,
{
move |reader, ro, args| {
(0..n)
.map(|_| reader.read_type_args(ro.endian, args.clone()))
.collect()
}
}