]> git.proxmox.com Git - rustc.git/blob - src/vendor/cmake/src/registry.rs
New upstream version 1.17.0+dfsg1
[rustc.git] / src / vendor / cmake / src / registry.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::ffi::OsStr;
12 use std::io;
13 use std::os::raw;
14 use std::os::windows::prelude::*;
15
16 pub struct RegistryKey(Repr);
17
18 type HKEY = *mut u8;
19 type DWORD = u32;
20 type LPCWSTR = *const u16;
21 type LONG = raw::c_long;
22 type PHKEY = *mut HKEY;
23 type REGSAM = u32;
24
25 const ERROR_SUCCESS: DWORD = 0;
26 const HKEY_LOCAL_MACHINE: HKEY = 0x80000002 as HKEY;
27 const KEY_READ: DWORD = 0x20019;
28 const KEY_WOW64_32KEY: DWORD = 0x200;
29
30 #[link(name = "advapi32")]
31 extern "system" {
32 fn RegOpenKeyExW(key: HKEY,
33 lpSubKey: LPCWSTR,
34 ulOptions: DWORD,
35 samDesired: REGSAM,
36 phkResult: PHKEY) -> LONG;
37 fn RegCloseKey(hKey: HKEY) -> LONG;
38 }
39
40 struct OwnedKey(HKEY);
41
42 enum Repr {
43 Const(HKEY),
44 Owned(OwnedKey),
45 }
46
47 unsafe impl Sync for Repr {}
48 unsafe impl Send for Repr {}
49
50 pub static LOCAL_MACHINE: RegistryKey =
51 RegistryKey(Repr::Const(HKEY_LOCAL_MACHINE));
52
53 impl RegistryKey {
54 fn raw(&self) -> HKEY {
55 match self.0 {
56 Repr::Const(val) => val,
57 Repr::Owned(ref val) => val.0,
58 }
59 }
60
61 pub fn open(&self, key: &OsStr) -> io::Result<RegistryKey> {
62 let key = key.encode_wide().chain(Some(0)).collect::<Vec<_>>();
63 let mut ret = 0 as *mut _;
64 let err = unsafe {
65 RegOpenKeyExW(self.raw(), key.as_ptr(), 0,
66 KEY_READ | KEY_WOW64_32KEY, &mut ret)
67 };
68 if err == ERROR_SUCCESS as LONG {
69 Ok(RegistryKey(Repr::Owned(OwnedKey(ret))))
70 } else {
71 Err(io::Error::from_raw_os_error(err as i32))
72 }
73 }
74 }
75
76 impl Drop for OwnedKey {
77 fn drop(&mut self) {
78 unsafe { RegCloseKey(self.0); }
79 }
80 }