2022-07-01 18:19:57 +00:00
|
|
|
# Nim-LibP2P
|
2023-01-20 14:47:40 +00:00
|
|
|
# Copyright (c) 2023 Status Research & Development GmbH
|
2022-07-01 18:19:57 +00:00
|
|
|
# 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.
|
2020-07-15 19:18:55 +00:00
|
|
|
|
2023-06-07 11:12:49 +00:00
|
|
|
{.push raises: [].}
|
2021-03-09 12:22:52 +00:00
|
|
|
|
2023-04-26 11:44:45 +00:00
|
|
|
import std/[tables, sets, sequtils]
|
2021-03-09 12:22:52 +00:00
|
|
|
import ./pubsubpeer, ../../peerid
|
2020-07-15 19:18:55 +00:00
|
|
|
|
2023-03-06 15:36:10 +00:00
|
|
|
export tables, sets
|
|
|
|
|
2024-06-11 15:18:06 +00:00
|
|
|
type PeerTable* = Table[string, HashSet[PubSubPeer]] # topic string to peer map
|
2020-07-15 19:18:55 +00:00
|
|
|
|
2021-12-16 10:05:20 +00:00
|
|
|
proc hasPeerId*(t: PeerTable, topic: string, peerId: PeerId): bool =
|
2020-09-04 16:31:43 +00:00
|
|
|
if topic in t:
|
2021-03-09 12:22:52 +00:00
|
|
|
try:
|
|
|
|
for peer in t[topic]:
|
|
|
|
if peer.peerId == peerId:
|
|
|
|
return true
|
2024-06-11 15:18:06 +00:00
|
|
|
except KeyError:
|
|
|
|
raiseAssert "checked with in"
|
2020-09-04 16:31:43 +00:00
|
|
|
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
|
2024-06-11 15:18:06 +00:00
|
|
|
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 =
|
2021-03-09 12:22:52 +00:00
|
|
|
try:
|
|
|
|
(topic in table) and (peer in table[topic])
|
2024-06-11 15:18:06 +00:00
|
|
|
except KeyError:
|
|
|
|
raiseAssert "checked with in"
|
2020-07-15 19:18:55 +00:00
|
|
|
|
|
|
|
func peers*(table: PeerTable, topic: string): int =
|
|
|
|
if topic in table:
|
2024-06-11 15:18:06 +00:00
|
|
|
try:
|
|
|
|
table[topic].len
|
|
|
|
except KeyError:
|
|
|
|
raiseAssert "checked with in"
|
2020-07-15 19:18:55 +00:00
|
|
|
else:
|
|
|
|
0
|
2023-04-26 11:44:45 +00:00
|
|
|
|
|
|
|
func outboundPeers*(table: PeerTable, topic: string): int =
|
|
|
|
if topic in table:
|
2024-06-11 15:18:06 +00:00
|
|
|
try:
|
|
|
|
table[topic].countIt(it.outbound)
|
|
|
|
except KeyError:
|
|
|
|
raiseAssert "checked with in"
|
2023-04-26 11:44:45 +00:00
|
|
|
else:
|
|
|
|
0
|