use std::any::{TypeId, type_name};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::hash::{Hash, Hasher};
#[derive(Clone, Copy)]
pub struct TypeName {
id: TypeId,
name: &'static str,
}
impl TypeName {
pub fn of<T: ?Sized + 'static>() -> TypeName {
TypeName { id: TypeId::of::<T>(), name: type_name::<T>() }
}
pub fn colliding(names: impl IntoIterator<Item = TypeName>) -> HashSet<TypeName> {
let mut by_text: HashMap<String, Vec<TypeName>> = HashMap::new();
for name in names {
let alike = by_text.entry(name.to_string()).or_default();
if !alike.contains(&name) {
alike.push(name);
}
}
by_text.into_values().filter(|alike| alike.len() > 1).flatten().collect()
}
pub(crate) fn from_parts(id: TypeId, name: &'static str) -> TypeName {
TypeName { id, name }
}
pub(crate) fn id(&self) -> TypeId {
self.id
}
pub(crate) fn full(&self) -> &'static str {
self.name
}
pub(crate) fn written(&self, full: &HashSet<TypeName>) -> String {
if full.contains(self) { self.name.to_owned() } else { short_type_name(self.name) }
}
}
impl PartialEq for TypeName {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for TypeName {}
impl Hash for TypeName {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl fmt::Display for TypeName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() { f.pad(self.name) } else { f.pad(&short_type_name(self.name)) }
}
}
impl fmt::Debug for TypeName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
pub(crate) fn short_type_name(full: &'static str) -> String {
let mut out = String::with_capacity(full.len());
let mut rest = full;
while let Some(c) = rest.chars().next() {
if is_path_char(c) {
let end = rest.find(|c: char| !is_path_char(c)).unwrap_or(rest.len());
push_last_segment(&mut out, &rest[..end]);
rest = &rest[end..];
} else {
out.push(c);
rest = &rest[c.len_utf8()..];
}
}
out
}
fn is_path_char(c: char) -> bool {
c.is_alphanumeric() || matches!(c, '_' | ':' | '{' | '}')
}
fn push_last_segment(out: &mut String, path: &str) {
let path = match path.strip_prefix("::") {
Some(tail) => {
out.push_str("::");
tail
}
None => path,
};
let mut segments = path.rsplit("::");
let last = segments.next().unwrap_or("");
if last.starts_with('{') {
if let Some(enclosing) = segments.next() {
out.push_str(enclosing);
out.push_str("::");
}
}
out.push_str(last);
}