razers_protocol_core/
lib.rs1use thiserror::Error;
8
9pub const REPORT_90_SIZE: usize = 90;
13pub const REPORT_90_ARGUMENT_CAPACITY: usize = 80;
17pub const REPORT_90_CRC_INDEX: usize = 88;
21pub const REPORT_90_RESERVED_INDEX: usize = 89;
25
26#[derive(Clone, Debug, Eq, PartialEq)]
33pub struct Report90 {
34 pub status: u8,
35 pub transaction_id: u8,
36 pub remaining_packets: u16,
37 pub protocol_type: u8,
38 pub command_class: u8,
39 pub command_id: u8,
40 arguments: Vec<u8>,
41 pub reserved: u8,
42}
43
44#[derive(Clone, Debug, Error, Eq, PartialEq)]
48pub enum Report90Error {
49 #[error("expected a {REPORT_90_SIZE}-byte report, received {actual} bytes")]
50 InvalidLength { actual: usize },
51 #[error(
52 "report arguments are {actual} bytes, exceeding the {REPORT_90_ARGUMENT_CAPACITY}-byte limit"
53 )]
54 ArgumentsTooLong { actual: usize },
55 #[error("report declares an invalid data size of {data_size} bytes")]
56 InvalidDataSize { data_size: usize },
57 #[error("report checksum mismatch: expected 0x{expected:02x}, received 0x{actual:02x}")]
58 ChecksumMismatch { expected: u8, actual: u8 },
59}
60
61impl Report90 {
62 pub fn command(
66 command_class: u8,
67 command_id: u8,
68 arguments: impl Into<Vec<u8>>,
69 ) -> Result<Self, Report90Error> {
70 let arguments = arguments.into();
71 validate_argument_length(arguments.len())?;
72
73 Ok(Self {
74 status: 0,
75 transaction_id: 0,
76 remaining_packets: 0,
77 protocol_type: 0,
78 command_class,
79 command_id,
80 arguments,
81 reserved: 0,
82 })
83 }
84
85 pub fn with_transaction_id(mut self, transaction_id: u8) -> Self {
89 self.transaction_id = transaction_id;
90 self
91 }
92
93 pub fn arguments(&self) -> &[u8] {
97 &self.arguments
98 }
99
100 pub fn encode(&self) -> Result<[u8; REPORT_90_SIZE], Report90Error> {
104 validate_argument_length(self.arguments.len())?;
105
106 let mut bytes = [0_u8; REPORT_90_SIZE];
107 bytes[0] = self.status;
108 bytes[1] = self.transaction_id;
109 bytes[2..4].copy_from_slice(&self.remaining_packets.to_be_bytes());
110 bytes[4] = self.protocol_type;
111 bytes[5] = self.arguments.len() as u8;
112 bytes[6] = self.command_class;
113 bytes[7] = self.command_id;
114 bytes[8..8 + self.arguments.len()].copy_from_slice(&self.arguments);
115 bytes[REPORT_90_CRC_INDEX] = calculate_crc(&bytes);
116 bytes[REPORT_90_RESERVED_INDEX] = self.reserved;
117 Ok(bytes)
118 }
119
120 pub fn decode(bytes: &[u8]) -> Result<Self, Report90Error> {
124 if bytes.len() != REPORT_90_SIZE {
125 return Err(Report90Error::InvalidLength {
126 actual: bytes.len(),
127 });
128 }
129
130 let data_size = bytes[5] as usize;
131 if data_size > REPORT_90_ARGUMENT_CAPACITY {
132 return Err(Report90Error::InvalidDataSize { data_size });
133 }
134
135 let packet: &[u8; REPORT_90_SIZE] = bytes
136 .try_into()
137 .expect("report length was checked before conversion");
138 let expected = calculate_crc(packet);
139 let actual = bytes[REPORT_90_CRC_INDEX];
140 if actual != expected {
141 return Err(Report90Error::ChecksumMismatch { expected, actual });
142 }
143
144 Ok(Self {
145 status: bytes[0],
146 transaction_id: bytes[1],
147 remaining_packets: u16::from_be_bytes([bytes[2], bytes[3]]),
148 protocol_type: bytes[4],
149 command_class: bytes[6],
150 command_id: bytes[7],
151 arguments: bytes[8..8 + data_size].to_vec(),
152 reserved: bytes[REPORT_90_RESERVED_INDEX],
153 })
154 }
155}
156
157fn validate_argument_length(actual: usize) -> Result<(), Report90Error> {
158 if actual > REPORT_90_ARGUMENT_CAPACITY {
159 return Err(Report90Error::ArgumentsTooLong { actual });
160 }
161 Ok(())
162}
163
164pub fn calculate_crc(bytes: &[u8; REPORT_90_SIZE]) -> u8 {
170 bytes[2..REPORT_90_CRC_INDEX]
171 .iter()
172 .fold(0_u8, |checksum, byte| checksum ^ byte)
173}
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178
179 #[test]
180 fn encodes_the_documented_wire_layout() {
181 let mut report = Report90::command(0x04, 0x05, [0x12, 0x34]).unwrap();
182 report.status = 0x02;
183 report.transaction_id = 0x1f;
184 report.remaining_packets = 0x1234;
185
186 let bytes = report.encode().unwrap();
187
188 assert_eq!(bytes.len(), REPORT_90_SIZE);
189 assert_eq!(
190 &bytes[..10],
191 &[0x02, 0x1f, 0x12, 0x34, 0, 2, 4, 5, 0x12, 0x34]
192 );
193 assert_eq!(bytes[REPORT_90_CRC_INDEX], calculate_crc(&bytes));
194 assert_eq!(bytes[REPORT_90_RESERVED_INDEX], 0);
195 }
196
197 #[test]
198 fn round_trips_a_report() {
199 let mut report = Report90::command(0x07, 0x82, [0xaa, 0xbb, 0xcc]).unwrap();
200 report.transaction_id = 0x3f;
201 report.remaining_packets = 2;
202
203 let decoded = Report90::decode(&report.encode().unwrap()).unwrap();
204 assert_eq!(decoded, report);
205 }
206
207 #[test]
208 fn rejects_a_corrupted_report() {
209 let mut bytes = Report90::command(0x00, 0x81, [0_u8, 0_u8])
210 .unwrap()
211 .encode()
212 .unwrap();
213 bytes[8] ^= 0xff;
214
215 assert!(matches!(
216 Report90::decode(&bytes),
217 Err(Report90Error::ChecksumMismatch { .. })
218 ));
219 }
220
221 #[test]
222 fn rejects_oversized_arguments() {
223 assert_eq!(
224 Report90::command(0, 0, vec![0; REPORT_90_ARGUMENT_CAPACITY + 1]),
225 Err(Report90Error::ArgumentsTooLong {
226 actual: REPORT_90_ARGUMENT_CAPACITY + 1
227 })
228 );
229 }
230
231 #[test]
232 fn rejects_an_invalid_declared_data_size_before_slicing() {
233 let mut bytes = [0_u8; REPORT_90_SIZE];
234 bytes[5] = 81;
235 bytes[REPORT_90_CRC_INDEX] = calculate_crc(&bytes);
236
237 assert_eq!(
238 Report90::decode(&bytes),
239 Err(Report90Error::InvalidDataSize { data_size: 81 })
240 );
241 }
242}