windows_registry/
key.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
use super::*;

/// A registry key.
#[repr(transparent)]
#[derive(Debug)]
pub struct Key(pub(crate) HKEY);

impl Default for Key {
    fn default() -> Self {
        Self(null_mut())
    }
}

impl Key {
    /// Creates a registry key. If the key already exists, the function opens it.
    pub fn create<T: AsRef<str>>(&self, path: T) -> Result<Self> {
        let mut handle = null_mut();

        let result = unsafe {
            RegCreateKeyExW(
                self.0,
                pcwstr(path).as_ptr(),
                0,
                null(),
                REG_OPTION_NON_VOLATILE,
                KEY_READ | KEY_WRITE,
                null(),
                &mut handle,
                null_mut(),
            )
        };

        win32_error(result).map(|_| Self(handle))
    }

    /// Opens a registry key.
    pub fn open<T: AsRef<str>>(&self, path: T) -> Result<Self> {
        let mut handle = null_mut();

        let result =
            unsafe { RegOpenKeyExW(self.0, pcwstr(path).as_ptr(), 0, KEY_READ, &mut handle) };

        win32_error(result).map(|_| Self(handle))
    }

    /// Constructs a registry key from an existing handle.
    ///
    /// # Safety
    ///
    /// This function takes ownership of the handle.
    /// The handle must be owned by the caller and safe to free with `RegCloseKey`.
    pub unsafe fn from_raw(handle: *mut core::ffi::c_void) -> Self {
        Self(handle)
    }

    /// Returns the underlying registry key handle.
    pub fn as_raw(&self) -> *mut core::ffi::c_void {
        self.0
    }

    /// Removes the registry keys and values of the specified key recursively.
    pub fn remove_tree<T: AsRef<str>>(&self, path: T) -> Result<()> {
        let result = unsafe { RegDeleteTreeW(self.0, pcwstr(path).as_ptr()) };
        win32_error(result)
    }

    /// Removes the registry value.
    pub fn remove_value<T: AsRef<str>>(&self, name: T) -> Result<()> {
        let result = unsafe { RegDeleteValueW(self.0, pcwstr(name).as_ptr()) };
        win32_error(result)
    }

