|
import torch |
|
|
|
|
|
XXPRIME_1 = -(11400714785074694791 ^ 0xffffffffffffffff) - 1 |
|
XXPRIME_2 = -(14029467366897019727 ^ 0xffffffffffffffff) - 1 |
|
XXPRIME_5 = 2870177450012600261 |
|
|
|
XXPRIME_5_3527539 = XXPRIME_5 ^ 3527539 |
|
|
|
def tensor_python_tuple_hash(items, out_or_in_place): |
|
|
|
|
|
|
|
|
|
len_ = len(items) |
|
|
|
if out_or_in_place is None: |
|
|
|
acc = torch.add(XXPRIME_5, items[0], alpha=XXPRIME_2, out=items[0]) |
|
else: |
|
|
|
acc = torch.add(XXPRIME_5, items[0], alpha=XXPRIME_2, out=out_or_in_place) |
|
|
|
upshift = acc << 31 |
|
acc >>= 33 |
|
acc &= 0x7fffffff |
|
acc |= upshift |
|
|
|
acc *= XXPRIME_1 |
|
|
|
for i in range(1, len_): |
|
|
|
acc.add_(items[i], alpha=XXPRIME_2) |
|
|
|
|
|
upshift = acc << 31 |
|
acc >>= 33 |
|
acc &= 0x7fffffff |
|
acc |= upshift |
|
|
|
acc *= XXPRIME_1 |
|
|
|
acc += (len_ ^ XXPRIME_5_3527539) |
|
return acc |
|
|
|
def hash(buffer, *incoming_unhashed_ints): |
|
if len(buffer) < 16: |
|
return bytes(buffer).__hash__() |
|
|
|
|
|
|
|
|
|
|
|
words = len(buffer) // 8 |
|
dwords = words // 2 |
|
incoming_data = torch.frombuffer(buffer, count=words, dtype=torch.int64) |
|
incoming_unhashed_ints = [int.from_bytes(buffer[words*8:],'little')] + list(incoming_unhashed_ints) |
|
|
|
incoming_hashable_length = words & ~1 |
|
incoming_unhashed_length = words & 1 |
|
incoming_unhashed_int_length = len(incoming_unhashed_ints) |
|
incoming_hashable_data = incoming_data[:incoming_hashable_length].view(2,-1) |
|
incoming_unhashed_data = incoming_data[incoming_hashable_length:] |
|
|
|
storage = torch.empty([dwords + incoming_unhashed_length + incoming_unhashed_int_length], dtype=torch.int64) |
|
hashed_data = tensor_python_tuple_hash(incoming_hashable_data, out_or_in_place=storage[:dwords]) |
|
storage[dwords:-incoming_unhashed_int_length] = incoming_unhashed_data |
|
for idx in range(incoming_unhashed_int_length): |
|
storage[dwords+idx] = incoming_unhashed_ints[idx] |
|
|
|
incoming_data = storage |
|
words = len(incoming_data) |
|
dwords = words // 2 |
|
|
|
|
|
while words > 1: |
|
incoming_hashable_length = words & ~1 |
|
incoming_unhashed_length = words & 1 |
|
incoming_hashable_data = incoming_data[:incoming_hashable_length].view(2,-1) |
|
incoming_unhashed_tensor_data = incoming_data[incoming_hashable_length:] |
|
|
|
hashed_data = tensor_python_tuple_hash(incoming_hashable_data, out_or_in_place=None) |
|
words = dwords + incoming_unhashed_length |
|
storage[dwords:words] = incoming_unhashed_tensor_data |
|
incoming_data = storage[:words] |
|
dwords = words // 2 |
|
|
|
return incoming_data[0].item() |
|
|
|
if __name__ == '__main__': |
|
print(hash(bytearray(b'the quick brown fox jumped over the lazy dog'))) |
|
|