Search code examples
hashd

D language unsigned hash of string


I am a complete beginner with the D language.

How to get, as an uint unsigned 32 bits integer in the D language, some hash of a string...

I need a quick and dirty hash code (I don't care much about the "randomness" or the "lack of collision", I care slightly more about performance).

 import std.digest.crc;
 uint string_hash(string s) {
    return  crc320f(s);
 }

is not good...

(using gdc-5 on Linux/x86-64 with phobos-2)


Solution

  • A really quick thing could just be this:

    uint string_hash(string s) { 
        import std.digest.crc; 
        auto r = crc32Of(s); 
        return *(cast(uint*) r.ptr); 
    } 
    

    Since crc32Of returns a ubyte[4] instead of the uint you want, a conversion is necessary, but since ubyte[4] and uint are the same thing to the machine, we can just do a reinterpret cast with the pointer trick seen there to convert types for free at runtime.