1- use std:: fs;
2- use std:: io;
3-
41use hostname;
52use md5;
63use rand:: RngCore ;
@@ -26,14 +23,15 @@ pub fn get() -> [u8; 3] {
2623 bytes
2724}
2825
29- // OS dependent machine ids. Only linux was confirmed.
30-
3126// https://github.com/rs/xid/blob/efa678f304ab65d6d57eedcb086798381ae22206/hostid_linux.go
3227// Not checking "/sys/class/dmi/id/product_uuid" because normal users can't read it.
3328#[ cfg( target_os = "linux" ) ]
34- fn machine_id ( ) -> io:: Result < String > {
29+ fn machine_id ( ) -> std:: io:: Result < String > {
30+ use std:: fs;
31+ // Get machine-id and remove the trailing new line.
3532 fs:: read_to_string ( "/var/lib/dbus/machine-id" )
3633 . or_else ( |_| fs:: read_to_string ( "/etc/machine-id" ) )
34+ . map ( |s| s. trim_end ( ) . to_string ( ) )
3735}
3836
3937// https://github.com/rs/xid/blob/efa678f304ab65d6d57eedcb086798381ae22206/hostid_darwin.go
@@ -46,14 +44,43 @@ fn machine_id() -> Result<String, SysctlError> {
4644
4745// https://github.com/rs/xid/blob/efa678f304ab65d6d57eedcb086798381ae22206/hostid_windows.go
4846#[ cfg( target_os = "windows" ) ]
49- fn machine_id ( ) -> io:: Result < String > {
50- winreg:: RegKey :: predef ( winreg:: enums:: HKEY_LOCAL_MACHINE )
47+ fn machine_id ( ) -> std:: io:: Result < String > {
48+ let hklm = winreg:: RegKey :: predef ( winreg:: enums:: HKEY_LOCAL_MACHINE ) ;
49+ let guid: String = hklm
5150 . open_subkey ( "SOFTWARE\\ Microsoft\\ Cryptography" ) ?
52- . get_value ( "MachineGuid" ) ?
51+ . get_value ( "MachineGuid" ) ?;
52+ Ok ( guid)
5353}
5454
5555#[ cfg( not( any( target_os = "linux" , target_os = "macos" , target_os = "windows" ) ) ) ]
56- fn machine_id ( ) -> io:: Result < String > {
56+ fn machine_id ( ) -> std :: io:: Result < String > {
5757 // Fallback to hostname or a random value
5858 Ok ( "" . to_string ( ) )
5959}
60+
61+ #[ cfg( test) ]
62+ mod tests {
63+ use super :: * ;
64+
65+ #[ cfg( target_os = "linux" ) ]
66+ #[ test]
67+ fn test_linux ( ) {
68+ // machine-id has length 32
69+ assert_eq ! ( machine_id( ) . unwrap( ) . len( ) , 32 ) ;
70+ }
71+
72+ #[ cfg( target_os = "macos" ) ]
73+ #[ test]
74+ fn test_macos ( ) {
75+ // Ensure non empty string
76+ assert ! ( machine_id( ) . unwrap( ) . len( ) > 0 ) ;
77+ }
78+
79+ #[ cfg( target_os = "windows" ) ]
80+ #[ test]
81+ fn test_windows ( ) {
82+ // MachineGuid has length 36
83+ // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
84+ assert_eq ! ( machine_id( ) . unwrap( ) . len( ) , 36 ) ;
85+ }
86+ }
0 commit comments