1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use core::convert::TryInto;
use ross_protocol::packet::Packet;
use crate::extractor::{Extractor, ExtractorError};
use crate::ExtractorValue;
#[repr(C)]
#[derive(Debug)]
pub struct EventCodeExtractor {}
impl EventCodeExtractor {
pub fn new() -> Self {
Self {}
}
}
impl Extractor for EventCodeExtractor {
fn extract<'a>(&self, packet: &'a Packet) -> Result<ExtractorValue<'a>, ExtractorError> {
if packet.data.len() < 2 {
Err(ExtractorError::PacketTooShort)
} else {
Ok(
ExtractorValue::U16(u16::from_be_bytes(packet.data[0..=1].try_into().unwrap()))
)
}
}
}
#[cfg(test)]
mod tests {
extern crate alloc;
use super::*;
use alloc::vec;
use alloc::vec::Vec;
const PACKET: Packet = Packet {
is_error: false,
device_address: 0xabab,
data: Vec::new(),
};
#[test]
fn correct_format_test() {
let mut packet = PACKET;
packet.data = vec![
0x00,
0x00,
];
let extractor = EventCodeExtractor::new();
assert_eq!(
extractor.extract(&packet),
Ok(ExtractorValue::U16(0x0000))
);
}
#[test]
fn wrong_format_test() {
let mut packet = PACKET;
packet.data = vec![
0x00,
];
let extractor = EventCodeExtractor::new();
assert_eq!(extractor.extract(&packet), Err(ExtractorError::PacketTooShort));
}
}