nim-libp2p/libp2p/streams/connection.nim

51 lines
1.4 KiB
Nim
Raw Normal View History

2020-04-14 11:51:26 -06:00
## Nim-LibP2P
## Copyright (c) 2020 Status Research & Development GmbH
## Licensed under either of
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
## at your option.
## This file may not be copied, modified, or distributed except according to
## those terms.
import chronos
import stream,
../peerinfo,
../multiaddress
type
2020-04-16 15:31:31 -06:00
Connection* = ref object of Stream[seq[byte]]
2020-04-14 11:51:26 -06:00
peerInfo*: PeerInfo
observedAddr*: MultiAddress
2020-04-16 15:31:31 -06:00
stream*: Stream[seq[byte]]
2020-04-14 11:51:26 -06:00
2020-04-16 23:26:01 -06:00
proc connSource*(s: Stream[seq[byte]]): Source[seq[byte]] {.gcsafe.} =
2020-04-16 15:31:31 -06:00
if not isNil(s.sourceImpl):
2020-04-16 23:26:01 -06:00
var c = Connection(s)
return c.stream.sourceImpl(c.stream)
2020-04-14 11:51:26 -06:00
2020-04-16 23:26:01 -06:00
proc connSink*(s: Stream[seq[byte]]): Sink[seq[byte]] {.gcsafe.} =
2020-04-16 15:31:31 -06:00
if not isNil(s.sinkImpl):
2020-04-16 23:26:01 -06:00
var c = Connection(s)
return c.stream.sinkImpl(c.stream)
2020-04-14 11:51:26 -06:00
proc close*(s: Connection) {.async.} =
2020-04-14 17:14:27 -06:00
result = close(s.stream)
2020-04-14 11:51:26 -06:00
proc getObservedAddrs*(c: Connection): Future[MultiAddress] {.async.} =
## get resolved multiaddresses for the connection
result = c.observedAddr
proc `$`*(c: Connection): string =
if not isNil(c.peerInfo):
result = $(c.peerInfo)
2020-04-16 23:26:01 -06:00
proc init*[T](C: type[Connection],
stream: T,
peerInfo: PeerInfo = nil): C =
Connection(stream: stream,
sourceImpl: connSource,
sinkImpl: connSink,
peerInfo: peerInfo,
name: "Connection")