Skip to main content

razers_types/
lib.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2
3//! Shared, transport-independent types used across the RazeRS workspace.
4//!
5//! RazeRS 工作区共用的类型,不依赖具体传输方式。
6
7use std::{fmt, str::FromStr};
8
9use serde::{Deserialize, Serialize};
10use thiserror::Error;
11
12/// Stable identifier for a product-level device descriptor.
13///
14/// 产品级设备描述的稳定标识。
15#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
16#[serde(try_from = "String", into = "String")]
17pub struct DeviceId(String);
18
19/// Stable identifier for one physical connection belonging to a product.
20///
21/// 产品某个物理连接的稳定标识。
22#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
23#[serde(try_from = "String", into = "String")]
24pub struct ConnectionId(String);
25
26/// Why an identifier could not be accepted.
27///
28/// 标识被拒绝的原因。
29#[derive(Clone, Debug, Error, Eq, PartialEq)]
30#[error("invalid {kind} identifier '{value}': {reason}")]
31pub struct InvalidIdentifier {
32    kind: &'static str,
33    value: String,
34    reason: &'static str,
35}
36
37impl DeviceId {
38    /// Parse a namespaced product identifier such as `razer.basilisk-v3`.
39    ///
40    /// 解析带命名空间的产品标识,例如 `razer.basilisk-v3`。
41    pub fn new(value: impl Into<String>) -> Result<Self, InvalidIdentifier> {
42        validate_identifier("device", value.into(), true).map(Self)
43    }
44
45    /// Return the identifier as a string slice.
46    ///
47    /// 返回标识的字符串切片。
48    pub fn as_str(&self) -> &str {
49        &self.0
50    }
51}
52
53impl ConnectionId {
54    /// Parse a connection identifier such as `wired` or `receiver-slot-1`.
55    ///
56    /// 解析连接标识,例如 `wired` 或 `receiver-slot-1`。
57    pub fn new(value: impl Into<String>) -> Result<Self, InvalidIdentifier> {
58        validate_identifier("connection", value.into(), false).map(Self)
59    }
60
61    /// Return the identifier as a string slice.
62    ///
63    /// 返回标识的字符串切片。
64    pub fn as_str(&self) -> &str {
65        &self.0
66    }
67}
68
69fn validate_identifier(
70    kind: &'static str,
71    value: String,
72    namespace_required: bool,
73) -> Result<String, InvalidIdentifier> {
74    let fail = |reason| InvalidIdentifier {
75        kind,
76        value: value.clone(),
77        reason,
78    };
79
80    if value.is_empty() {
81        return Err(fail("must not be empty"));
82    }
83    if value.len() > 96 {
84        return Err(fail("must be at most 96 bytes"));
85    }
86    if namespace_required && !value.contains('.') {
87        return Err(fail("must contain a namespace separator"));
88    }
89    if value.starts_with(['.', '-']) || value.ends_with(['.', '-']) {
90        return Err(fail("must not start or end with a separator"));
91    }
92    if value.contains("..") || value.contains("--") || value.contains(".-") || value.contains("-.")
93    {
94        return Err(fail("must not contain adjacent separators"));
95    }
96    if !value.bytes().all(|byte| {
97        byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'.' || byte == b'-'
98    }) {
99        return Err(fail(
100            "use lowercase ASCII letters, digits, dots, and hyphens only",
101        ));
102    }
103    if !namespace_required && value.contains('.') {
104        return Err(fail("must not contain a namespace separator"));
105    }
106
107    Ok(value)
108}
109
110macro_rules! identifier_impls {
111    ($name:ident) => {
112        impl fmt::Display for $name {
113            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
114                formatter.write_str(&self.0)
115            }
116        }
117
118        impl FromStr for $name {
119            type Err = InvalidIdentifier;
120
121            fn from_str(value: &str) -> Result<Self, Self::Err> {
122                Self::new(value)
123            }
124        }
125
126        impl TryFrom<String> for $name {
127            type Error = InvalidIdentifier;
128
129            fn try_from(value: String) -> Result<Self, Self::Error> {
130                Self::new(value)
131            }
132        }
133
134        impl From<$name> for String {
135            fn from(value: $name) -> Self {
136                value.0
137            }
138        }
139    };
140}
141
142identifier_impls!(DeviceId);
143identifier_impls!(ConnectionId);
144
145/// Confidence level for product or capability support.
146///
147/// 产品或能力支持的可信程度。
148#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
149#[serde(rename_all = "kebab-case")]
150pub enum SupportStatus {
151    Detected,
152    Experimental,
153    Verified,
154    Regressed,
155    Unsupported,
156}
157
158/// Safety class assigned to every protocol command.
159///
160/// 每条协议命令的安全风险等级。
161#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
162#[serde(rename_all = "kebab-case")]
163pub enum CommandRisk {
164    ReadOnly,
165    Reversible,
166    Persistent,
167    ExperimentalWrite,
168    Firmware,
169}
170
171/// Where a setting is expected to persist.
172///
173/// 设置预期保存的位置与持久性。
174#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
175#[serde(rename_all = "kebab-case")]
176pub enum PersistenceScope {
177    Session,
178    HostProfile,
179    DeviceSetting,
180    OnboardProfileSlot,
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn accepts_stable_identifiers() {
189        assert_eq!(
190            DeviceId::new("razer.basilisk-v3").unwrap().as_str(),
191            "razer.basilisk-v3"
192        );
193        assert_eq!(
194            ConnectionId::new("receiver-slot-1").unwrap().as_str(),
195            "receiver-slot-1"
196        );
197    }
198
199    #[test]
200    fn rejects_ambiguous_identifiers() {
201        assert!(DeviceId::new("BasiliskV3").is_err());
202        assert!(DeviceId::new("basilisk-v3").is_err());
203        assert!(ConnectionId::new("usb.main").is_err());
204        assert!(ConnectionId::new("wired--usb").is_err());
205    }
206}