ruma_common/identifiers/
device_id.rs
1use ruma_macros::IdZst;
2
3#[cfg(feature = "rand")]
4use super::generate_localpart;
5use super::{IdParseError, KeyName};
6
7#[repr(transparent)]
32#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, IdZst)]
33pub struct DeviceId(str);
34
35impl DeviceId {
36 #[cfg(feature = "rand")]
38 #[allow(clippy::new_ret_no_self)]
39 pub fn new() -> OwnedDeviceId {
40 Self::from_borrowed(&generate_localpart(10)).to_owned()
41 }
42}
43
44impl KeyName for DeviceId {
45 fn validate(_s: &str) -> Result<(), IdParseError> {
46 Ok(())
47 }
48}
49
50impl KeyName for OwnedDeviceId {
51 fn validate(_s: &str) -> Result<(), IdParseError> {
52 Ok(())
53 }
54}
55
56#[cfg(test)]
57mod tests {
58 use super::{DeviceId, OwnedDeviceId};
59
60 #[cfg(feature = "rand")]
61 #[test]
62 fn generate_device_id() {
63 assert_eq!(DeviceId::new().as_str().len(), 10);
64 }
65
66 #[test]
67 fn create_device_id_from_str() {
68 let ref_id: &DeviceId = "abcdefgh".into();
69 assert_eq!(ref_id.as_str(), "abcdefgh");
70 }
71
72 #[test]
73 fn create_boxed_device_id_from_str() {
74 let box_id: OwnedDeviceId = "12345678".into();
75 assert_eq!(box_id.as_str(), "12345678");
76 }
77
78 #[test]
79 fn create_device_id_from_box() {
80 let box_str: Box<str> = "ijklmnop".into();
81 let device_id: OwnedDeviceId = box_str.into();
82 assert_eq!(device_id.as_str(), "ijklmnop");
83 }
84}