]> git.proxmox.com Git - rustc.git/blobdiff - src/libstd/sys/windows/os.rs
New upstream version 1.41.1+dfsg1
[rustc.git] / src / libstd / sys / windows / os.rs
index 7c400dce686f374a439138834b91284ddc4ae035..8631e50cf3888833110278ca2baccbc94be70c85 100644 (file)
@@ -5,7 +5,7 @@
 use crate::os::windows::prelude::*;
 
 use crate::error::Error as StdError;
-use crate::ffi::{OsString, OsStr};
+use crate::ffi::{OsStr, OsString};
 use crate::fmt;
 use crate::io;
 use crate::os::windows::ffi::EncodeWide;
@@ -37,8 +37,10 @@ pub fn error_string(mut errnum: i32) -> String {
         // `[MS-ERREF]`: https://msdn.microsoft.com/en-us/library/cc231198.aspx
         if (errnum & c::FACILITY_NT_BIT as i32) != 0 {
             // format according to https://support.microsoft.com/en-us/help/259693
-            const NTDLL_DLL: &[u16] = &['N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _,
-                                        '.' as _, 'D' as _, 'L' as _, 'L' as _, 0];
+            const NTDLL_DLL: &[u16] = &[
+                'N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _, '.' as _, 'D' as _, 'L' as _,
+                'L' as _, 0,
+            ];
             module = c::GetModuleHandleW(NTDLL_DLL.as_ptr());
 
             if module != ptr::null_mut() {
@@ -47,19 +49,19 @@ pub fn error_string(mut errnum: i32) -> String {
             }
         }
 
-        let res = c::FormatMessageW(flags | c::FORMAT_MESSAGE_FROM_SYSTEM |
-                                        c::FORMAT_MESSAGE_IGNORE_INSERTS,
-                                    module,
-                                    errnum as c::DWORD,
-                                    langId,
-                                    buf.as_mut_ptr(),
-                                    buf.len() as c::DWORD,
-                                    ptr::null()) as usize;
+        let res = c::FormatMessageW(
+            flags | c::FORMAT_MESSAGE_FROM_SYSTEM | c::FORMAT_MESSAGE_IGNORE_INSERTS,
+            module,
+            errnum as c::DWORD,
+            langId,
+            buf.as_mut_ptr(),
+            buf.len() as c::DWORD,
+            ptr::null(),
+        ) as usize;
         if res == 0 {
             // Sometimes FormatMessageW can fail e.g., system doesn't like langId,
             let fm_err = errno();
-            return format!("OS Error {} (FormatMessageW() returned error {})",
-                           errnum, fm_err);
+            return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
         }
 
         match String::from_utf16(&buf[..res]) {
@@ -68,9 +70,12 @@ pub fn error_string(mut errnum: i32) -> String {
                 let len = msg.trim_end().len();
                 msg.truncate(len);
                 msg
-            },
-            Err(..) => format!("OS Error {} (FormatMessageW() returned \
-                                invalid UTF-16)", errnum),
+            }
+            Err(..) => format!(
+                "OS Error {} (FormatMessageW() returned \
+                 invalid UTF-16)",
+                errnum
+            ),
         }
     }
 }
@@ -86,7 +91,9 @@ impl Iterator for Env {
     fn next(&mut self) -> Option<(OsString, OsString)> {
         loop {
             unsafe {
-                if *self.cur == 0 { return None }
+                if *self.cur == 0 {
+                    return None;
+                }
                 let p = &*self.cur as *const u16;
                 let mut len = 0;
                 while *p.offset(len) != 0 {
@@ -106,8 +113,8 @@ impl Iterator for Env {
                 };
                 return Some((
                     OsStringExt::from_wide(&s[..pos]),
-                    OsStringExt::from_wide(&s[pos+1..]),
-                ))
+                    OsStringExt::from_wide(&s[pos + 1..]),
+                ));
             }
         }
     }
