title: “Testing NonNull with Miri” meta_description: “Comprehensive testing strategies for NonNull usage including Miri validation.” keywords: [“miri nonnull”, “nonnull testing”, “rust unsafe testing”]
🧪 Reinventing from Scratch: NonNull<T>
Chapter 10 — “Tests, Miri, and Safety Checklist”
“Test with Miri, or test in production.”
✅ 10.1. Basic Tests
#[test]
fn test_nonnull_construction() {
let x = 42;
let ptr = NonNull::new(&x as *const i32 as *mut i32);
assert!(ptr.is_some());
let null = NonNull::<i32>::new(std::ptr::null_mut());
assert!(null.is_none());
}
#[test]
fn test_niche_optimization() {
use std::mem::size_of;
assert_eq!(
size_of::<Option<NonNull<u8>>>(),
size_of::<*mut u8>()
);
}
🔬 10.2. Miri Validation
cargo +nightly miri test
Miri will catch:
- Use-after-free
- Invalid pointer arithmetic
- Alignment violations
- Provenance issues
🧠 10.3. Safety Checklist
When using NonNull:
- Pointer is actually non-null
- Memory is allocated and valid
- Proper alignment for type T
- Have permission to access
- Lifetime doesn’t outlive allocation
Next: Chapter 11 — Appendix: Reference Implementations 📚