dumping with macro

This commit is contained in:
Christoph J. Scherr 2023-09-20 11:30:50 +02:00
parent fcce2500f0
commit f7e0b277ce
1 changed files with 27 additions and 18 deletions

View File

@ -1,6 +1,4 @@
use std::any::{TypeId, type_name};
use std::mem::*;
use std::fmt::Debug;
//* # See what's behind the primitive datatypes of Rust
//*
//* This Crate shows off, how primitive Types of rust are stored in memory.
@ -9,23 +7,34 @@ fn main() {
let mut items = Vec::new();
items.push(true);
items.push(false);
dump_type::<bool>(items);
investigate!(bool, items);
let mut items = Vec::new();
items.push(String::from("foo"));
items.push(String::from("bar"));
items.push(String::from("文学"));
investigate!(String, items);
}
fn dump_type<T: Debug + 'static>(items: Vec<T>) {
println!("Type:\t{}", type_name::<T>());
println!("\tID:\t{:?}", TypeId::of::<T>());
println!("\tItems:");
unsafe {
for (index, item) in items.iter().enumerate() {
let pointer = item as *const T;
let raw_pointer = pointer as *const u8;
println!("\t{index:02x}\titem:\t{item:?}\n\
\t\tpointer: {:X?}\n\
\t\tmemory: {:X?}",
pointer,
*raw_pointer,
);
#[macro_export]
macro_rules! investigate {
($t:ty, $v:tt) => {
println!("Type:\t{}", type_name::<$t>());
println!("\tID:\t{:?}", TypeId::of::<$t>());
println!("\tItems:");
unsafe {
for (index, item) in $v.iter().enumerate() {
let pointer = item as *const $t;
let raw_pointer: [u8; std::mem::size_of::<$t>()] = std::mem::transmute(item.clone());
println!("\t{index:02x}\titem:\t{item:?}\n\
\t\tpointer: {:X?}\n\
\t\talign: {:#X} B\n\
\t\tmemory: {:X?}\n",
pointer,
std::mem::align_of::<$t>(),
raw_pointer,
);
}
}
}
};
}