Skip to content

Commit 6918595

Browse files
authored
opaque-debug: support generics (#1053)
1 parent 82f5b1b commit 6918595

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

opaque-debug/src/lib.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,17 @@
88
#[doc(hidden)]
99
pub extern crate core as __core;
1010

11+
#[macro_export]
12+
#[doc(hidden)]
13+
macro_rules! format_params {
14+
($single:ident) => {
15+
"{}"
16+
};
17+
($first:ident, $($rest:ident),+) => {
18+
concat!("{}", ", ", $crate::format_params!($($rest),+))
19+
};
20+
}
21+
1122
/// Macro for defining opaque `Debug` implementation.
1223
///
1324
/// It will use the following format: "StructName { ... }". While it's
@@ -16,6 +27,20 @@ pub extern crate core as __core;
1627
/// uncareful logging.
1728
#[macro_export]
1829
macro_rules! implement {
30+
($struct:ident <$($params:ident),+>) => {
31+
impl <$($params),+> $crate::__core::fmt::Debug for $struct <$($params),+> {
32+
fn fmt(
33+
&self,
34+
f: &mut $crate::__core::fmt::Formatter,
35+
) -> Result<(), $crate::__core::fmt::Error> {
36+
write!(
37+
f,
38+
concat!(stringify!($struct), "<", $crate::format_params!($($params),+), "> {{ ... }}"),
39+
$($crate::__core::any::type_name::<$params>()),+
40+
)
41+
}
42+
}
43+
};
1944
($struct:ty) => {
2045
impl $crate::__core::fmt::Debug for $struct {
2146
fn fmt(

opaque-debug/tests/mod.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,50 @@ struct Foo {
66

77
opaque_debug::implement!(Foo);
88

9+
struct FooGeneric<T> {
10+
secret: u64,
11+
generic: T,
12+
}
13+
14+
opaque_debug::implement!(FooGeneric<T>);
15+
16+
struct FooManyGenerics<T, U, V> {
17+
secret: u64,
18+
generic1: T,
19+
generic2: U,
20+
generic3: V,
21+
}
22+
23+
opaque_debug::implement!(FooManyGenerics<T, U, V>);
24+
925
#[test]
1026
fn debug_formatting() {
1127
let s = format!("{:?}", Foo { secret: 42 });
1228
assert_eq!(s, "Foo { ... }");
1329
}
30+
31+
#[test]
32+
fn debug_formatting_generic() {
33+
let s = format!(
34+
"{:?}",
35+
FooGeneric::<()> {
36+
secret: 42,
37+
generic: ()
38+
}
39+
);
40+
assert_eq!(s, "FooGeneric<()> { ... }");
41+
}
42+
43+
#[test]
44+
fn debug_formatting_many_generics() {
45+
let s = format!(
46+
"{:?}",
47+
FooManyGenerics::<(), u8, &str> {
48+
secret: 42,
49+
generic1: (),
50+
generic2: 0u8,
51+
generic3: "hello",
52+
}
53+
);
54+
assert_eq!(s, "FooManyGenerics<(), u8, &str> { ... }");
55+
}

0 commit comments

Comments
 (0)