hooking 0.7.0

cross platform detour / hooking library in rust
Documentation
use std::ffi::c_void;
use std::ptr::NonNull;

use crate::error::Result;
use crate::patch::PatchWriter;

/// Whether a hook's patch is written over its target, and the patcher that
/// writes it. Shared by every kind of hook.
#[derive(Debug)]
pub(super) struct PatchState<'a> {
    patcher: &'a dyn PatchWriter,
    is_applied: bool,
}

impl<'a> PatchState<'a> {
    pub(super) fn new(patcher: &'a dyn PatchWriter) -> Self {
        Self {
            patcher,
            is_applied: false,
        }
    }

    pub(super) fn is_applied(&self) -> bool {
        self.is_applied
    }

    /// Write `patch` over `target`, unless it is already applied.
    ///
    /// # Safety
    /// As for [`PatchWriter::write`].
    pub(super) unsafe fn apply(&mut self, target: NonNull<c_void>, patch: &[u8]) -> Result<()> {
        if self.is_applied {
            return Ok(());
        }
        unsafe { self.patcher.write(target.cast(), patch)? };
        self.is_applied = true;
        Ok(())
    }

    /// Write `original` back over `target`, unless the patch isn't applied.
    ///
    /// # Safety
    /// As for [`PatchWriter::write`].
    pub(super) unsafe fn remove(&mut self, target: NonNull<c_void>, original: &[u8]) -> Result<()> {
        if !self.is_applied {
            return Ok(());
        }
        unsafe { self.patcher.write(target.cast(), original)? };
        self.is_applied = false;
        Ok(())
    }
}