2019-04-24 17:13:34 -04:00
|
|
|
//! Example using hand-coded structs to validate that the borrow checker
|
|
|
|
//! will allow our code to actually run
|
|
|
|
|
2019-05-09 13:58:27 -04:00
|
|
|
use kaitai::{BytesReader, KError, KResult, KStream, KStruct, KStructUnit, TypedStack};
|
2019-04-24 17:13:34 -04:00
|
|
|
|
|
|
|
#[derive(Debug, PartialEq, Clone, Default)]
|
2019-05-09 13:58:27 -04:00
|
|
|
struct TestRootStruct<'s> {
|
|
|
|
pub bytes: &'s [u8],
|
|
|
|
pub child: Option<TestChildStruct<'s>>,
|
2019-04-24 17:13:34 -04:00
|
|
|
}
|
|
|
|
#[derive(Debug, PartialEq, Clone, Default)]
|
2019-05-09 13:58:27 -04:00
|
|
|
struct TestChildStruct<'s> {
|
|
|
|
pub bytes: &'s [u8],
|
|
|
|
pub root_bytes: &'s [u8],
|
2019-04-24 17:13:34 -04:00
|
|
|
}
|
|
|
|
|
2019-05-09 13:58:27 -04:00
|
|
|
impl<'r, 's: 'r> KStruct<'r, 's> for TestRootStruct<'s> {
|
|
|
|
type Root = Self;
|
|
|
|
type ParentStack = (KStructUnit);
|
2019-04-24 17:13:34 -04:00
|
|
|
|
2019-05-09 13:58:27 -04:00
|
|
|
fn read<S: KStream>(
|
2019-04-26 16:08:55 -04:00
|
|
|
&mut self,
|
|
|
|
_io: &'s S,
|
2019-05-09 13:58:27 -04:00
|
|
|
_root: Option<&'r Self::Root>,
|
|
|
|
_parent: TypedStack<Self::ParentStack>,
|
2019-04-26 16:08:55 -04:00
|
|
|
) -> KResult<'s, ()> {
|
|
|
|
self.bytes = _io.read_bytes(1)?;
|
|
|
|
|
|
|
|
let mut child = TestChildStruct::default();
|
2019-05-09 13:58:27 -04:00
|
|
|
child.read(_io, Some(self), _parent.push(self))?;
|
2019-04-26 16:08:55 -04:00
|
|
|
self.child = Some(child);
|
2019-04-24 17:13:34 -04:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-09 13:58:27 -04:00
|
|
|
impl<'r, 's: 'r> KStruct<'r, 's> for TestChildStruct<'s> {
|
|
|
|
type Root = <TestRootStruct<'s> as KStruct<'r, 's>>::Root;
|
|
|
|
type ParentStack = (&'r TestRootStruct<'s>, <TestRootStruct<'s> as KStruct<'r, 's>>::ParentStack);
|
2019-04-24 17:13:34 -04:00
|
|
|
|
2019-05-09 13:58:27 -04:00
|
|
|
fn read<S: KStream>(
|
2019-04-26 16:08:55 -04:00
|
|
|
&mut self,
|
|
|
|
_io: &'s S,
|
2019-05-09 13:58:27 -04:00
|
|
|
_root: Option<&'r Self::Root>,
|
|
|
|
_parent: TypedStack<Self::ParentStack>,
|
2019-04-26 16:08:55 -04:00
|
|
|
) -> KResult<'s, ()> {
|
|
|
|
self.bytes = _io.read_bytes(1).unwrap();
|
|
|
|
_root.map(|r| self.root_bytes = r.bytes).ok_or(KError::MissingRoot)?;
|
2019-04-24 17:13:34 -04:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn basic_parse() {
|
2019-04-26 16:08:55 -04:00
|
|
|
let bytes = vec![1, 2];
|
|
|
|
let mut reader = BytesReader::new(&bytes);
|
2019-04-24 17:13:34 -04:00
|
|
|
|
2019-04-26 16:08:55 -04:00
|
|
|
let mut root = TestRootStruct::default();
|
2019-05-09 13:58:27 -04:00
|
|
|
let res = root.read(&mut reader, None, KStructUnit::parent_stack());
|
2019-04-24 17:13:34 -04:00
|
|
|
assert!(res.is_ok());
|
|
|
|
|
|
|
|
assert_eq!([1], root.bytes);
|
|
|
|
assert!(root.child.is_some());
|
|
|
|
assert_eq!([2], root.child.unwrap().bytes);
|
|
|
|
}
|