Debian Codegraph @

third_party/rust/winreg/src/transaction.rs

raw
1 // Copyright 2015, Igor Shaula
2 // Licensed under the MIT License <LICENSE or
3 // http://opensource.org/licenses/MIT>. This file
4 // may not be copied, modified, or distributed
5 // except according to those terms.
6
7 //! Structure for a registry transaction.
8 //! Part of `transactions` feature.
9 //!
10 //!```no_run
11 //!extern crate winreg;
12 //!use std::io;
13 //!use winreg::RegKey;
14 //!use winreg::enums::*;
15 //!use winreg::transaction::Transaction;
16 //!
17 //!fn main() {
18 //! let t = Transaction::new().unwrap();
19 //! let hkcu = RegKey::predef(HKEY_CURRENT_USER);
20 //! let (key, _disp) = hkcu.create_subkey_transacted("Software\\RustTransaction", &t).unwrap();
21 //! key.set_value("TestQWORD", &1234567891011121314u64).unwrap();
22 //! key.set_value("TestDWORD", &1234567890u32).unwrap();
23 //!
24 //! println!("Commit transaction? [y/N]:");
25 //! let mut input = String::new();
26 //! io::stdin().read_line(&mut input).unwrap();
27 //! input = input.trim_right().to_owned();
28 //! if input == "y" || input == "Y" {
29 //! t.commit().unwrap();
30 //! println!("Transaction committed.");
31 //! }
32 //! else {
33 //! // this is optional, if transaction wasn't committed,
34 //! // it will be rolled back on disposal
35 //! t.rollback().unwrap();
36 //!
37 //! println!("Transaction wasn't committed, it will be rolled back.");
38 //! }
39 //!}
40 //!```
41 #![cfg(feature = "transactions")]
42 use std::io;
43 use std::ptr;
44 use winapi::um::handleapi;
45 use winapi::um::ktmw32;
46 use winapi::um::winnt;
47
48 #[derive(Debug)]
49 pub struct Transaction {
50 pub handle: winnt::HANDLE,
51 }
52
53 impl Transaction {
54 //TODO: add arguments
55 pub fn new() -> io::Result<Transaction> {
56 unsafe {
57 let handle = ktmw32::CreateTransaction(
58 ptr::null_mut(),
59 ptr::null_mut(),
60 0,
61 0,
62 0,
63 0,
64 ptr::null_mut(),
65 );
66 if handle == handleapi::INVALID_HANDLE_VALUE {
67 return Err(io::Error::last_os_error());
68 };
69 Ok(Transaction { handle })
70 }
71 }
72
73 pub fn commit(&self) -> io::Result<()> {
74 unsafe {
75 match ktmw32::CommitTransaction(self.handle) {
76 0 => Err(io::Error::last_os_error()),
77 _ => Ok(()),
78 }
79 }
80 }
81
82 pub fn rollback(&self) -> io::Result<()> {
83 unsafe {
84 match ktmw32::RollbackTransaction(self.handle) {
85 0 => Err(io::Error::last_os_error()),
86 _ => Ok(()),
87 }
88 }
89 }
90
91 fn close_(&mut self) -> io::Result<()> {
92 unsafe {
93 match handleapi::CloseHandle(self.handle) {
94 0 => Err(io::Error::last_os_error()),
95 _ => Ok(()),
96 }
97 }
98 }
99 }
100
101 impl Drop for Transaction {
102 fn drop(&mut self) {
103 self.close_().unwrap_or(());
104 }
105 }