2020-07-15 19:18:55 +00:00
|
|
|
## Nim-LibP2P
|
|
|
|
## Copyright (c) 2019 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 tables, sequtils, sets
|
2020-07-17 19:46:24 +00:00
|
|
|
import pubsubpeer, ../../peerid
|
2020-07-15 19:18:55 +00:00
|
|
|
|
|
|
|
type
|
2020-07-17 19:46:24 +00:00
|
|
|
PeerTable* = Table[string, HashSet[PubSubPeer]] # topic string to peer map
|
2020-07-15 19:18:55 +00:00
|
|
|
|
2020-08-12 00:05:49 +00:00
|
|
|
proc hasPeerID*(t: PeerTable, topic: string, peerId: PeerID): bool =
|
2020-09-04 16:31:43 +00:00
|
|
|
if topic in t:
|
|
|
|
for peer in t[topic]:
|
|
|
|
if peer.peerId == peerId:
|
|
|
|
return true
|
|
|
|
false
|
2020-07-15 19:18:55 +00:00
|
|
|
|
|
|
|
func addPeer*(table: var PeerTable, topic: string, peer: PubSubPeer): bool =
|
2020-07-17 19:46:24 +00:00
|
|
|
# returns true if the peer was added,
|
|
|
|
# false if it was already in the collection
|
|
|
|
not table.mgetOrPut(topic,
|
|
|
|
initHashSet[PubSubPeer]())
|
|
|
|
.containsOrIncl(peer)
|
2020-07-15 19:18:55 +00:00
|
|
|
|
|
|
|
func removePeer*(table: var PeerTable, topic: string, peer: PubSubPeer) =
|
|
|
|
table.withValue(topic, peers):
|
|
|
|
peers[].excl(peer)
|
|
|
|
if peers[].len == 0:
|
|
|
|
table.del(topic)
|
|
|
|
|
|
|
|
func hasPeer*(table: PeerTable, topic: string, peer: PubSubPeer): bool =
|
|
|
|
(topic in table) and (peer in table[topic])
|
|
|
|
|
|
|
|
func peers*(table: PeerTable, topic: string): int =
|
|
|
|
if topic in table:
|
|
|
|
table[topic].len
|
|
|
|
else:
|
|
|
|
0
|
|
|
|
|
|
|
|
func getPeers*(table: Table[string, HashSet[string]], topic: string): HashSet[string] =
|
|
|
|
table.getOrDefault(topic, initHashSet[string]())
|