iso14229_1/request/
write_mem_by_addr.rs1use crate::{AddressAndLengthFormatIdentifier, Configuration, Error, MemoryLocation, Placeholder, RequestData, utils};
5
6#[derive(Debug, Clone)]
7pub struct WriteMemByAddr {
8 pub(crate) mem_loc: MemoryLocation,
9 pub(crate) data: Vec<u8>,
10}
11
12impl WriteMemByAddr {
13 #[inline]
14 pub fn new(
15 alfi: AddressAndLengthFormatIdentifier,
16 mem_addr: u128,
17 mem_size: u128,
18 data: Vec<u8>,
19 ) -> Result<Self, Error> {
20 if data.len() != mem_size as usize {
21 return Err(Error::InvalidParam("the length of data must be equal to mem_size and the mem_size must rather than 0".to_string()));
22 }
23
24 Ok(Self {
25 mem_loc: MemoryLocation::new(alfi, mem_addr, mem_size)?,
26 data,
27 })
28 }
29
30 #[inline]
31 pub fn memory_location(&self) -> &MemoryLocation {
32 &self.mem_loc
33 }
34
35 #[inline]
36 pub fn data_record(&self) -> &Vec<u8> {
37 &self.data
38 }
39}
40
41impl RequestData for WriteMemByAddr {
42 type SubFunc = Placeholder;
43 fn try_parse(data: &[u8], _: Option<Self::SubFunc>, cfg: &Configuration) -> Result<Self, Error> {
44 utils::data_length_check(data.len(), 5, false)?;
45 let mut offset = 0;
46 let mem_loc = MemoryLocation::from_slice(data, cfg)?;
47 offset += mem_loc.len();
48 let data = data[offset..].to_vec();
49
50 Ok(Self { mem_loc, data })
51 }
52
53 fn to_vec(mut self, cfg: &Configuration) -> Vec<u8> {
54 let mut result: Vec<_> = self.mem_loc.to_vec(cfg);
55 result.append(&mut self.data);
56
57 result
58 }
59}
60
61#[cfg(test)]
62mod tests {
63 use crate::{AddressAndLengthFormatIdentifier, Configuration, RequestData};
64 use super::WriteMemByAddr;
65
66 #[test]
67 fn new() -> anyhow::Result<()> {
68 let cfg = Configuration::default();
69
70 let source = hex::decode("3D4420481213000000051122334455")?;
71 let request = WriteMemByAddr::new(
72 AddressAndLengthFormatIdentifier::new(4, 4)?,
73 0x20481213,
74 0x05,
75 hex::decode("1122334455")?,
76 )?;
77 let result: Vec<_> = request.to_vec(&cfg);
78 assert_eq!(result, source[1..].to_vec());
79
80 let request = WriteMemByAddr::try_parse(&source[1..], None, &cfg)?;
81 assert_eq!(request.mem_loc.memory_address(), 0x20481213);
82 assert_eq!(request.mem_loc.memory_size(), 0x05);
83 assert_eq!(request.data, hex::decode("1122334455")?);
84
85 Ok(())
86 }
87}