rs_machineid/
lib.rs

1mod bsd;
2mod errors;
3mod linux;
4mod macos;
5mod utils;
6mod windows;
7
8use errors::MachineIdError;
9
10#[cfg(target_os = "macos")]
11use macos::get_machine_id;
12
13#[cfg(target_os = "windows")]
14use windows::get_machine_id;
15
16#[cfg(target_os = "linux")]
17use linux::get_machine_id;
18
19#[cfg(any(target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))]
20use bsd::get_machine_id;
21
22use crate::utils::{hashed_id, sanitize};
23
24/// Get the machine ID
25pub struct MachineId;
26
27impl MachineId {
28    /// Obtain the unique identifier of the machine.
29    /// Return a unique ID in string form.
30    pub fn get() -> Result<String, MachineIdError> {
31        let id = get_machine_id();
32        match id {
33            Ok(id) => Ok(sanitize(&id)),
34            Err(e) => Err(e),
35        }
36    }
37
38    pub fn get_hashed(app_id: &str) -> Result<String, MachineIdError> {
39        let id = get_machine_id();
40        match id {
41            Ok(id) => Ok(hashed_id(&id, app_id)),
42            Err(e) => Err(e),
43        }
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::MachineId;
50
51    #[test]
52    fn test_get() {
53        let id = MachineId::get();
54        assert!(id.is_ok());
55
56        let machine_id = id.unwrap();
57        println!("Generated Machine ID: {}", machine_id);
58        println!("Length: {}", machine_id.len());
59
60        assert!(!machine_id.is_empty());
61        assert!(machine_id.len() >= 6);
62    }
63
64    #[test]
65    fn test_id_uniqueness() {
66        let id1 = MachineId::get().unwrap();
67        let id2 = MachineId::get().unwrap();
68        let id3 = MachineId::get().unwrap();
69
70        println!("ID 1: {}", id1);
71        println!("ID 2: {}", id2);
72        println!("ID 3: {}", id3);
73
74        assert_eq!(id1, id2);
75        assert_eq!(id2, id3);
76    }
77
78    #[test]
79    fn test_get_hashed() {
80        let app_id = "test_app";
81        let hash = MachineId::get_hashed(app_id);
82        assert!(hash.is_ok());
83
84        let hash = hash.unwrap();
85        println!("Generated Hash: {}", hash);
86        println!("Length: {}", hash.len());
87
88        assert!(!hash.is_empty());
89        assert!(hash.len() >= 64);
90    }
91}