Skip to content

Commit 4978bfb

Browse files
committed
ZJIT: fmt::Debug for VALUE in hex. Shorthand for rb_obj_info()
The default `{:?}` still always prints the pointer address and never dereferences it, but now in hex. The "alternate" flag lets you do `println!("{my_ruby_object:#?}")` and get a rich printout like `VALUE(0x000000010232fd00 T_CLASS/Object)`.
1 parent 5ffaaf0 commit 4978bfb

1 file changed

Lines changed: 19 additions & 1 deletion

File tree

zjit/src/cruby.rs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ pub struct rb_iseq_constant_body {
248248
/// that this is a handle. Sometimes the C code briefly uses VALUE as
249249
/// an unsigned integer type and don't necessarily store valid handles but
250250
/// thankfully those cases are rare and don't cross the FFI boundary.
251-
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
251+
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
252252
#[repr(transparent)] // same size and alignment as simply `usize`
253253
pub struct VALUE(pub usize);
254254

@@ -757,6 +757,17 @@ impl IseqParameters {
757757
}
758758
}
759759

760+
impl Debug for VALUE {
761+
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
762+
// Only use rb_obj_info() when {:#?} since it dereferences the pointer so carries some risk.
763+
if f.alternate() {
764+
write!(f, "VALUE({})", self.obj_info())
765+
} else {
766+
write!(f, "VALUE(0x{:x})", self.0)
767+
}
768+
}
769+
}
770+
760771
impl From<IseqPtr> for VALUE {
761772
/// For `.into()` convenience
762773
fn from(iseq: IseqPtr) -> Self {
@@ -1418,6 +1429,13 @@ pub mod test_utils {
14181429
fn value_from_fixnum_too_small_isize() {
14191430
assert_eq!(VALUE::fixnum_from_isize(RUBY_FIXNUM_MIN-1), VALUE(1));
14201431
}
1432+
1433+
#[test]
1434+
fn value_fmt_debug() {
1435+
assert_eq!("VALUE(0xcafe)", format!("{:?}", VALUE(0xcafe)));
1436+
let alternate = format!("{:#?}", eval("::Hash"));
1437+
assert!(alternate.contains("Hash"), "'Hash' not substring of '{alternate}'");
1438+
}
14211439
}
14221440
#[cfg(test)]
14231441
pub use test_utils::*;

0 commit comments

Comments
 (0)