pub struct MemSafe<T> { /* private fields */ }
Expand description
MemSafe
allows for a protected memory space with controlled access to prevent
unauthorized access and ensure memory safety.
§Examples
use memsafe::MemSafe;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut safe_data = MemSafe::new(42)?;
// Read access
{
let reader = safe_data.read()?;
assert_eq!(*reader, 42);
} // reader is dropped, privileges are released
// Write access
{
let mut writer = safe_data.write()?;
*writer = 100;
} // writer is dropped, privileges are released
// Verify the change
{
let reader = safe_data.read()?;
assert_eq!(*reader, 100);
}
}
Implementations§
Source§impl<T> MemSafe<T>
impl<T> MemSafe<T>
Sourcepub fn new(value: T) -> Result<MemSafe<T>, MemoryError>
pub fn new(value: T) -> Result<MemSafe<T>, MemoryError>
Initialize a protected memory region containing the specified value, with lowest possible memory access controls applied.
Lowest access level:
Platform | Read | Write |
---|---|---|
Unix | ❌ | ❌ |
Windows | ✅ | ❌ |
§Errors
Returns a MemoryError
if memory protection could not be initialized.
§Examples
use memsafe::MemSafe;
let safe_data = MemSafe::new([0_u8; 32]).unwrap();
Sourcepub fn read(&mut self) -> Result<MemSafeRead<'_, T>, MemoryError>
pub fn read(&mut self) -> Result<MemSafeRead<'_, T>, MemoryError>
Obtains read-only access to the protected memory region. This method temporarily
elevates the read privileges and returns a handle that implements Deref
for
accessing the inner value. When the returned MemSafeRead
is dropped,
privileges are automatically revoked on Unix-based OSes.
§Errors
Returns a MemoryError
if privilege elevation fails.
Sourcepub fn write(&mut self) -> Result<MemSafeWrite<'_, T>, MemoryError>
pub fn write(&mut self) -> Result<MemSafeWrite<'_, T>, MemoryError>
Obtains mutable access to the protected memory region. This method temporarily
elevates the read and write privileges and returns a handle that implements Deref
and DerefMut
for modifying the inner value. When the returned MemSafeWrite
is
dropped, privileges are automatically revoked on Unix-based OSes. On Windows read,
privileges are maintained while write privileges are revoked.
§Errors
Returns a MemoryError
if privilege elevation fails.