From f7e0b277ce610fd91649b34628e148d641d4b183 Mon Sep 17 00:00:00 2001 From: "Christoph J. Scherr" Date: Wed, 20 Sep 2023 11:30:50 +0200 Subject: [PATCH] dumping with macro --- members/what-is/src/main.rs | 45 ++++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/members/what-is/src/main.rs b/members/what-is/src/main.rs index ea707c9..dcafa2b 100644 --- a/members/what-is/src/main.rs +++ b/members/what-is/src/main.rs @@ -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::(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(items: Vec) { - println!("Type:\t{}", type_name::()); - println!("\tID:\t{:?}", TypeId::of::()); - 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, + ); + } } - } + }; }