Skip to content

Commit

Permalink
opaque-debug: support generics (#1053)
Browse files Browse the repository at this point in the history
  • Loading branch information
sinui0 authored Mar 1, 2024
1 parent 82f5b1b commit 6918595
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
25 changes: 25 additions & 0 deletions opaque-debug/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@
#[doc(hidden)]
pub extern crate core as __core;

#[macro_export]
#[doc(hidden)]
macro_rules! format_params {
($single:ident) => {
"{}"
};
($first:ident, $($rest:ident),+) => {
concat!("{}", ", ", $crate::format_params!($($rest),+))
};
}

/// Macro for defining opaque `Debug` implementation.
///
/// It will use the following format: "StructName { ... }". While it's
Expand All @@ -16,6 +27,20 @@ pub extern crate core as __core;
/// uncareful logging.
#[macro_export]
macro_rules! implement {
($struct:ident <$($params:ident),+>) => {
impl <$($params),+> $crate::__core::fmt::Debug for $struct <$($params),+> {
fn fmt(
&self,
f: &mut $crate::__core::fmt::Formatter,
) -> Result<(), $crate::__core::fmt::Error> {
write!(
f,
concat!(stringify!($struct), "<", $crate::format_params!($($params),+), "> {{ ... }}"),
$($crate::__core::any::type_name::<$params>()),+
)
}
}
};
($struct:ty) => {
impl $crate::__core::fmt::Debug for $struct {
fn fmt(
Expand Down
42 changes: 42 additions & 0 deletions opaque-debug/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,50 @@ struct Foo {

opaque_debug::implement!(Foo);

struct FooGeneric<T> {
secret: u64,
generic: T,
}

opaque_debug::implement!(FooGeneric<T>);

struct FooManyGenerics<T, U, V> {
secret: u64,
generic1: T,
generic2: U,
generic3: V,
}

opaque_debug::implement!(FooManyGenerics<T, U, V>);

#[test]
fn debug_formatting() {
let s = format!("{:?}", Foo { secret: 42 });
assert_eq!(s, "Foo { ... }");
}

#[test]
fn debug_formatting_generic() {
let s = format!(
"{:?}",
FooGeneric::<()> {
secret: 42,
generic: ()
}
);
assert_eq!(s, "FooGeneric<()> { ... }");
}

#[test]
fn debug_formatting_many_generics() {
let s = format!(
"{:?}",
FooManyGenerics::<(), u8, &str> {
secret: 42,
generic1: (),
generic2: 0u8,
generic3: "hello",
}
);
assert_eq!(s, "FooManyGenerics<(), u8, &str> { ... }");
}

0 comments on commit 6918595

Please sign in to comment.