Skip to main content

razers_protocol_core/
lib.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2
3//! Pure protocol codecs with no device or operating-system I/O.
4//!
5//! 纯协议编解码,不执行设备或操作系统读写。
6
7use thiserror::Error;
8
9/// Total size of the classic Razer vendor report.
10///
11/// 经典 Razer 厂商报文的总长度。
12pub const REPORT_90_SIZE: usize = 90;
13/// Maximum number of argument bytes carried by a classic report.
14///
15/// 经典报文可携带的参数字节数上限。
16pub const REPORT_90_ARGUMENT_CAPACITY: usize = 80;
17/// Byte position containing the report checksum.
18///
19/// 报文校验和所在的字节位置。
20pub const REPORT_90_CRC_INDEX: usize = 88;
21/// Byte position containing the reserved trailing byte.
22///
23/// 末尾保留字节的位置。
24pub const REPORT_90_RESERVED_INDEX: usize = 89;
25
26/// A decoded classic 90-byte Razer vendor report.
27///
28/// The representation is intentionally explicit instead of relying on packed
29/// structs or unsafe memory conversion.
30///
31/// 解码后的 90 字节经典 Razer 厂商报文。字段显式表示,不依赖紧凑结构体或不安全内存转换。
32#[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/// Errors produced while encoding or decoding a classic report.
45///
46/// 经典报文编解码可能产生的错误。
47#[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    /// Construct a host-to-device command with default status and protocol fields.
63    ///
64    /// 使用默认状态和协议字段构造主机到设备的命令。
65    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    /// Set the transaction identifier used to match a request and response.
86    ///
87    /// 设置用于匹配请求与响应的事务标识。
88    pub fn with_transaction_id(mut self, transaction_id: u8) -> Self {
89        self.transaction_id = transaction_id;
90        self
91    }
92
93    /// Return only the meaningful argument bytes declared by `data_size`.
94    ///
95    /// 仅返回 `data_size` 声明的有效参数字节。
96    pub fn arguments(&self) -> &[u8] {
97        &self.arguments
98    }
99
100    /// Encode this report into its fixed-size wire representation.
101    ///
102    /// 将此报文编码为固定长度的线上格式。
103    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    /// Decode and validate an exact 90-byte wire report.
121    ///
122    /// 解码并校验长度恰好为 90 字节的报文。
123    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
164/// Calculate the XOR checksum over byte positions 2 through 87 inclusive.
165///
166/// The CRC and reserved bytes are intentionally excluded.
167///
168/// 对第 2 至 87 字节(含两端)计算异或校验和;不包含校验和与保留字节。
169pub 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}