Trait rkyv_typename::TypeName[][src]

pub trait TypeName {
    fn build_type_name<F: FnMut(&str)>(f: F);
}
Expand description

Builds a name for a type.

An implementation can be derived automatically with #[derive(TypeName)]. See TypeName for more details.

Names cannot be guaranteed to be unique and although they are usually suitable to use as keys, precautions should be taken to ensure that if name collisions happen that they are detected and fixable.

Examples

Most of the time, #[derive(TypeName)] will suit your needs. However, if you need more control, you can always implement it manually:

use rkyv_typename::TypeName;

struct Example;

impl TypeName for Example {
    fn build_type_name<F: FnMut(&str)>(mut f: F) {
        f("CoolStruct");
    }
}

struct GenericExample<T, U, V>(T, U, V);

impl<
    T: TypeName,
    U: TypeName,
    V: TypeName
> TypeName for GenericExample<T, U, V> {
    fn build_type_name<F: FnMut(&str)>(mut f: F) {
        f("CoolGeneric<");
        T::build_type_name(&mut f);
        f(", ");
        U::build_type_name(&mut f);
        f(", ");
        V::build_type_name(&mut f);
        f(">");
    }
}

fn type_name<T: TypeName>() -> String {
    let mut result = String::new();
    T::build_type_name(|piece| result += piece);
    result
}

assert_eq!(type_name::<Example>(), "CoolStruct");
assert_eq!(
    type_name::<GenericExample<i32, Option<String>, Example>>(),
    "CoolGeneric<i32, core::option::Option<alloc::string::String>, CoolStruct>"
);

Required methods

Submits the pieces of the type name to the given function.

Implementations on Foreign Types

Implementors