Skip to content

Commit 5d98edc

Browse files
authored
feat: show typenames in Extensions debug output (#773)
1 parent 613d3d4 commit 5d98edc

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

src/extensions.rs

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::any::{Any, TypeId};
1+
use std::any::{type_name, Any, TypeId};
22
use std::collections::HashMap;
33
use std::fmt;
44
use std::hash::{BuildHasherDefault, Hasher};
@@ -267,7 +267,21 @@ impl Extensions {
267267

268268
impl fmt::Debug for Extensions {
269269
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270-
f.debug_struct("Extensions").finish()
270+
struct TypeName(&'static str);
271+
impl fmt::Debug for TypeName {
272+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273+
f.write_str(self.0)
274+
}
275+
}
276+
277+
let mut set = f.debug_set();
278+
if let Some(map) = &self.map {
279+
set.entries(
280+
map.values()
281+
.map(|any_clone| TypeName(any_clone.as_ref().type_name())),
282+
);
283+
}
284+
set.finish()
271285
}
272286
}
273287

@@ -276,6 +290,7 @@ trait AnyClone: Any {
276290
fn as_any(&self) -> &dyn Any;
277291
fn as_any_mut(&mut self) -> &mut dyn Any;
278292
fn into_any(self: Box<Self>) -> Box<dyn Any>;
293+
fn type_name(&self) -> &'static str;
279294
}
280295

281296
impl<T: Clone + Send + Sync + 'static> AnyClone for T {
@@ -294,6 +309,10 @@ impl<T: Clone + Send + Sync + 'static> AnyClone for T {
294309
fn into_any(self: Box<Self>) -> Box<dyn Any> {
295310
self
296311
}
312+
313+
fn type_name(&self) -> &'static str {
314+
type_name::<T>()
315+
}
297316
}
298317

299318
impl Clone for Box<dyn AnyClone + Send + Sync> {
@@ -308,13 +327,23 @@ fn test_extensions() {
308327
struct MyType(i32);
309328

310329
let mut extensions = Extensions::new();
330+
assert_eq!(format!("{extensions:?}"), "{}");
311331

312332
extensions.insert(5i32);
313333
extensions.insert(MyType(10));
314334

315335
assert_eq!(extensions.get(), Some(&5i32));
316336
assert_eq!(extensions.get_mut(), Some(&mut 5i32));
317337

338+
let dbg = format!("{extensions:?}");
339+
// map order is NOT deterministic
340+
assert!(
341+
(dbg == "{http::extensions::test_extensions::MyType, i32}")
342+
|| (dbg == "{i32, http::extensions::test_extensions::MyType}"),
343+
"{}",
344+
dbg
345+
);
346+
318347
let ext2 = extensions.clone();
319348

320349
assert_eq!(extensions.remove::<i32>(), Some(5i32));

0 commit comments

Comments
 (0)