Adding new methods to multiaddr and commenting

This commit is contained in:
Robert Zajac 2018-10-21 15:19:22 -04:00
parent 342e0318a5
commit 9db53a6fb1

View File

@ -1,6 +1,12 @@
class Multiaddr: class Multiaddr:
# Validates input string and constructs internal representation.
def __init__(self, addr): def __init__(self, addr):
# Empty multiaddrs are valid.
if not addr:
self.protocol_map = dict()
return
if not addr[0] == "/": if not addr[0] == "/":
raise MultiaddrValueError("Invalid input multiaddr.") raise MultiaddrValueError("Invalid input multiaddr.")
@ -22,17 +28,53 @@ class Multiaddr:
is_protocol = not is_protocol is_protocol = not is_protocol
self.protocol_map = protocol_map self.protocol_map = protocol_map
self.addr = addr
def get_protocols(self): def get_protocols(self):
"""
:return: List of protocols contained in this multiaddr.
"""
return list(self.protocol_map.keys()) return list(self.protocol_map.keys())
def get_protocol_value(self, protocol): def get_protocol_value(self, protocol):
"""
Getter for protocol values in this multiaddr.
:param protocol: the protocol whose value to retrieve
:return: value of input protocol
"""
if protocol not in self.protocol_map: if protocol not in self.protocol_map:
return None return None
return self.protocol_map[protocol] return self.protocol_map[protocol]
def add_protocol(self, protocol, value):
"""
Setter for protocol values in this multiaddr.
:param protocol: the protocol whose value to set or add
:param value: the value for the input protocol
:return: True if successful
"""
self.protocol_map[protocol] = value
return True
def remove_protocol(self, protocol):
"""
Remove protocol and its value from this multiaddr.
:param protocol: the protocol to remove
:return: True if remove succeeded, False if protocol was not contained in this multiaddr
"""
del self.protocol_map[protocol]
def get_multiaddr_string(self):
"""
:return: the string representation of this multiaddr.
"""
addr = ""
for protocol in self.protocol_map:
addr += "/" + protocol + "/" + self.get_protocol_value(protocol)
return addr
class MultiaddrValueError(ValueError): class MultiaddrValueError(ValueError):
"""Raised when the input string to the Multiaddr constructor was invalid.""" """Raised when the input string to the Multiaddr constructor was invalid."""