From 04c7d40f7a8687f7ad4fec60badd85f1aca513f8 Mon Sep 17 00:00:00 2001 From: Mitchell Hamilton Date: Sat, 20 Jan 2018 17:44:14 +1000 Subject: [PATCH] Change hash implementation --- packages/emotion-utils/src/hash.js | 91 +++++++++++------------------- 1 file changed, 34 insertions(+), 57 deletions(-) diff --git a/packages/emotion-utils/src/hash.js b/packages/emotion-utils/src/hash.js index 42e57d88c..2a88b77ee 100644 --- a/packages/emotion-utils/src/hash.js +++ b/packages/emotion-utils/src/hash.js @@ -1,74 +1,51 @@ // @flow -// murmurhash2 via https://gist.github.com/raycmorgan/588423 +/* eslint-disable */ +// murmurhash2 via https://github.com/garycourt/murmurhash-js/blob/master/murmurhash2_gc.js export function hashString(str: string) { - return hash(str, str.length).toString(36) + return murmurhash2_32_gc(str, str.length).toString(36) } -function hash(str: string, seed: number) { - let m = 0x5bd1e995 - let r = 24 - let h = seed ^ str.length - let length = str.length - let currentIndex = 0 - - while (length >= 4) { - let k = UInt32(str, currentIndex) - - k = Umul32(k, m) - k ^= k >>> r - k = Umul32(k, m) - - h = Umul32(h, m) - h ^= k - - currentIndex += 4 - length -= 4 +function murmurhash2_32_gc(str: string, seed: number) { + var l = str.length, + h = seed ^ l, + i = 0, + k + + while (l >= 4) { + k = + (str.charCodeAt(i) & 0xff) | + ((str.charCodeAt(++i) & 0xff) << 8) | + ((str.charCodeAt(++i) & 0xff) << 16) | + ((str.charCodeAt(++i) & 0xff) << 24) + + k = (k & 0xffff) * 0x5bd1e995 + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16) + k ^= k >>> 24 + k = (k & 0xffff) * 0x5bd1e995 + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16) + + h = + ((h & 0xffff) * 0x5bd1e995 + + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ + k + + l -= 4 + ++i } - switch (length) { + switch (l) { case 3: - h ^= UInt16(str, currentIndex) - h ^= str.charCodeAt(currentIndex + 2) << 16 - h = Umul32(h, m) - break - + h ^= (str.charCodeAt(i + 2) & 0xff) << 16 case 2: - h ^= UInt16(str, currentIndex) - h = Umul32(h, m) - break - + h ^= (str.charCodeAt(i + 1) & 0xff) << 8 case 1: - h ^= str.charCodeAt(currentIndex) - h = Umul32(h, m) - break + h ^= str.charCodeAt(i) & 0xff + h = + (h & 0xffff) * 0x5bd1e995 + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16) } h ^= h >>> 13 - h = Umul32(h, m) + h = (h & 0xffff) * 0x5bd1e995 + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16) h ^= h >>> 15 return h >>> 0 } - -function UInt32(str, pos) { - return ( - str.charCodeAt(pos++) + - (str.charCodeAt(pos++) << 8) + - (str.charCodeAt(pos++) << 16) + - (str.charCodeAt(pos) << 24) - ) -} - -function UInt16(str, pos) { - return str.charCodeAt(pos++) + (str.charCodeAt(pos++) << 8) -} - -function Umul32(n, m) { - n = n | 0 - m = m | 0 - let nlo = n & 0xffff - let nhi = n >>> 16 - let res = (nlo * m + (((nhi * m) & 0xffff) << 16)) | 0 - return res -}