lbry-sdk/lbrynet/dht/protocol/distance.py

24 lines
759 B
Python
Raw Normal View History

2018-05-29 16:59:46 +02:00
from lbrynet.dht import constants
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
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):
if len(key) != constants.hash_length:
2018-05-29 22:50:23 +02:00
raise ValueError("invalid key length: %i" % len(key))
2017-10-23 19:09:46 +02:00
self.key = key
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:
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
2019-01-22 18:49:43 +01:00
def is_closer(self, a: bytes, b: bytes) -> bool:
2017-10-23 19:09:46 +02:00
"""Returns true is `a` is closer to `key` than `b` is"""
return self(a) < self(b)