| name | unsafe-review |
| description | Audit unsafe blocks — verify necessity, add SAFETY comments, confirm test coverage, encapsulate in safe public API |
/unsafe-review — Audit unsafe blocks
Find all unsafe blocks
grep -rn "unsafe" crates/ --include="*.rs" | grep -v "// SAFETY:"
grep -rn -A 5 -B 2 "unsafe {" crates/ --include="*.rs"
For each unsafe block, answer these questions
1. Is it really necessary?
Try safe alternatives first:
use bytemuck::{Pod, Zeroable};
#[repr(C)]
#[derive(Pod, Zeroable, Clone, Copy)]
struct Page { ... }
let page: &Page = bytemuck::from_bytes(&bytes);
use rkyv::{Archive, Deserialize};
let archived = unsafe { rkyv::access_unchecked::<Page>(&bytes) };
2. What invariant guarantees it is safe?
The SAFETY comment must be specific, not generic:
let page = unsafe { &*(ptr as *const Page) };
3. Is there a test that verifies the contract?
#[test]
fn test_safety_invariant_mmap_pointer() {
let storage = MmapStorage::create_temp();
let last_page = storage.total_pages() - 1;
let result = storage.read_page(last_page);
assert!(result.is_ok());
let result = storage.read_page(storage.total_pages());
assert!(matches!(result, Err(DbError::PageNotFound { .. })));
}
4. Is it correctly encapsulated?
pub fn get_page_ptr(id: u64) -> *const Page { ... }
pub fn read_page(&self, id: u64) -> Result<&Page, DbError> {
if id >= self.total_pages {
return Err(DbError::PageNotFound { page_id: id });
}
let ptr = self.mmap.as_ptr().add(id as usize * PAGE_SIZE);
Ok(unsafe { &*(ptr as *const Page) })
}
Checklist per unsafe block
[ ] Did I try bytemuck/rkyv/restructuring first?
[ ] Does the SAFETY comment explain the specific invariant?
[ ] Does the comment mention why each condition holds?
[ ] Is there a test that verifies the contract at edge cases?
[ ] Does the public function have a safe signature even if it uses unsafe internally?
[ ] Did I run miri on this code?
cargo +nightly miri test unsafe_test_name