2019-06-21 02:55:47 +02:00
|
|
|
from lbry.dht import constants
|
2018-05-29 16:59:46 +02:00
|
|
|
|
|
|
|
|
2018-07-22 00:34:59 +02:00
|
|
|
class Distance:
|
2017-10-23 19:09:46 +02:00
|
|
|
"""Calculate the XOR result between two string variables.
|
|
|
|
|
|
|
|
Frequently we re-use one of the points so as an optimization
|
2018-07-31 19:20:25 +02:00
|
|
|
we pre-calculate the value of that point.
|
2017-10-23 19:09:46 +02:00
|
|
|
"""
|
|
|
|
|
2019-01-22 18:49:43 +01:00
|
|
|
def __init__(self, key: bytes):
|
2020-01-03 04:57:28 +01:00
|
|
|
if len(key) != constants.HASH_LENGTH:
|
2019-03-15 17:44:41 +01:00
|
|
|
raise ValueError(f"invalid key length: {len(key)}")
|
2017-10-23 19:09:46 +02:00
|
|
|
self.key = key
|
2018-08-22 17:47:40 +02:00
|
|
|
self.val_key_one = int.from_bytes(key, 'big')
|
2017-10-23 19:09:46 +02:00
|
|
|
|
2019-01-22 18:49:43 +01:00
|
|
|
def __call__(self, key_two: bytes) -> int:
|
2020-01-03 04:57:28 +01:00
|
|
|
if len(key_two) != constants.HASH_LENGTH:
|
2019-03-15 17:44:41 +01:00
|
|
|
raise ValueError(f"invalid length of key to compare: {len(key_two)}")
|
2018-08-22 17:47:40 +02:00
|
|
|
val_key_two = int.from_bytes(key_two, 'big')
|
2017-10-23 19:09:46 +02:00
|
|
|
return self.val_key_one ^ val_key_two
|
|
|
|
|
2020-01-03 05:31:28 +01:00
|
|
|
def is_closer(self, key_a: bytes, key_b: bytes) -> bool:
|
|
|
|
"""Returns true is `key_a` is closer to `key` than `key_b` is"""
|
|
|
|
return self(key_a) < self(key_b)
|