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