Array toHash()
David Held via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Nov 29 20:30:37 PST 2014
On 11/29/2014 3:59 PM, Ali Çehreli wrote:
> [...]
> typeid() is a runtime function. I think it will be costly every time
> toHash is called. The function pointer can be initialized once.
>
> // I've "deduced" the type from an error message. ;)
> static const ulong delegate(const(void*)) const pure nothrow
> @trusted func;
>
> // This will be executed once per thread:
> static this() {
> func = assumePure(&(typeid(Foo.init.importantStuff).getHash));
> }
>
> override
> size_t toHash() @trusted pure const nothrow
> {
> return func(&importantStuff);
> }
>
> Now there is no TypeInfo lookup after thread initialization time.
Nice! This is getting very fancy, but also a bit unfortunate. It would
be appropriate if the type of importantStuff were arbitrary, but it's
not. It's int[]. In fact, the fact that I can get a compiler-generated
hash function for any type (I presume) surprises me. Not entirely,
since the compiler can just treat types as binary blobs, and define a
hash function that operates as if it were byte[].
Although it is nice that we can get at stuff through reflection, this is
not quite the same as the ostensibly static [and inlinable] call to
int[].toHash() which logically occurs when int[] is used directly as a key.
Also, would it be possible to avoid spelling the delegate type by making
func a function static and using an auto return on a named method?
Finally, I find it a little surprising that there's no standard module
which implements a quality hash function builder (using something like
MurmurHash or CityHash). This seems like it would be a fairly common
requirement for a lot of users. Are there any non-standard libraries
which do this?
Dave
More information about the Digitalmars-d-learn
mailing list