Skip to content

Commit

Permalink
Merge branch 'experiment/functional' into feat/peer-discovery
Browse files Browse the repository at this point in the history
  • Loading branch information
Rahul Ghangas committed Mar 8, 2021
2 parents 280501f + 2c5d279 commit 2c8e733
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions dht/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,9 @@ func (table *InMemTable) Peers(n int) []id.Signatory {

// RandomPeers returns n random peer IDs
func (table *InMemTable) RandomPeers(n int) []id.Signatory {
table.sortedMu.Lock()
m := len(table.sorted)
table.sortedMu.Unlock()

if n <= 0 {
// For values of n that are less than, or equal to, zero, return an
Expand All @@ -207,6 +209,8 @@ func (table *InMemTable) RandomPeers(n int) []id.Signatory {
}
if n >= m {
sigs := make([]id.Signatory, m)
table.sortedMu.Lock()
defer table.sortedMu.Unlock()
copy(sigs, table.sorted)
return sigs
}
Expand All @@ -218,6 +222,8 @@ func (table *InMemTable) RandomPeers(n int) []id.Signatory {
if m <= 10000 || n >= m / 50.0 {
shuffled := make([]id.Signatory, n)
indexPerm := rand.Perm(m)
table.sortedMu.Lock()
defer table.sortedMu.Unlock()
for i := 0; i < n; i++ {
shuffled[i] = table.sorted[indexPerm[i]]
}
Expand All @@ -227,6 +233,8 @@ func (table *InMemTable) RandomPeers(n int) []id.Signatory {
// Otherwise, use Floyd's sampling algorithm to select n random elements
set := make(map[int]struct{}, n)
randomSelection := make([]id.Signatory, 0, n)
table.sortedMu.Lock()
defer table.sortedMu.Unlock()
for i := m - n; i < m; i++ {
index := table.randObj.Intn(i)
if _, ok := set[index]; !ok {
Expand Down

0 comments on commit 2c8e733

Please sign in to comment.