Created
May 8, 2026 14:53
-
-
Save alexcrichton/ff1fe2648362023238f36c3b5834fd2c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::ptr::NonNull; | |
| #[derive(Default)] | |
| struct Heap { | |
| data: Data, | |
| } | |
| #[derive(Default)] | |
| struct Data { | |
| a: u32, | |
| } | |
| impl Heap { | |
| #[cfg(not(mutable))] | |
| fn data_ptr(&self) -> NonNull<u8> { | |
| let a: *const _ = &self.data; | |
| NonNull::new(a.cast_mut()).unwrap().cast() | |
| } | |
| #[cfg(mutable)] | |
| fn data_ptr(&mut self) -> NonNull<u8> { | |
| NonNull::from(&mut self.data).cast() | |
| } | |
| fn mutate(&mut self) { | |
| self.data.a = 4; | |
| } | |
| } | |
| fn main() { | |
| let mut heap = Box::new(Heap::default()); | |
| let ptr = heap.data_ptr(); | |
| unsafe { | |
| ptr.cast::<u32>().write(4); | |
| heap.mutate(); | |
| ptr.cast::<u32>().write(4); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment