Created
October 25, 2018 16:46
-
-
Save pacmancoder/0bcbc2a7f927c87a5bfd58dd878cb15a to your computer and use it in GitHub Desktop.
Exploring unsafe in rust
This file contains 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
extern crate rayon; | |
use rayon::prelude::*; | |
use std::marker::PhantomData; | |
use std::mem; | |
struct Storage<'a, T : 'a> | |
{ | |
ptr: *mut T, | |
phantom: PhantomData<&'a T>, | |
} | |
impl<'a, T> Storage<'a, T> | |
{ | |
fn from(ptr: &mut T) -> Storage<'a, T> | |
{ | |
Storage { | |
ptr: unsafe {mem::transmute(ptr)}, | |
phantom: PhantomData, | |
} | |
} | |
fn clone(&self) -> &'a mut T | |
{ | |
return unsafe { mem::transmute(self.ptr) }; | |
} | |
} | |
unsafe impl<'a, T> Send for Storage<'a, T> {} | |
unsafe impl<'a, T> Sync for Storage<'a, T> {} | |
fn main() { | |
let mut v : Vec<u8> = vec![1, 2, 3, 4, 5, 6]; | |
let storage = Storage::from(&mut v); | |
(0..6u8).into_par_iter().for_each(move |x| | |
{ | |
let k = storage.clone(); | |
k[x as usize] = 42 - x; | |
}); | |
// [42, 41, 40, 39, 38, 37] | |
println!("{:?}", v) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment