Skip to content

Instantly share code, notes, and snippets.

@taskie
Created January 24, 2017 13:16
Show Gist options
  • Save taskie/734569fd772872f84a6e07e69b054e29 to your computer and use it in GitHub Desktop.
Save taskie/734569fd772872f84a6e07e69b054e29 to your computer and use it in GitHub Desktop.
Rust でメモリ上の生のバイト列を見るやつ
fn get_raw_bytes<T>(p: *const T) -> Vec<u8> {
// https://www.reddit.com/r/rust/comments/2ngnmk/viewing_any_object_as_a_raw_memory_array/
let size = std::mem::size_of::<T>();
let mut buf = Vec::with_capacity(size);
let view = p as *const _ as *const u8;
for i in 0..size {
buf.push(unsafe {*view.offset(i as isize)});
}
buf
}
fn print_bytes(bytes: Vec<u8>) {
for (i, x) in bytes.iter().enumerate() {
if i % 16 == 0 {
if i != 0 { println!(""); }
print!("{:04x}| ", i);
}
print!("{:02x} ", x);
}
println!("");
}
fn print_raw_bytes<T>(p: *const T) {
print_bytes(get_raw_bytes(p));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment