Debian Codegraph @

third_party/rust/winreg/README.md

raw
1 winreg
2 [![Winreg on Appveyor][appveyor-image]][appveyor]
3 [![Winreg on crates.io][cratesio-image]][cratesio]
4 [![Winreg on docs.rs][docsrs-image]][docsrs]
5 ======
6
7 [appveyor-image]: https://ci.appveyor.com/api/projects/status/f3lwrt67ghrf5omd?svg=true
8 [appveyor]: https://ci.appveyor.com/project/gentoo90/winreg-rs
9 [cratesio-image]: https://img.shields.io/crates/v/winreg.svg
10 [cratesio]: https://crates.io/crates/winreg
11 [docsrs-image]: https://docs.rs/winreg/badge.svg
12 [docsrs]: https://docs.rs/winreg
13
14 Rust bindings to MS Windows Registry API. Work in progress.
15
16 Current features:
17 * Basic registry operations:
18 * open/create/delete keys
19 * load application hive from a file
20 * read and write values
21 * seamless conversion between `REG_*` types and rust primitives
22 * `String` and `OsString` <= `REG_SZ`, `REG_EXPAND_SZ` or `REG_MULTI_SZ`
23 * `String`, `&str`, `OsString`, `&OsStr` => `REG_SZ`
24 * `Vec<String>`, `Vec<OsString>` <= `REG_MULTI_SZ`
25 * `Vec<String>`, `Vec<&str>`, `Vec<OsString>`, `Vec<&OsStr>` => `REG_MULTI_SZ`
26 * `u32` <=> `REG_DWORD`
27 * `u64` <=> `REG_QWORD`
28 * Iteration through key names and through values
29 * Transactions
30 * Transacted serialization of rust types into/from registry (only primitives, structures and maps for now)
31
32 ## Usage
33
34 ### Basic usage
35
36 ```toml
37 # Cargo.toml
38 [dependencies]
39 winreg = "0.10"
40 ```
41
42 ```rust
43 extern crate winreg;
44 use std::io;
45 use std::path::Path;
46 use winreg::enums::*;
47 use winreg::RegKey;
48
49 fn main() -> io::Result<()> {
50 println!("Reading some system info...");
51 let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
52 let cur_ver = hklm.open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion")?;
53 let pf: String = cur_ver.get_value("ProgramFilesDir")?;
54 let dp: String = cur_ver.get_value("DevicePath")?;
55 println!("ProgramFiles = {}\nDevicePath = {}", pf, dp);
56 let info = cur_ver.query_info()?;
57 println!("info = {:?}", info);
58 let mt = info.get_last_write_time_system();
59 println!(
60 "last_write_time as winapi::um::minwinbase::SYSTEMTIME = {}-{:02}-{:02} {:02}:{:02}:{:02}",
61 mt.wYear, mt.wMonth, mt.wDay, mt.wHour, mt.wMinute, mt.wSecond
62 );
63
64 // enable `chrono` feature on `winreg` to make this work
65 // println!(
66 // "last_write_time as chrono::NaiveDateTime = {}",
67 // info.get_last_write_time_chrono()
68 // );
69
70 println!("And now lets write something...");
71 let hkcu = RegKey::predef(HKEY_CURRENT_USER);
72 let path = Path::new("Software").join("WinregRsExample1");
73 let (key, disp) = hkcu.create_subkey(&path)?;
74
75 match disp {
76 REG_CREATED_NEW_KEY => println!("A new key has been created"),
77 REG_OPENED_EXISTING_KEY => println!("An existing key has been opened"),
78 }
79
80 key.set_value("TestSZ", &"written by Rust")?;
81 let sz_val: String = key.get_value("TestSZ")?;
82 key.delete_value("TestSZ")?;
83 println!("TestSZ = {}", sz_val);
84
85 key.set_value("TestMultiSZ", &vec!["written", "by", "Rust"])?;
86 let multi_sz_val: Vec<String> = key.get_value("TestMultiSZ")?;
87 key.delete_value("TestMultiSZ")?;
88 println!("TestMultiSZ = {:?}", multi_sz_val);
89
90 key.set_value("TestDWORD", &1234567890u32)?;
91 let dword_val: u32 = key.get_value("TestDWORD")?;
92 println!("TestDWORD = {}", dword_val);
93
94 key.set_value("TestQWORD", &1234567891011121314u64)?;
95 let qword_val: u64 = key.get_value("TestQWORD")?;
96 println!("TestQWORD = {}", qword_val);
97
98 key.create_subkey("sub\\key")?;
99 hkcu.delete_subkey_all(&path)?;
100
101 println!("Trying to open nonexistent key...");
102 hkcu.open_subkey(&path).unwrap_or_else(|e| match e.kind() {
103 io::ErrorKind::NotFound => panic!("Key doesn't exist"),
104 io::ErrorKind::PermissionDenied => panic!("Access denied"),
105 _ => panic!("{:?}", e),
106 });
107 Ok(())
108 }
109 ```
110
111 ### Iterators
112
113 ```rust
114 extern crate winreg;
115 use std::io;
116 use winreg::RegKey;
117 use winreg::enums::*;
118
119 fn main() -> io::Result<()> {
120 println!("File extensions, registered in system:");
121 for i in RegKey::predef(HKEY_CLASSES_ROOT)
122 .enum_keys().map(|x| x.unwrap())
123 .filter(|x| x.starts_with("."))
124 {
125 println!("{}", i);
126 }
127
128 let system = RegKey::predef(HKEY_LOCAL_MACHINE)
129 .open_subkey("HARDWARE\\DESCRIPTION\\System")?;
130 for (name, value) in system.enum_values().map(|x| x.unwrap()) {
131 println!("{} = {:?}", name, value);
132 }
133
134 Ok(())
135 }
136 ```
137
138 ### Transactions
139
140 ```toml
141 # Cargo.toml
142 [dependencies]
143 winreg = { version = "0.10", features = ["transactions"] }
144 ```
145
146 ```rust
147 extern crate winreg;
148 use std::io;
149 use winreg::RegKey;
150 use winreg::enums::*;
151 use winreg::transaction::Transaction;
152
153 fn main() -> io::Result<()> {
154 let t = Transaction::new()?;
155 let hkcu = RegKey::predef(HKEY_CURRENT_USER);
156 let (key, _disp) = hkcu.create_subkey_transacted("Software\\RustTransaction", &t)?;
157 key.set_value("TestQWORD", &1234567891011121314u64)?;
158 key.set_value("TestDWORD", &1234567890u32)?;
159
160 println!("Commit transaction? [y/N]:");
161 let mut input = String::new();
162 io::stdin().read_line(&mut input)?;
163 input = input.trim_right().to_owned();
164 if input == "y" || input == "Y" {
165 t.commit()?;
166 println!("Transaction committed.");
167 }
168 else {
169 // this is optional, if transaction wasn't committed,
170 // it will be rolled back on disposal
171 t.rollback()?;
172
173 println!("Transaction wasn't committed, it will be rolled back.");
174 }
175
176 Ok(())
177 }
178 ```
179
180 ### Serialization
181
182 ```toml
183 # Cargo.toml
184 [dependencies]
185 winreg = { version = "0.10", features = ["serialization-serde"] }
186 serde = "1"
187 serde_derive = "1"
188 ```
189
190 ```rust
191 #[macro_use]
192 extern crate serde_derive;
193 extern crate winreg;
194 use std::collections::HashMap;
195 use std::error::Error;
196 use winreg::enums::*;
197
198 #[derive(Debug, Serialize, Deserialize, PartialEq)]
199 struct Coords {
200 x: u32,
201 y: u32,
202 }
203
204 #[derive(Debug, Serialize, Deserialize, PartialEq)]
205 struct Size {
206 w: u32,
207 h: u32,
208 }
209
210 #[derive(Debug, Serialize, Deserialize, PartialEq)]
211 struct Rectangle {
212 coords: Coords,
213 size: Size,
214 }
215
216 #[derive(Debug, Serialize, Deserialize, PartialEq)]
217 struct Test {
218 t_bool: bool,
219 t_u8: u8,
220 t_u16: u16,
221 t_u32: u32,
222 t_u64: u64,
223 t_usize: usize,
224 t_struct: Rectangle,
225 t_map: HashMap<String, u32>,
226 t_string: String,
227 #[serde(rename = "")] // empty name becomes the (Default) value in the registry
228 t_char: char,
229 t_i8: i8,
230 t_i16: i16,
231 t_i32: i32,
232 t_i64: i64,
233 t_isize: isize,
234 t_f64: f64,
235 t_f32: f32,
236 }
237
238 fn main() -> Result<(), Box<dyn Error>> {
239 let hkcu = winreg::RegKey::predef(HKEY_CURRENT_USER);
240 let (key, _disp) = hkcu.create_subkey("Software\\RustEncode")?;
241
242 let mut map = HashMap::new();
243 map.insert("".to_owned(), 0); // empty name becomes the (Default) value in the registry
244 map.insert("v1".to_owned(), 1);
245 map.insert("v2".to_owned(), 2);
246 map.insert("v3".to_owned(), 3);
247
248 let v1 = Test {
249 t_bool: false,
250 t_u8: 127,
251 t_u16: 32768,
252 t_u32: 123_456_789,
253 t_u64: 123_456_789_101_112,
254 t_usize: 1_234_567_891,
255 t_struct: Rectangle {
256 coords: Coords { x: 55, y: 77 },
257 size: Size { w: 500, h: 300 },
258 },
259 t_map: map,
260 t_string: "test 123!".to_owned(),
261 t_char: 'a',
262 t_i8: -123,
263 t_i16: -2049,
264 t_i32: 20100,
265 t_i64: -12_345_678_910,
266 t_isize: -1_234_567_890,
267 t_f64: -0.01,
268 t_f32: 3.15,
269 };
270
271 key.encode(&v1)?;
272
273 let v2: Test = key.decode()?;
274 println!("Decoded {:?}", v2);
275
276 println!("Equal to encoded: {:?}", v1 == v2);
277 Ok(())
278 }
279 ```
280
281 ## Changelog
282
283 ### 0.10.1
284
285 * Bump minimal required version of `winapi` to `0.3.9` (required for `load_app_key`)
286 * Reexport `REG_PROCESS_APPKEY` and use it in the `load_app_key` example
287
288 ### 0.10.0
289
290 * Add `RegKey::load_app_key()` and `RegKey::load_app_key_with_flags()` ([#30](https://github.com/gentoo90/winreg-rs/issues/30))
291 * Update dev dependency `rand` to `0.8`
292 * Add Github actions
293 * Fix some clippy warnings
294
295 ### 0.9.0
296
297 * Breaking change: `OsStr` and `OsString` registry values are not `NULL`-terminated any more ([#34](https://github.com/gentoo90/winreg-rs/issues/34), [#42](https://github.com/gentoo90/winreg-rs/issues/42))
298 * Refactoring: use macros for `ToRegValue` impls and tests for string values
299 * Fix `bare_trait_objects` warning in the doctests
300 * Add `impl ToRegValue for OsString`
301 * Add conversion between `REG_MULTI_SZ` and vectors of strings ([#16](https://github.com/gentoo90/winreg-rs/issues/16))
302 * Fix: set minimal `winapi` version to 0.3.7 (earlier versions don't have `impl-default` and `impl-debug` features which we use)
303 * Appveyor now checks the crate against `rust-1.31.1` too
304
305 ### 0.8.0
306
307 * Implement serialization of `char` and maps
308 * Implement `std::fmt::Display` for `RegValue`
309 * Make `RegKey::{predef,raw_handle,enum_keys,enum_values}` functions `const`
310 * Give a better error message when compiling on platforms other than Windows ([#38](https://github.com/gentoo90/winreg-rs/pull/38))
311 * Tests are moved from `src/lib.rs` to `tests/reg_key.rs`
312
313 ### 0.7.0
314
315 * Breaking change: remove deprecated `Error::description` ([#28](https://github.com/gentoo90/winreg-rs/pull/28))
316 * Optimize `Iterator::nth()` for the `Enum*` iterators ([#29](https://github.com/gentoo90/winreg-rs/pull/29))
317
318 ### 0.6.2
319
320 * Add `RegKey::delete_subkey_with_flags()` ([#27](https://github.com/gentoo90/winreg-rs/pull/27))
321
322 ### 0.6.1
323
324 * Add `last_write_time` field to `RegKeyMetadata` (returned by `RegKey::query_info()`) ([#25](https://github.com/gentoo90/winreg-rs/pull/25)).
325 * Add `get_last_write_time_system()` and `get_last_write_time_chrono()` (under `chrono` feature) methods to `RegKeyMetadata`.
326
327 ### 0.6.0
328
329 * Breaking change: `create_subkey`, `create_subkey_with_flags`, `create_subkey_transacted` and
330 `create_subkey_transacted_with_flags` now return a tuple which contains the subkey and its disposition
331 which can be `REG_CREATED_NEW_KEY` or `REG_OPENED_EXISTING_KEY` ([#21](https://github.com/gentoo90/winreg-rs/issues/21)).
332 * Examples fixed to not use `unwrap` according to [Rust API guidelines](https://rust-lang-nursery.github.io/api-guidelines/documentation.html#examples-use--not-try-not-unwrap-c-question-mark).
333
334 ### 0.5.1
335
336 * Reexport `HKEY` ([#15](https://github.com/gentoo90/winreg-rs/issues/15)).
337 * Add `raw_handle` method ([#18](https://github.com/gentoo90/winreg-rs/pull/18)).
338
339 ### 0.5.0
340
341 * Breaking change: `open_subkey` now opens a key with readonly permissions.
342 Use `create_subkey` or `open_subkey_with_flags` to open with read-write permissins.
343 * Breaking change: features `transactions` and `serialization-serde` are now disabled by default.
344 * Breaking change: serialization now uses `serde` instead of `rustc-serialize`.
345 * `winapi` updated to `0.3`.
346 * Documentation fixes ([#14](https://github.com/gentoo90/winreg-rs/pull/14))
347
348 ### 0.4.0
349
350 * Make transactions and serialization otional features
351 * Update dependensies + minor fixes ([#12](https://github.com/gentoo90/winreg-rs/pull/12))
352
353 ### 0.3.5
354
355 * Implement `FromRegValue` for `OsString` and `ToRegValue` for `OsStr` ([#8](https://github.com/gentoo90/winreg-rs/issues/8))
356 * Minor fixes
357
358 ### 0.3.4
359
360 * Add `copy_tree` method to `RegKey`
361 * Now checked with [rust-clippy](https://github.com/Manishearth/rust-clippy)
362 * no more `unwrap`s
363 * replaced `to_string` with `to_owned`
364 * Fix: reading strings longer than 2048 characters ([#6](https://github.com/gentoo90/winreg-rs/pull/6))
365
366 ### 0.3.3
367
368 * Fix: now able to read values longer than 2048 bytes ([#3](https://github.com/gentoo90/winreg-rs/pull/3))
369
370 ### 0.3.2
371
372 * Fix: `FromRegValue` trait now requires `Sized` (fixes build with rust 1.4)
373
374 ### 0.3.1
375
376 * Fix: bump `winapi` version to fix build
377
378 ### 0.3.0
379
380 * Add transactions support and make serialization transacted
381 * Breaking change: use `std::io::{Error,Result}` instead of own `RegError` and `RegResult`