WyHash

#include <Windows.h>
#include <intrin.h>

PVOID CopyMemoryEx(_Inout_ PVOID Destination, _In_ CONST PVOID Source, _In_ SIZE_T Length)
{
    PBYTE D = (PBYTE)Destination;
    PBYTE S = (PBYTE)Source;

    while (Length--)
        *D++ = *S++;

    return Destination;
}

SIZE_T StringLengthW(_In_ LPCWSTR String)
{
	LPCWSTR String2;

	for (String2 = String; *String2; ++String2);

	return (String2 - String);
}

UINT64 Read64BitsAlignedSafe(PVOID Pointer)
{
    UINT64 Value = 0;

    CopyMemoryEx(&Value, Pointer, 8);

    return Value;
}

UINT64 WyHashMix(UINT64 Mix0, UINT64 Mix1)
{
    INT64 High = 0;
    INT64 Low = 0;

    Low = _mul128(Mix0, Mix1, &High);

    return (UINT64)Low ^ High;
}

UINT64 HashStringWyHashW(PVOID Data, UINT64 Length, UINT64 Seed)
{
    PBYTE Pointer = (PBYTE)Data;
    UINT State0 = 0;
    UINT State1 = 0;
    Seed ^= 0xa0761d6478bd642full;

    for (;Length >= 16; Pointer += 16, Length -= 16)
        Seed = WyHashMix(Read64BitsAlignedSafe(Pointer) ^ 0xe7037ed1a0b428dbull, Read64BitsAlignedSafe(Pointer + 8) ^ Seed);

    if (Length >= 8)
    {
        State0 = Read64BitsAlignedSafe(Pointer);
        Pointer += 8;
        Length -= 8;
    }
    else if(Length)
    {
        for (SIZE_T i = 0; i < Length; i++)
            State0 |= (UINT64)Pointer[i] << (i * 8);
        
        Length = 0;
    }

    if (Length)
    {
        for(SIZE_T i = 0; i < Length; i++)
            State1 |= (UINT64)Pointer[i] << (i * 8);
    }

    return WyHashMix(0x8ebc6af09c88c6e3ull ^ Seed ^ (UINT64)Length, WyHashMix(State0 ^ 0x589965cc75374cc3ull, State1 ^ Seed));
}

INT main(VOID)
{
    WCHAR StringHashExample[] = L"Hash This String";
    UINT64 Hash = 0;

    Hash = HashStringWyHashW(StringHashExample, (StringLengthW(StringHashExample) * sizeof(WCHAR)), 1);

    return ERROR_SUCCESS;
}

Last updated