Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::cell::UnsafeCell;
- pub fn evil_foo<'bytes, T>(bytes: &'bytes mut [u8]) -> &'bytes mut [u8] {
- // Dear borrow checker, please go out of the way for a second
- // let bytes_alias: &'bytes UnsafeCell<[u8]> = std::mem::transmute(bytes);
- // Now, we're going to need a scope to contain some evil deeds
- {
- // This is a perfect copy of the original "bytes"
- // let bytes: &'bytes mut [u8] = &mut *bytes_alias.get();
- // The borrow checker can borrow it as long as it likes...
- deserialize2::<T>(bytes);
- // ...because we're just going to drop it anyhow.
- }
- // What we will return is... a _different_ clone of "bytes"
- // let bytes: &'bytes mut [u8] = &mut *bytes_alias.get();
- bytes
- }
- fn deserialize2<T>(bytes: &mut [u8]) -> &mut T {
- unsafe {
- &mut *(bytes as *mut [u8] as *mut T)
- }
- }
- #[repr(C)]
- struct AlignTo<T, U>(T, [U;0]);
- fn main() {
- let mut x = AlignTo::<_, u32>([0; 10], []);
- evil_foo::<u32>(&mut x.0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement