mod body;
mod decode_helpers;
mod header;
mod types_section;
pub use body::EofBody;
pub use header::EofHeader;
pub use types_section::TypesSection;
use crate::Bytes;
use core::cmp::min;
use std::{vec, vec::Vec};
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Eof {
pub header: EofHeader,
pub body: EofBody,
pub raw: Bytes,
}
impl Default for Eof {
fn default() -> Self {
let body = EofBody {
types_section: vec![TypesSection::default()],
code_section: vec![[0x00].into()],
container_section: vec![],
data_section: Bytes::new(),
is_data_filled: true,
};
body.into_eof()
}
}
impl Eof {
pub fn size(&self) -> usize {
self.header.size() + self.header.body_size()
}
pub fn raw(&self) -> &Bytes {
&self.raw
}
pub fn data_slice(&self, offset: usize, len: usize) -> &[u8] {
self.body
.data_section
.get(offset..)
.and_then(|bytes| bytes.get(..min(len, bytes.len())))
.unwrap_or(&[])
}
pub fn data(&self) -> &[u8] {
&self.body.data_section
}
pub fn encode_slow(&self) -> Bytes {
let mut buffer: Vec<u8> = Vec::with_capacity(self.size());
self.header.encode(&mut buffer);
self.body.encode(&mut buffer);
buffer.into()
}
pub fn decode(raw: Bytes) -> Result<Self, EofDecodeError> {
let (header, _) = EofHeader::decode(&raw)?;
let body = EofBody::decode(&raw, &header)?;
Ok(Self { header, body, raw })
}
}
#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub enum EofDecodeError {
MissingInput,
MissingBodyWithoutData,
DanglingData,
InvalidTypesSection,
InvalidTypesSectionSize,
InvalidEOFMagicNumber,
InvalidEOFVersion,
InvalidTypesKind,
InvalidCodeKind,
InvalidTerminalByte,
InvalidDataKind,
InvalidKindAfterCode,
MismatchCodeAndTypesSize,
NonSizes,
ShortInputForSizes,
ZeroSize,
TooManyCodeSections,
ZeroCodeSections,
TooManyContainerSections,
}
#[cfg(test)]
mod test {
use super::*;
use crate::bytes;
#[test]
fn decode_eof() {
let bytes = bytes!("ef000101000402000100010400000000800000fe");
let eof = Eof::decode(bytes.clone()).unwrap();
assert_eq!(bytes, eof.encode_slow());
}
#[test]
fn data_slice() {
let bytes = bytes!("ef000101000402000100010400000000800000fe");
let mut eof = Eof::decode(bytes.clone()).unwrap();
eof.body.data_section = bytes!("01020304");
assert_eq!(eof.data_slice(0, 1), &[0x01]);
assert_eq!(eof.data_slice(0, 4), &[0x01, 0x02, 0x03, 0x04]);
assert_eq!(eof.data_slice(0, 5), &[0x01, 0x02, 0x03, 0x04]);
assert_eq!(eof.data_slice(1, 2), &[0x02, 0x03]);
assert_eq!(eof.data_slice(10, 2), &[]);
assert_eq!(eof.data_slice(1, 0), &[]);
assert_eq!(eof.data_slice(10, 0), &[]);
}
}