Created
May 25, 2016 17:18
-
-
Save fero23/28bf4bc3ac428bc8ec320f4a60975f23 to your computer and use it in GitHub Desktop.
Unsafe copy using a byte buffer with Rust
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
#[derive(PartialEq, Eq)] | |
struct Person { | |
id: u32, | |
name: String, | |
last_name: String | |
} | |
fn main() { | |
let p1 = Person { | |
id: 1, | |
name: "Fernando".to_string(), | |
last_name: "Ulloa".to_string() | |
}; | |
let byte_count = std::mem::size_of_val(&p1); | |
let mut bytes = Vec::with_capacity(byte_count); | |
unsafe { | |
let cp = &p1 as *const _ as *const u8; | |
for i in 0..byte_count { | |
bytes.push(*((cp as usize + i) as *const u8)); | |
} | |
} | |
println!("Bytes: {:?}", bytes); | |
let p2 = unsafe { | |
let mut p = std::mem::uninitialized(); | |
let cp = &*bytes as *const _ as *const u8; | |
for i in 0..byte_count { | |
std::ptr::write((&mut p as *mut _ as usize + i) as *mut u8, | |
*((cp as usize + i) as *const u8)); | |
} | |
p | |
}; | |
println!("p1 == p2: {}", p1 == p2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment