6

I want to generate a unique id for every type at compile time. Is this possible in Rust?

So far, I have the following code

//Pseudo code
struct ClassTypeId{
    id: &'static uint
}
impl ClassTypeId{
    fn get_type<T>(&mut self) -> &'static uint {
        let _id :&'static uint = self.id + 1;
        self.id = _id;
        _id
    }
}

let c = ClassTypeId{id:0};
c.get_type::<i32>();  // returns 1
c.get_type::<f32>();  // returns 2
c.get_type::<i32>();  // returns 1
c.get_type::<uint>(); // returns 3

I stole this idea from a C++ library, which looks like this

typedef std::size_t TypeId;

        template <typename TBase>
        class ClassTypeId
        {
        public:

            template <typename T>
            static TypeId GetTypeId()
            {
                static const TypeId id = m_nextTypeId++;
                return id;
            }

        private:

            static TypeId m_nextTypeId;
        };

        template <typename TBase>
        TypeId ClassTypeId<TBase>::m_nextTypeId = 0;
    }
nbro
  • 15,395
  • 32
  • 113
  • 196
Maik Klein
  • 15,548
  • 27
  • 101
  • 197

3 Answers3

15

std::any::TypeId does something like that:

use std::any::TypeId;

fn main() {
    let type_id = TypeId::of::<isize>();
    println!("{:?}", type_id);
}

outputs:

TypeId { t: 4150853580804116396 }
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Paige Ruten
  • 172,675
  • 36
  • 177
  • 197
8

This sounds like a job for the bitflags! macro:

#[macro_use] extern crate rustc_bitflags;

bitflags!(
    #[derive(Debug)]
    flags ComponentMask: u8 {
        const Render     = 0b00000001,
        const Position   = 0b00000010,
        const Physics    = 0b00000100
    }
);

// the set of components owned by an entity:
let owned_components:  = Render | Position;

// check whether an entity has a certain component:
if owned_components.contains(Physics) { ... }

http://doc.rust-lang.org/rustc_bitflags/macro.bitflags!.html

ArtemGr
  • 11,684
  • 3
  • 52
  • 85
A.B.
  • 15,364
  • 3
  • 61
  • 64
0

If you want to manage type ids manually, you can use my unique-type-id crate. It allows you to specify what ids a type has in a special file. It will generate them at compile time. Currently it can be used in this way:

use unique_type_id::UniqueTypeId;
#[derive(UniqueTypeId)]
struct Test1;
#[derive(UniqueTypeId)]
struct Test2;

assert_eq!(Test1::id().0, 1u64);
assert_eq!(Test2::id().0, 2u64);

It can both generate types using incremental number and use the id from a file.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
VP.
  • 15,509
  • 17
  • 91
  • 161