ev3_dc/parser/
mod.rs

1//! Module for parsing direct reply
2//!
3//! # Example
4//! Show information about reply
5//! ```
6//! let buf: Vec<u8> = vec![]; // Direct reply vector
7//! let rep = Reply::parse(&buf);
8//! println!("Length: {}, Id: {}, Error: {}, Memory: {:?}", rep.length(), rep.id(), rep.error(), rep.memory());
9//! ```
10
11use crate::DataType;
12
13/// Reply object
14pub struct Reply {
15    length: u16,
16    id: u16,
17    error: bool,
18    memory: Vec<u8>
19}
20
21impl Reply {
22    /// Parse direct reply packet
23    pub fn parse(packet: &[u8]) -> Self {
24        let len = u16::from_le_bytes([packet[0], packet[1]]);
25        let rid = u16::from_le_bytes([packet[2], packet[3]]);
26        let err = packet[4] == 0x20;
27        let mem = packet[5..].to_vec();
28        Reply { length: len, id: rid, error: err, memory: mem }
29    }
30    /// Get reply's length excluding first 2 bytes
31    pub fn length(&self) -> u16 { self.length }
32    /// Get reply's id. Command and reply match up if they have same id
33    pub fn id(&self) -> u16 { self.id }
34    /// Check reply's error
35    pub fn error(&self) -> bool { self.error }
36    /// Get reply's global memory
37    pub fn memory(&self) -> &[u8] { &self.memory }
38}
39
40/// Extract n bytes from specific [`DataType`] 
41pub fn extract_data<T: Iterator<Item = u8>>(bytes: &mut T, dtype: DataType) -> Vec<u8> {
42    let len = match dtype {
43        DataType::DATA8 => 1,
44        DataType::DATA16 => 2,
45        DataType::DATA32 | DataType::DATAF => 4,
46        DataType::DATAN(length) | DataType::DATAS(length) => length,
47    };
48    bytes.by_ref().take(len).collect::<Vec<u8>>()
49}