Skip to content

Commit

Permalink
KeyBuilder: change int to direct str representation
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasdiener committed Sep 3, 2024
1 parent cee5027 commit 9f739d0
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 13 deletions.
11 changes: 1 addition & 10 deletions pytools/persistent_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,16 +283,7 @@ def update_for_type(key_hash: Hash, key: type) -> None:

@staticmethod
def update_for_int(key_hash: Hash, key: int) -> None:
sz = 8
while True:
try:
# Must match system byte order so that numpy and this
# generate the same string of bytes.
# https://github.com/inducer/pytools/issues/259
key_hash.update(key.to_bytes(sz, byteorder=sys.byteorder, signed=True))
return
except OverflowError:
sz *= 2
key_hash.update(str(key).encode("utf-8"))

@classmethod
def update_for_enum(cls, key_hash: Hash, key: Enum) -> None:
Expand Down
10 changes: 7 additions & 3 deletions pytools/test/test_persistent_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,9 +432,13 @@ def test_scalar_hashing() -> None:
assert keyb(np.int32(1)) == keyb(np.int32(1))
assert keyb(np.int32(2)) != keyb(np.int32(1))
assert keyb(np.int64(1)) == keyb(np.int64(1))
assert keyb(1) == keyb(np.int64(1))
assert keyb(1) != keyb(np.int64(1))
assert keyb(1) != keyb(np.int32(1))

assert keyb(1) == keyb("1")
assert keyb(1.0) != keyb("1.0") # '1.0' uses hex representation
assert keyb(1+1j) == keyb("(1+1j)")

assert keyb(np.longlong(1)) == keyb(np.longlong(1))

assert keyb(np.float16(1.1)) == keyb(np.float16(1.1))
Expand Down Expand Up @@ -566,7 +570,7 @@ class MyDC:
name: str
value: int

assert keyb(MyDC("hi", 1)) == "d1a1079f1c10aa4f"
assert keyb(MyDC("hi", 1)) == "72c25f5d0ac2bda7"

assert keyb(MyDC("hi", 1)) == keyb(MyDC("hi", 1))
assert keyb(MyDC("hi", 1)) != keyb(MyDC("hi", 2))
Expand All @@ -590,7 +594,7 @@ class MyAttrs:
name: str
value: int

assert (keyb(MyAttrs("hi", 1)) == "5b6c5da60eb2bd0f") # type: ignore[call-arg]
assert (keyb(MyAttrs("hi", 1)) == "6e8bfc4394f82985") # type: ignore[call-arg]

assert keyb(MyAttrs("hi", 1)) == keyb(MyAttrs("hi", 1)) # type: ignore[call-arg]
assert keyb(MyAttrs("hi", 1)) != keyb(MyAttrs("hi", 2)) # type: ignore[call-arg]
Expand Down

0 comments on commit 9f739d0

Please sign in to comment.