    /// Creates an iterator of registry key names.
    pub fn keys(&self) -> Result<KeyIterator<'_>> {
        KeyIterator::new(self)
    }

    /// Creates an iterator of registry values.
    pub fn values(&self) -> Result<ValueIterator<'_>> {
        ValueIterator::new(self)
    }

    /// Sets the name and value in the registry key.
    pub fn set_u32<T: AsRef<str>>(&self, name: T, value: u32) -> Result<()> {
        self.set_bytes(name, Type::U32, &value.to_le_bytes())
    }

    /// Sets the name and value in the registry key.
    pub fn set_u64<T: AsRef<str>>(&self, name: T, value: u64) -> Result<()> {
        self.set_bytes(name, Type::U64, &value.to_le_bytes())
    }

    /// Sets the name and value in the registry key.
    pub fn set_string<T: AsRef<str>>(&self, name: T, value: T) -> Result<()> {
        self.set_bytes(name, Type::String, pcwstr(value).as_bytes())
    }

    /// Sets the name and value in the registry key.
    pub fn set_hstring<T: AsRef<str>>(
        &self,
        name: T,
        value: &windows_strings::HSTRING,
    ) -> Result<()> {
        self.set_bytes(name, Type::String, as_bytes(value))
    }

    /// Sets the name and value in the registry key.
    pub fn set_expand_string<T: AsRef<str>>(&self, name: T, value: T) -> Result<()> {
        self.set_bytes(name, Type::ExpandString, pcwstr(value).as_bytes())
    }

    /// Sets the name and value in the registry key.
    pub fn set_expand_hstring<T: AsRef<str>>(
        &self,
        name: T,
        value: &windows_strings::HSTRING,
    ) -> Result<()> {
        self.set_bytes(name, Type::ExpandString, as_bytes(value))
    }

    /// Sets the name and value in the registry key.
    pub fn set_multi_string<T: AsRef<str>>(&self, name: T, value: &[T]) -> Result<()> {
        let value = multi_pcwstr(value);
        self.set_bytes(name, Type::MultiString, value.as_bytes())
    }

    /// Sets the name and value in the registry key.
    pub fn set_value<T: AsRef<str>>(&self, name: T, value: &Value) -> Result<()> {
        self.set_bytes(name, value.ty(), value)
    }

    /// Sets the name and value in the registry key.
    pub fn set_bytes<T: AsRef<str>>(&self, name: T, ty: Type, value: &[u8]) -> Result<()> {
        unsafe { self.raw_set_bytes(pcwstr(name).as_raw(), ty, value) }
    }

    /// Gets the type for the name in the registry key.
    pub fn get_type<T: AsRef<str>>(&self, name: T) -> Result<Type> {
        let (ty, _) = unsafe { self.raw_get_info(pcwstr(name).as_raw())? };
        Ok(ty)
    }

    /// Gets the value for the name in the registry key.
    pub fn get_value<T: AsRef<str>>(&self, name: T) -> Result<Value> {
        let name = pcwstr(name);
        let (ty, len) = unsafe { self.raw_get_info(name.as_raw())? };
        let mut data = Data::new(len);
        unsafe { self.raw_get_bytes(name.as_raw(), &mut data)? };
        Ok(Value { data, ty })
    }

    /// Gets the value for the name in the registry key.
    pub fn get_u32<T: AsRef<str>>(&self, name: T) -> Result<u32> {
        Ok(self.get_u64(name)?.try_into()?)
    }

    /// Gets the value for the name in the registry key.
    pub fn get_u64<T: AsRef<str>>(&self, name: T) -> Result<u64> {
        let value = &mut [0; 8];
        let (ty, value) = unsafe { self.raw_get_bytes(pcwstr(name).as_raw(), value)? };
        from_le_bytes(ty, value)
    }

    /// Gets the value for the name in the registry key.
    pub fn get_string<T: AsRef<str>>(&self, name: T) -> Result<String> {
        self.get_value(name)?.try_into()
    }

    /// Gets the value for the name in the registry key.
    pub fn get_hstring<T: AsRef<str>>(&self, name: T) -> Result<HSTRING> {
        let name = pcwstr(name);
        let (ty, len) = unsafe { self.raw_get_info(name.as_raw())? };

        if !matches!(ty, Type::String | Type::ExpandString) {
            return Err(invalid_data());
        }

        let mut value = HStringBuilder::new(len / 2);
        unsafe { self.raw_get_bytes(name.as_raw(), value.as_bytes_mut())? };
        value.trim_end();
        Ok(value.into())
    }

    /// Gets the value for the name in the registry key.
    pub fn get_multi_string<T: AsRef<str>>(&self, name: T) -> Result<Vec<String>> {
        self.get_value(name)?.try_into()
    }

    /// Sets the name and value in the registry key.
    ///
    /// This method avoids any allocations.
    ///
    /// # Safety
    ///
    /// The `PCWSTR` pointer needs to be valid for reads up until and including the next `\0`.
    #[track_caller]
    pub unsafe fn raw_set_bytes<N: AsRef<PCWSTR>>(
        &self,
        name: N,
        ty: Type,
        value: &[u8],
    ) -> Result<()> {
        if cfg!(debug_assertions) {
            // RegSetValueExW expects string data to be null terminated.
            if matches!(ty, Type::String | Type::ExpandString | Type::MultiString) {
                debug_assert!(
                    value.get(value.len() - 2) == Some(&0),
                    "`value` isn't null-terminated"
                );
                debug_assert!(value.last() == Some(&0), "`value` isn't null-terminated");
            }
        }

        let result = RegSetValueExW(
            self.0,
            name.as_ref().as_ptr(),
            0,
            ty.into(),
            value.as_ptr(),
            value.len().try_into()?,
        );

        win32_error(result)
    }

    /// Gets the type and length for the name in the registry key.
    ///
    /// This method avoids any allocations.
    ///
    /// # Safety
    ///
    /// The `PCWSTR` pointer needs to be valid for reads up until and including the next `\0`.
    pub unsafe fn raw_get_info<N: AsRef<PCWSTR>>(&self, name: N) -> Result<(Type, usize)> {
        let mut ty = 0;
        let mut len = 0;

        let result = RegQueryValueExW(
            self.0,
            name.as_ref().as_ptr(),
            null(),
            &mut ty,
            core::ptr::null_mut(),
            &mut len,
        );

        win32_error(result)?;
        Ok((ty.into(), len as usize))
    }

    /// Gets the value for the name in the registry key.
    ///
    /// This method avoids any allocations.
    ///
    /// # Safety
    ///
    /// The `PCWSTR` pointer needs to be valid for reads up until and including the next `\0`.
    pub unsafe fn raw_get_bytes<'a, N: AsRef<PCWSTR>>(
        &self,
        name: N,
        value: &'a mut [u8],
    ) -> Result<(Type, &'a [u8])> {
        let mut ty = 0;
        let mut len = value.len().try_into()?;

        let result = RegQueryValueExW(
            self.0,
            name.as_ref().as_ptr(),
            null(),
            &mut ty,
            value.as_mut_ptr(),
            &mut len,
        );

        win32_error(result)?;
        Ok((ty.into(), value.get(0..len as usize).unwrap()))
    }
}

impl Drop for Key {
    fn drop(&mut self) {
        unsafe {
            RegCloseKey(self.0);
        }
    }
}