use core::ffi::c_void;
pub unsafe fn freezero(ptr: *mut c_void, size: usize) {
unsafe {
if !ptr.is_null() {
libc::memset(ptr, 0, size);
libc::free(ptr);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_freezero_frees_allocation() {
unsafe {
let p = libc::malloc(64);
assert!(!p.is_null());
libc::memset(p, 0xAB, 64);
freezero(p, 64);
}
}
#[test]
fn test_freezero_null_is_noop() {
unsafe {
freezero(core::ptr::null_mut(), 0);
freezero(core::ptr::null_mut(), 128);
}
}
#[test]
fn test_freezero_zero_size_allocation() {
unsafe {
let p = libc::malloc(16);
assert!(!p.is_null());
freezero(p, 0);
}
}
#[test]
fn test_freezero_various_sizes() {
unsafe {
for &sz in &[1usize, 7, 64, 1024, 4096] {
let p = libc::malloc(sz);
assert!(!p.is_null(), "malloc({sz}) failed");
libc::memset(p, 0xCD, sz);
freezero(p, sz);
}
}
}
#[test]
fn test_freezero_size_smaller_than_alloc() {
unsafe {
let p = libc::malloc(32);
assert!(!p.is_null());
libc::memset(p, 0xEE, 32);
freezero(p, 16);
}
}
}