From 43a97878ce14b72f0981164f87f2e35e14151312 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 11:22:09 +0200 Subject: Adding upstream version 110.0.1. Signed-off-by: Daniel Baumann --- third_party/rust/scroll/examples/data_ctx.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 third_party/rust/scroll/examples/data_ctx.rs (limited to 'third_party/rust/scroll/examples') diff --git a/third_party/rust/scroll/examples/data_ctx.rs b/third_party/rust/scroll/examples/data_ctx.rs new file mode 100644 index 0000000000..667f4b18f0 --- /dev/null +++ b/third_party/rust/scroll/examples/data_ctx.rs @@ -0,0 +1,24 @@ +use scroll::{ctx, Endian, Pread, BE}; + +#[derive(Debug)] +struct Data<'a> { + name: &'a str, + id: u32, +} + +impl<'a> ctx::TryFromCtx<'a, Endian> for Data<'a> { + type Error = scroll::Error; + fn try_from_ctx(src: &'a [u8], endian: Endian) -> Result<(Self, usize), Self::Error> { + let name = src.pread::<&'a str>(0)?; + let id = src.pread_with(name.len() + 1, endian)?; + Ok((Data { name: name, id: id }, name.len() + 4)) + } +} + +fn main() { + let bytes = b"UserName\x00\x01\x02\x03\x04"; + let data = bytes.pread_with::(0, BE).unwrap(); + assert_eq!(data.id, 0x01020304); + assert_eq!(data.name.to_string(), "UserName".to_string()); + println!("Data: {:?}", &data); +} -- cgit v1.2.3