From 9db53a6fb1c3dc0e6112022ac4140fe0dc0c2c67 Mon Sep 17 00:00:00 2001 From: Robert Zajac Date: Sun, 21 Oct 2018 15:19:22 -0400 Subject: [PATCH] Adding new methods to multiaddr and commenting --- network/multiaddr.py | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/network/multiaddr.py b/network/multiaddr.py index e6d4a5c..d5de3e0 100644 --- a/network/multiaddr.py +++ b/network/multiaddr.py @@ -1,6 +1,12 @@ class Multiaddr: + # Validates input string and constructs internal representation. def __init__(self, addr): + # Empty multiaddrs are valid. + if not addr: + self.protocol_map = dict() + return + if not addr[0] == "/": raise MultiaddrValueError("Invalid input multiaddr.") @@ -22,17 +28,53 @@ class Multiaddr: is_protocol = not is_protocol self.protocol_map = protocol_map - self.addr = addr def get_protocols(self): + """ + :return: List of protocols contained in this multiaddr. + """ return list(self.protocol_map.keys()) 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: return None 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): """Raised when the input string to the Multiaddr constructor was invalid."""