extern crate alloc;
mod info;
pub use info::*;
mod protection;
pub use protection::*;
use crate::{internal::protect, terminated_array, FaitheError};
#[inline]
pub unsafe fn follow_pointer_path<const I: usize, T>(
mut base: *const u8,
offsets: [usize; I],
) -> *const T {
for offset in &offsets {
base = *((base as usize + *offset) as *const usize) as _;
}
base as _
}
#[inline]
pub unsafe fn read_string<'a>(ptr: *const i8) -> crate::Result<&'a str> {
core::str::from_utf8(terminated_array(ptr as *const u8, &0))
.map_err(|_| FaitheError::InvalidString)
}
#[inline]
pub unsafe fn read_string_unchecked<'a>(ptr: *const i8) -> &'a str {
read_string(ptr).unwrap()
}
#[inline]
pub unsafe fn read_wide_string<'a>(ptr: *const u16) -> crate::Result<alloc::string::String> {
alloc::string::String::from_utf16(terminated_array(ptr, &0))
.map_err(|_| FaitheError::InvalidString)
}
#[inline]
pub unsafe fn read_wide_string_unchecked<'a>(ptr: *const u16) -> alloc::string::String {
read_wide_string(ptr).unwrap()
}
#[inline]
pub fn guard<T>(
address: *mut (),
size: usize,
protection: MemoryProtection,
callback: impl FnOnce() -> T,
) -> T {
let old = crate::__expect!(
protect(address, size, protection),
"Failed to protect memory."
);
let val = callback();
crate::__expect!(
protect(address, size, old),
"Failed to restore previous protection"
);
val
}