From 91d2f52f4e2521bab4e9b4ddecc7c26793c1c6ed Mon Sep 17 00:00:00 2001 From: Eugene Kabanov Date: Thu, 27 Feb 2020 19:26:42 +0200 Subject: [PATCH] Add some utility procedures to MultiAddress. (#94) * Add some utility procedures to MultiAddress. * Do not use result and add more operations to be more effective for compiler. --- libp2p/multiaddress.nim | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/libp2p/multiaddress.nim b/libp2p/multiaddress.nim index b6a4b80fe..a94d412c4 100644 --- a/libp2p/multiaddress.nim +++ b/libp2p/multiaddress.nim @@ -569,6 +569,31 @@ iterator items*(ma: MultiAddress): MultiAddress = res.data.finish() yield res +proc contains*(ma: MultiAddress, codec: MultiCodec): bool {.inline.} = + ## Returns ``true``, if address with MultiCodec ``codec`` present in + ## MultiAddress ``ma``. + var res = false + for item in ma.items: + if item.protoCode() == codec: + res = true + break + result = res + +proc `[]`*(ma: MultiAddress, codec: MultiCodec): MultiAddress {.inline.} = + ## Returns partial MultiAddress with MultiCodec ``codec`` and present in + ## MultiAddress ``ma``. + ## + ## Procedure will raise ``MultiAddressError`` if ``codec`` could not be + ## found inside of ``ma``. + var res = MultiAddress(data: initVBuffer()) + for item in ma.items: + if item.protoCode == codec: + res = item + break + if res.data.isEmpty(): + raise newException(MultiAddressError, "Codec is not present in address") + result = res + proc `$`*(value: MultiAddress): string = ## Return string representation of MultiAddress ``value``. var header: uint64