diff --git a/samtranslator/third_party/py27hash/hash.py b/samtranslator/third_party/py27hash/hash.py index acf90ed7f..0fb1f9e67 100644 --- a/samtranslator/third_party/py27hash/hash.py +++ b/samtranslator/third_party/py27hash/hash.py @@ -2,10 +2,12 @@ Compatibility methods to support Python 2.7 style hashing in Python 3.X+ This is designed for compatibility not performance. + """ import ctypes import math +from functools import lru_cache def hash27(value): # type: ignore[no-untyped-def] @@ -19,7 +21,7 @@ def hash27(value): # type: ignore[no-untyped-def] Python 2.7 hash """ - return Hash.hash(value) # type: ignore[no-untyped-call] + return Hash.hash(value) class Hash(object): @@ -28,6 +30,7 @@ class Hash(object): """ @staticmethod + @lru_cache(maxsize=2048) def hash(value): # type: ignore[no-untyped-def] """ Returns a Python 2.7 hash for a value. @@ -39,14 +42,14 @@ def hash(value): # type: ignore[no-untyped-def] Python 2.7 hash """ + if isinstance(value, ("".__class__, bytes)) or type(value).__name__ == "buffer": + return Hash.shash(value) # type: ignore[no-untyped-call] if isinstance(value, tuple): return Hash.thash(value) # type: ignore[no-untyped-call] if isinstance(value, float): return Hash.fhash(value) # type: ignore[no-untyped-call] if isinstance(value, int): return hash(value) - if isinstance(value, ("".__class__, bytes)) or type(value).__name__ == "buffer": - return Hash.shash(value) # type: ignore[no-untyped-call] raise TypeError("unhashable type: '%s'" % (type(value).__name__)) @@ -73,7 +76,7 @@ def thash(value): # type: ignore[no-untyped-def] for y in value: length -= 1 - y = Hash.hash(y) # type: ignore[no-untyped-call] + y = Hash.hash(y) x = (x ^ y) * mult mult += 82520 + length + length diff --git a/samtranslator/utils/py27hash_fix.py b/samtranslator/utils/py27hash_fix.py index c0f567075..f0f1f44e2 100644 --- a/samtranslator/utils/py27hash_fix.py +++ b/samtranslator/utils/py27hash_fix.py @@ -141,7 +141,7 @@ def __deepcopy__(self, memo): # type: ignore[no-untyped-def] def _get_py27_hash(self): # type: ignore[no-untyped-def] h = getattr(self, "_py27_hash", None) if h is None: - self._py27_hash = h = ctypes.c_size_t(Hash.hash(self)).value # type: ignore[no-untyped-call] + self._py27_hash = h = ctypes.c_size_t(Hash.hash(self)).value return h @@ -198,7 +198,7 @@ def _get_key_idx(self, k): # type: ignore[no-untyped-def] if isinstance(k, Py27UniStr): h = k._get_py27_hash() # type: ignore[no-untyped-call] else: - h = ctypes.c_size_t(Hash.hash(k)).value # type: ignore[no-untyped-call] + h = ctypes.c_size_t(Hash.hash(k)).value i = h & self.mask