Add ID.to_base58() and comparison against str type

This commit is contained in:
NIC619 2019-08-01 21:48:30 +08:00
parent 924e965537
commit 0173b5e0d9
No known key found for this signature in database
GPG Key ID: 570C35F5C2D51B17

View File

@ -20,6 +20,7 @@ class ID:
_bytes: bytes _bytes: bytes
_xor_id: int = None _xor_id: int = None
_b58_str: str = None
def __init__(self, peer_id_bytes: bytes) -> None: def __init__(self, peer_id_bytes: bytes) -> None:
self._bytes = peer_id_bytes self._bytes = peer_id_bytes
@ -33,17 +34,21 @@ class ID:
def to_bytes(self) -> bytes: def to_bytes(self) -> bytes:
return self._bytes return self._bytes
def pretty(self) -> str: def to_base58(self) -> str:
return base58.b58encode(self._bytes).decode() if not self._b58_str:
self._b58_str = base58.b58encode(self._bytes).decode()
return self._b58_str
def __str__(self) -> str: def __bytes__(self) -> bytes:
return self.pretty() return self._bytes
__repr__ = __str__ __repr__ = __str__ = pretty = to_string = to_base58
def __eq__(self, other: object) -> bool: def __eq__(self, other: object) -> bool:
# pylint: disable=protected-access, no-else-return # pylint: disable=protected-access, no-else-return
if isinstance(other, bytes): if isinstance(other, str):
return self.to_base58() == other
elif isinstance(other, bytes):
return self._bytes == other return self._bytes == other
elif isinstance(other, ID): elif isinstance(other, ID):
return self._bytes == other._bytes return self._bytes == other._bytes