Add MultiAddress.init(TransportAddress).

This commit is contained in:
cheatfate 2019-10-10 07:16:02 +03:00
parent 2e369a7967
commit fb9d2d7d05
No known key found for this signature in database
GPG Key ID: 46ADD633A7201F95
1 changed files with 26 additions and 0 deletions

View File

@ -9,6 +9,7 @@
## This module implements MultiAddress. ## This module implements MultiAddress.
import tables, strutils, net import tables, strutils, net
import chronos
import multicodec, multihash, multibase, transcoder, base58, base32, vbuffer import multicodec, multihash, multibase, transcoder, base58, base32, vbuffer
from peer import PeerID from peer import PeerID
@ -749,6 +750,31 @@ proc init*(mtype: typedesc[MultiAddress],
raise newException(MultiAddressError, "Error encoding port number") raise newException(MultiAddressError, "Error encoding port number")
result.data.finish() result.data.finish()
proc init*(mtype: typedesc[MultiAddress], address: TransportAddress,
protocol: Protocol = IPPROTO_TCP): MultiAddress =
## Initialize MultiAddress using chronos.TransportAddress (IPv4/IPv6/Unix)
## and protocol information (UDP/TCP).
result.data = initVBuffer()
let protoProto = case protocol
of IPPROTO_TCP: getProtocol("tcp")
of IPPROTO_UDP: getProtocol("udp")
else: raise newException(AssertionError,
"protocol should be either TCP or UDP")
if address.family == AddressFamily.IPv4:
result.data.write(getProtocol("ip4").mcodec)
result.data.writeArray(address.address_v4)
result.data.write(protoProto.mcodec)
discard protoProto.coder.stringToBuffer($address.port, result.data)
elif address.family == AddressFamily.IPv6:
result.data.write(getProtocol("ip6").mcodec)
result.data.writeArray(address.address_v6)
result.data.write(protoProto.mcodec)
discard protoProto.coder.stringToBuffer($address.port, result.data)
elif address.family == AddressFamily.Unix:
result.data.write(getProtocol("unix").mcodec)
result.data.writeSeq(address.address_un)
result.data.finish()
proc isEmpty*(ma: MultiAddress): bool = proc isEmpty*(ma: MultiAddress): bool =
## Returns ``true``, if MultiAddress ``ma`` is empty or non initialized. ## Returns ``true``, if MultiAddress ``ma`` is empty or non initialized.
result = len(ma.data) == 0 result = len(ma.data) == 0