windows_registry/
transaction.rs

1use super::*;
2
3/// A transaction object.
4#[repr(transparent)]
5#[derive(Debug)]
6pub struct Transaction(pub(crate) HANDLE);
7
8impl Transaction {
9    /// Creates a new transaction.
10    pub fn new() -> Result<Self> {
11        let handle = unsafe { CreateTransaction(null_mut(), null_mut(), 0, 0, 0, 0, null()) };
12
13        if core::ptr::eq(handle, INVALID_HANDLE_VALUE) {
14            Err(Error::from_win32())
15        } else {
16            Ok(Self(handle))
17        }
18    }
19
20    /// Commits the transaction.
21    ///
22    /// The transaction rolls back if it is dropped before `commit` is called.
23    pub fn commit(self) -> Result<()> {
24        let result = unsafe { CommitTransaction(self.0) };
25
26        if result == 0 {
27            Err(Error::from_win32())
28        } else {
29            Ok(())
30        }
31    }
32
33    /// Constructs a transaction object from an existing handle.
34    ///
35    /// # Safety
36    ///
37    /// This function takes ownership of the handle.
38    /// The handle must be owned by the caller and safe to free with `CloseHandle`.
39    pub unsafe fn from_raw(handle: *mut core::ffi::c_void) -> Self {
40        Self(handle)
41    }
42
43    /// Returns the underlying transaction handle.
44    pub fn as_raw(&self) -> *mut core::ffi::c_void {
45        self.0
46    }
47}
48
49impl Drop for Transaction {
50    fn drop(&mut self) {
51        unsafe { CloseHandle(self.0) };
52    }
53}