Skip to content

Commit

Permalink
refactor: optimize regedit.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
sigoden committed Apr 17, 2024
1 parent 20d60a9 commit d2dbbaf
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
8 changes: 4 additions & 4 deletions src/startup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl Startup {

fn detect() -> Result<bool> {
let key = win_run_key()?;
let value = match key.get_value(HKEY_NAME)? {
let value = match key.get_value()? {
Some(value) => value,
None => return Ok(false),
};
Expand All @@ -45,17 +45,17 @@ impl Startup {
let key = win_run_key()?;
let path = get_exe_path();
let path = unsafe { path.align_to::<u8>().1 };
key.set_value(HKEY_NAME, path)?;
key.set_value(path)?;
Ok(())
}

fn disable() -> Result<()> {
let key = win_run_key()?;
key.delete_value(HKEY_NAME)?;
key.delete_value()?;
Ok(())
}
}

fn win_run_key() -> Result<RegKey> {
RegKey::new_hkcu(HKEY_RUN)
RegKey::new_hkcu(HKEY_RUN, HKEY_NAME)
}
18 changes: 10 additions & 8 deletions src/utils/regedit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ use windows::Win32::System::Registry::{
HKEY_CURRENT_USER, KEY_ALL_ACCESS, REG_SZ, REG_VALUE_TYPE, RRF_RT_REG_SZ,
};

#[derive(Debug)]
pub struct RegKey {
hkey: HKEY,
name: PCWSTR,
}

impl RegKey {
pub fn new_hkcu(subkey: PCWSTR) -> Result<RegKey> {
pub fn new_hkcu(subkey: PCWSTR, name: PCWSTR) -> Result<RegKey> {
let mut hkey = HKEY::default();
unsafe {
RegOpenKeyExW(
Expand All @@ -24,18 +26,18 @@ impl RegKey {
}
.ok()
.map_err(|err| anyhow!("Fail to open reg key, {:?}", err))?;
Ok(RegKey { hkey })
Ok(RegKey { hkey, name })
}

pub fn get_value(&self, name: PCWSTR) -> Result<Option<Vec<u16>>> {
pub fn get_value(&self) -> Result<Option<Vec<u16>>> {
let mut buffer = [0u16; 1024];
let mut size: u32 = (1024 * std::mem::size_of_val(&buffer[0])) as u32;
let mut kind: REG_VALUE_TYPE = Default::default();
let ret = unsafe {
RegGetValueW(
self.hkey,
None,
name,
self.name,
RRF_RT_REG_SZ,
Some(&mut kind),
Some(buffer.as_mut_ptr() as *mut _),
Expand All @@ -55,15 +57,15 @@ impl RegKey {
Ok(Some(buffer[..len].to_vec()))
}

pub fn set_value(&self, name: PCWSTR, value: &[u8]) -> Result<()> {
unsafe { RegSetValueExW(self.hkey, name, 0, REG_SZ, Some(value)) }
pub fn set_value(&self, value: &[u8]) -> Result<()> {
unsafe { RegSetValueExW(self.hkey, self.name, 0, REG_SZ, Some(value)) }
.ok()
.map_err(|err| anyhow!("Fail to write reg value, {:?}", err))?;
Ok(())
}

pub fn delete_value(&self, name: PCWSTR) -> Result<()> {
unsafe { RegDeleteValueW(self.hkey, name) }
pub fn delete_value(&self) -> Result<()> {
unsafe { RegDeleteValueW(self.hkey, self.name) }
.ok()
.map_err(|err| anyhow!("Failed to delete reg value, {:?}", err))?;
Ok(())
Expand Down

0 comments on commit d2dbbaf

Please sign in to comment.