@@ -115,7 +122,9 @@ impl Iterator for Env {
 
 impl Drop for Env {
     fn drop(&mut self) {
-        unsafe { c::FreeEnvironmentStringsW(self.base); }
+        unsafe {
+            c::FreeEnvironmentStringsW(self.base);
+        }
     }
 }
 
@@ -123,8 +132,7 @@ pub fn env() -> Env {
     unsafe {
         let ch = c::GetEnvironmentStringsW();
         if ch as usize == 0 {
-            panic!("failure getting env string from OS: {}",
-                   io::Error::last_os_error());
+            panic!("failure getting env string from OS: {}", io::Error::last_os_error());
         }
         Env { base: ch, cur: ch }
     }
@@ -136,10 +144,7 @@ pub struct SplitPaths<'a> {
 }
 
 pub fn split_paths(unparsed: &OsStr) -> SplitPaths<'_> {
-    SplitPaths {
-        data: unparsed.encode_wide(),
-        must_yield: true,
-    }
+    SplitPaths { data: unparsed.encode_wide(), must_yield: true }
 }
 
 impl<'a> Iterator for SplitPaths<'a> {
@@ -158,7 +163,6 @@ impl<'a> Iterator for SplitPaths<'a> {
         // (The above is based on testing; there is no clear reference available
         // for the grammar.)
 
-
         let must_yield = self.must_yield;
         self.must_yield = false;
 
@@ -169,7 +173,7 @@ impl<'a> Iterator for SplitPaths<'a> {
                 in_quote = !in_quote;
             } else if b == ';' as u16 && !in_quote {
                 self.must_yield = true;
-                break
+                break;
             } else {
                 in_progress.push(b)
             }
@@ -187,17 +191,21 @@ impl<'a> Iterator for SplitPaths<'a> {
 pub struct JoinPathsError;
 
 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
-    where I: Iterator<Item=T>, T: AsRef<OsStr>
+where
+    I: Iterator<Item = T>,
+    T: AsRef<OsStr>,
 {
     let mut joined = Vec::new();
     let sep = b';' as u16;
 
     for (i, path) in paths.enumerate() {
         let path = path.as_ref();
-        if i > 0 { joined.push(sep) }
+        if i > 0 {
+            joined.push(sep)
+        }
         let v = path.encode_wide().collect::<Vec<u16>>();
         if v.contains(&(b'"' as u16)) {
-            return Err(JoinPathsError)
+            return Err(JoinPathsError);
         } else if v.contains(&sep) {
             joined.push(b'"' as u16);
             joined.extend_from_slice(&v[..]);
@@ -217,19 +225,20 @@ impl fmt::Display for JoinPathsError {
 }
 
 impl StdError for JoinPathsError {
-    fn description(&self) -> &str { "failed to join paths" }
+    fn description(&self) -> &str {
+        "failed to join paths"
+    }
 }
 
 pub fn current_exe() -> io::Result<PathBuf> {
-    super::fill_utf16_buf(|buf, sz| unsafe {
-        c::GetModuleFileNameW(ptr::null_mut(), buf, sz)
-    }, super::os2path)
+    super::fill_utf16_buf(
+        |buf, sz| unsafe { c::GetModuleFileNameW(ptr::null_mut(), buf, sz) },
+        super::os2path,
+    )
 }
 
 pub fn getcwd() -> io::Result<PathBuf> {
-    super::fill_utf16_buf(|buf, sz| unsafe {
-        c::GetCurrentDirectoryW(sz, buf)
-    }, super::os2path)
+    super::fill_utf16_buf(|buf, sz| unsafe { c::GetCurrentDirectoryW(sz, buf) }, super::os2path)
 }
 
 pub fn chdir(p: &path::Path) -> io::Result<()> {
@@ -237,18 +246,15 @@ pub fn chdir(p: &path::Path) -> io::Result<()> {
     let mut p = p.encode_wide().collect::<Vec<_>>();
     p.push(0);
 
-    cvt(unsafe {
-        c::SetCurrentDirectoryW(p.as_ptr())
-    }).map(|_| ())
+    cvt(unsafe { c::SetCurrentDirectoryW(p.as_ptr()) }).map(|_| ())
 }
 
 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
     let k = to_u16s(k)?;
-    let res = super::fill_utf16_buf(|buf, sz| unsafe {
-        c::GetEnvironmentVariableW(k.as_ptr(), buf, sz)
-    }, |buf| {
-        OsStringExt::from_wide(buf)
-    });
+    let res = super::fill_utf16_buf(
+        |buf, sz| unsafe { c::GetEnvironmentVariableW(k.as_ptr(), buf, sz) },
+        |buf| OsStringExt::from_wide(buf),
+    );
     match res {
         Ok(value) => Ok(Some(value)),
         Err(e) => {
@@ -265,22 +271,16 @@ pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
     let k = to_u16s(k)?;
     let v = to_u16s(v)?;
 
-    cvt(unsafe {
-        c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr())
-    }).map(|_| ())
+    cvt(unsafe { c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr()) }).map(|_| ())
 }
 
 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
     let v = to_u16s(n)?;
-    cvt(unsafe {
-        c::SetEnvironmentVariableW(v.as_ptr(), ptr::null())
-    }).map(|_| ())
+    cvt(unsafe { c::SetEnvironmentVariableW(v.as_ptr(), ptr::null()) }).map(|_| ())
 }
 
 pub fn temp_dir() -> PathBuf {
-    super::fill_utf16_buf(|buf, sz| unsafe {
-        c::GetTempPathW(sz, buf)
-    }, super::os2path).unwrap()
+    super::fill_utf16_buf(|buf, sz| unsafe { c::GetTempPathW(sz, buf) }, super::os2path).unwrap()
 }
 
 #[cfg(not(target_vendor = "uwp"))]
@@ -291,16 +291,20 @@ fn home_dir_crt() -> Option<PathBuf> {
         let me = c::GetCurrentProcess();
         let mut token = ptr::null_mut();
         if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 {
-            return None
+            return None;
         }
         let _handle = Handle::new(token);
-        super::fill_utf16_buf(|buf, mut sz| {
-            match c::GetUserProfileDirectoryW(token, buf, &mut sz) {
-                0 if c::GetLastError() != c::ERROR_INSUFFICIENT_BUFFER => 0,
-                0 => sz,
-                _ => sz - 1, // sz includes the null terminator
-            }
-        }, super::os2path).ok()
+        super::fill_utf16_buf(
+            |buf, mut sz| {
+                match c::GetUserProfileDirectoryW(token, buf, &mut sz) {
+                    0 if c::GetLastError() != c::ERROR_INSUFFICIENT_BUFFER => 0,
+                    0 => sz,
+                    _ => sz - 1, // sz includes the null terminator
+                }
+            },
+            super::os2path,
+        )
+        .ok()
     }
 }
 
@@ -310,9 +314,10 @@ fn home_dir_crt() -> Option<PathBuf> {
 }
 
 pub fn home_dir() -> Option<PathBuf> {
-    crate::env::var_os("HOME").or_else(|| {
-        crate::env::var_os("USERPROFILE")
-    }).map(PathBuf::from).or_else(|| home_dir_crt())
+    crate::env::var_os("HOME")
+        .or_else(|| crate::env::var_os("USERPROFILE"))
+        .map(PathBuf::from)
+        .or_else(|| home_dir_crt())
 }
 
 pub fn exit(code: i32) -> ! {
@@ -332,7 +337,10 @@ mod tests {
     #[test]
     fn ntstatus_error() {
         const STATUS_UNSUCCESSFUL: u32 = 0xc000_0001;
-        assert!(!Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _)
-            .to_string().contains("FormatMessageW() returned error"));
+        assert!(
+            !Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _)
+                .to_string()
+                .contains("FormatMessageW() returned error")
+        );
     }
 }