SHARE
TWEET

Untitled

a guest Oct 20th, 2019 92 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::cell::UnsafeCell;
  2.  
  3. pub fn evil_foo<'bytes, T>(bytes: &'bytes mut [u8]) -> &'bytes mut [u8] {
  4.         // Dear borrow checker, please go out of the way for a second
  5.         //  let bytes_alias: &'bytes UnsafeCell<[u8]> = std::mem::transmute(bytes);
  6.        
  7.         // Now, we're going to need a scope to contain some evil deeds
  8.         {
  9.             // This is a perfect copy of the original "bytes"
  10.             // let bytes: &'bytes mut [u8] = &mut *bytes_alias.get();
  11.            
  12.             // The borrow checker can borrow it as long as it likes...
  13.             deserialize2::<T>(bytes);
  14.             // ...because we're just going to drop it anyhow.
  15.         }
  16.        
  17.         // What we will return is... a _different_ clone of "bytes"
  18.         // let bytes: &'bytes mut [u8] = &mut *bytes_alias.get();
  19.         bytes
  20.    
  21. }
  22.  
  23. fn deserialize2<T>(bytes: &mut [u8]) -> &mut T {
  24.     unsafe {
  25.         &mut *(bytes as *mut [u8] as *mut T)
  26.     }
  27. }
  28.  
  29. #[repr(C)]
  30. struct AlignTo<T, U>(T, [U;0]);
  31.  
  32. fn main() {
  33.     let mut x = AlignTo::<_, u32>([0; 10], []);
  34.     evil_foo::<u32>(&mut x.0);
  35. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top