views:

106

answers:

4

I need to generate something that can be used as a unique handle for a user defined type (struct or class) in the D programming language. Preferably this would be a compile time computable value. I want the handle to relate to the name of the type as well as change if the internal structure (data layout) of the type changes but remain the same for most other edits (including compiling the same type into a different app).

This is not a security thing so it doesn't need to be hard to bypass or anything

My current thought is to use a string with something like an MD5 hash of the type name and member types and names.

Any thoughts

A: 

The typeid expression will return an unique instance of a TypeInfo object. In theory, you should be able to use the address of the TypeInfo object as the type's unique identifier value.

CyberShadow
That has two problems, it doesn't work with DLLs and it's not a compile time value.
BCS
A: 

You know, you can just hardcode a revision into the type, like "const REV = 173; ", then update it every time you change the layout, then mix that with the type name to produce your identifier.

This is a bit of a hassle because it requires manual updates, but you could script it to be updated automatically on commit when svn diff recognizes a change in that class. And it's probably the easiest solution.

FeepingCreature
That requires the ability to edit the type. I can't count on that in my case. Also I would be requiring /my/ users to do that.
BCS
+1  A: 

After thinking about this for a bit, I think this would be a feasible approach (note: this is just pseudo code):

UniqueId(Type) = Type.stringof ~ MemberIds!(Type.tupleof)

UniqueId(Type) if( Type is builtin ) = Type.stringof

MemberIds(M, Ms...) = "," ~ UniqueId!(typeof(M))
                      ~ "@" ~ ToString!(M.offsetof)
                      ~ ":" ~ M.stringof
                      ~ MemberIds!(Ms)

That is, construct the unique ID from the type's name (you might need to chop off the module and package, not sure), and each member's type's ID, offset and name.

Depending on exactly what you want, you could remove the member name.

DK
That's more or less my first thought and it will work. (+1) OTOH I'm still hoping for some brilliant solution <g>.
BCS
+1  A: 

The fully qualified name of a type should be unique. This is the same as typeid(T).toString. This is not the same as T.stringof -- T.stringof will erase any template instantiations and will not give the fully qualified name.

The workaround is to use demangled(T.mangleof) at compiletime and typeid(T).toString at runtime.

Usefull! Just thinking about it, I think I might be able to use the mangle of. It wouldn't notice changes in the members but that can be had as well.
BCS