Debian Codegraph @

debian/rust-vendor/hostname/src/windows/mod.rs

raw
1 #[cfg(feature = "set")]
2 use std::ffi::OsStr;
3 use std::ffi::OsString;
4 use std::io;
5 #[cfg(feature = "set")]
6 use std::os::windows::ffi::OsStrExt;
7 use std::os::windows::ffi::OsStringExt;
8 use std::ptr;
9
10 mod bindings;
11 use bindings::{ComputerNamePhysicalDnsHostname, GetComputerNameExW, PWSTR};
12
13 pub fn get() -> io::Result<OsString> {
14 let mut size = 0;
15 unsafe {
16 // Don't care much about the result here,
17 // it is guaranteed to return an error,
18 // since we passed the NULL pointer as a buffer
19 let result =
20 GetComputerNameExW(ComputerNamePhysicalDnsHostname, ptr::null_mut(), &mut size);
21 debug_assert_eq!(result, 0);
22 };
23
24 let mut buffer = Vec::with_capacity(size as usize);
25
26 let result = unsafe {
27 GetComputerNameExW(
28 ComputerNamePhysicalDnsHostname,
29 PWSTR::from(buffer.as_mut_ptr()),
30 &mut size,
31 )
32 };
33
34 match result {
35 0 => Err(io::Error::last_os_error()),
36 _ => {
37 unsafe {
38 buffer.set_len(size as usize);
39 }
40
41 Ok(OsString::from_wide(&buffer))
42 }
43 }
44 }
45
46 #[cfg(feature = "set")]
47 pub fn set(hostname: &OsStr) -> io::Result<()> {
48 use bindings::{SetComputerNameExW, PCWSTR};
49
50 let mut buffer = hostname.encode_wide().collect::<Vec<_>>();
51 buffer.push(0x00); // Appending the null terminator
52
53 let result = unsafe {
54 SetComputerNameExW(
55 ComputerNamePhysicalDnsHostname,
56 PCWSTR::from(buffer.as_ptr()),
57 )
58 };
59
60 match result {
61 0 => Err(io::Error::last_os_error()),
62 _ => Ok(()),
63 }
64 }