|
| 1 | +use scroll::Pread; |
| 2 | +use scroll_derive::{Pread, Pwrite}; |
| 3 | + |
| 4 | +#[derive(Debug, Pread, Pwrite)] |
| 5 | +pub struct FloofHeader { |
| 6 | + pub boop: u8, |
| 7 | + pub length: u16, |
| 8 | + pub flag: u8, |
| 9 | + pub quux_service: u8, |
| 10 | + pub quux_client_id: u8, |
| 11 | +} |
| 12 | + |
| 13 | +pub trait QuuxHeaderApi { |
| 14 | + fn msg_len(&self) -> usize; |
| 15 | +} |
| 16 | + |
| 17 | +#[derive(Debug, Pread, Pwrite)] |
| 18 | +pub struct QuuxHeader { |
| 19 | + pub typ: u8, |
| 20 | + pub txn_id: u16, |
| 21 | + pub msg_id: u16, |
| 22 | + pub msg_len: u16, |
| 23 | +} |
| 24 | + |
| 25 | +impl QuuxHeaderApi for QuuxHeader { |
| 26 | + fn msg_len(&self) -> usize { |
| 27 | + self.msg_len as usize |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +#[derive(Debug, Pread, Pwrite)] |
| 32 | +pub struct Response<'a, T: QuuxHeaderApi> { |
| 33 | + pub floof: FloofHeader, |
| 34 | + pub quux: T, |
| 35 | + #[scroll(ctx = quux.msg_len())] |
| 36 | + pub tlvs: &'a [u8], |
| 37 | +} |
| 38 | + |
| 39 | +#[test] |
| 40 | +fn test_pread_generics_with_ctx_dependent_on_prior_field() { |
| 41 | + let bytes = [ |
| 42 | + 1, 70, 0, 128, 9, 3, 4, 1, 0, 46, 0, 58, 0, 1, 8, 0, 1, 1, 4, 0, 1, 6, 0, 0, 16, 16, 0, 1, |
| 43 | + 1, 0, 12, 43, 47, 52, 48, 49, 57, 42, 54, 49, 53, 50, 51, 39, 3, 0, 1, 1, 2, 43, 19, 0, 1, |
| 44 | + 1, 0, 0, 0, 1, 12, 41, 49, 51, 48, 49, 57, 42, 54, 43, 51, 50, 54, |
| 45 | + ]; |
| 46 | + let resp: Response<QuuxHeader> = bytes.pread(0).unwrap(); |
| 47 | + assert_eq!(resp.floof.flag, 0x80); |
| 48 | + assert_eq!(resp.floof.length as usize, bytes.len() - 1); |
| 49 | + assert_eq!(resp.floof.quux_service, 0x9); |
| 50 | + assert_eq!(resp.floof.quux_client_id, 3); |
| 51 | + assert_eq!(resp.quux.msg_len(), resp.tlvs.len()); |
| 52 | + assert_eq!(resp.quux.typ, 0x4); |
| 53 | + assert_eq!(resp.quux.txn_id, 1); |
| 54 | +} |
0 commit comments