pretty_type_name/
lib.rs

1//! ```rust
2//! use pretty_type_name::pretty_type_name;
3//!
4//! mod foo {
5//!     pub mod bar {
6//!         pub struct X<T>(T);
7//!     }
8//!
9//!     pub struct Y;
10//! }
11//!
12//! println!("{}", pretty_type_name::<foo::bar::X<foo::Y>>());
13//! # assert_eq!(pretty_type_name::<foo::bar::X<foo::Y>>(), "X<Y>".to_string());
14//! // prints `X<Y>`
15//! ```
16
17/// Returns a shorter version of [`std::any::type_name`]
18pub fn pretty_type_name<T: ?Sized>() -> String {
19    let type_name = std::any::type_name::<T>();
20    pretty_type_name_str(type_name)
21}
22
23/// same as [pretty_type_name], but works strings
24pub fn pretty_type_name_str(type_name: &str) -> String {
25    if let Some(before) = type_name.strip_suffix("::{{closure}}") {
26        return format!("{}::{{{{closure}}}}", pretty_type_name_str(before));
27    }
28
29    // code taken from [bevy](https://github.com/bevyengine/bevy/blob/89a41bc62843be5f92b4b978f6d801af4de14a2d/crates/bevy_reflect/src/type_registry.rs#L156)
30    let mut short_name = String::new();
31
32    // A typename may be a composition of several other type names (e.g. generic parameters)
33    // separated by the characters that we try to find below.
34    // Then, each individual typename is shortened to its last path component.
35    //
36    // Note: Instead of `find`, `split_inclusive` would be nice but it's still unstable...
37    let mut remainder = type_name;
38    while let Some(index) = remainder.find(&['<', '>', '(', ')', '[', ']', ',', ';'][..]) {
39        let (path, new_remainder) = remainder.split_at(index);
40        // Push the shortened path in front of the found character
41        short_name.push_str(path.rsplit(':').next().unwrap());
42        // Push the character that was found
43        let character = new_remainder.chars().next().unwrap();
44        short_name.push(character);
45        // Advance the remainder
46        if character == ',' || character == ';' {
47            // A comma or semicolon is always followed by a space
48            short_name.push(' ');
49            remainder = &new_remainder[2..];
50        } else {
51            remainder = &new_remainder[1..];
52        }
53    }
54
55    // The remainder will only be non-empty if there were no matches at all
56    if !remainder.is_empty() {
57        // Then, the full typename is a path that has to be shortened
58        short_name.push_str(remainder.rsplit(':').next().unwrap());
59    }
60
61    short_name
62}
63
64#[cfg(test)]
65mod tests;