StringHash

Parameters
sstring
comment

Returns a string hash for the given string. The string is normalized before hashing.

The hash is supposed to be case-insensitive of the input string: this works for ASCII and (Reforged) some small subset of Unicode (Latin Supplement, Cyrillic...). Also the backslash is the same as forward slash: / and \. A probable explanation for this is the usage of file paths, since the game runs on Windows and Mac OS/OSX. StringHash is also used for variable lookup: string name -> integer index.

StringHash("\\") == StringHash("/") StringHash("AB") == StringHash("ab")

note

Code for the algorithm "SStrHash2" via "1997 Dr Dobbs article".

note

Breaking: The hashing of multi-byte characters (Unicode) was changed in v1.30.0/1.31.1. It's unknown if hashes of these characters are different in old versions between Windows/Mac OS or depends on OS-default character page settings (non-Unicode programs on Windows).

note

Reforged 2.0.4: an incomplete multi-byte UTF-8 slice that begins with the character's lead byte hashes to 1843378377. This was verified with 2-, 3- and 4-byte characters:

StringHash(SubString("д",  0, 1)) == 1843378377  -- 2-byte char, 1 of 2
StringHash(SubString("中", 0, 1)) == 1843378377  -- 3-byte char, 1 of 3
StringHash(SubString("中", 0, 2)) == 1843378377  -- 3-byte char, 2 of 3
StringHash(SubString("😀", 0, 3)) == 1843378377  -- 4-byte char, 3 of 4

These invalid sequences are normalized to a single replacement form before hashing. The exact replacement form was not verified. A slice that starts with a UTF-8 continuation byte does not use this marker and retains a distinct per-byte hash.

To iterate over UTF-8 characters, hash a one-byte slice. If it returns 1843378377, widen the slice one byte at a time, up to four bytes, until the hash differs. The resulting slice contains the complete character.

note

Reforged 2.0.4: fixed-size byte chunks can produce hash collisions when they end partway through multi-byte characters, because every such lead-byte slice uses the same hash.

pure
This function is pure. For the same values passed to it, it will always return the same value.
patch

1.24a

Source
common.j (suggest an edit or discuss on Github)
return type
integer
Source code
native StringHash takes string s returns integer