util.go 1.34 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
package dht

import (
	"sync"

	peer "github.com/jbenet/go-ipfs/peer"
)

// Pool size is the number of nodes used for group find/set RPC calls
var PoolSize = 6

// We put the 'K' in kademlia!
var KValue = 10

// Its in the paper, i swear
var AlphaValue = 3

// A counter for incrementing a variable across multiple threads
type counter struct {
	n   int
	mut sync.Mutex
}

func (c *counter) Increment() {
	c.mut.Lock()
	c.n++
	c.mut.Unlock()
}

func (c *counter) Decrement() {
	c.mut.Lock()
	c.n--
	c.mut.Unlock()
}

func (c *counter) Size() (s int) {
	c.mut.Lock()
	s = c.n
	c.mut.Unlock()
	return
}

43
// peerSet is a threadsafe set of peers
44 45 46 47 48 49 50 51 52 53 54
type peerSet struct {
	ps map[string]bool
	lk sync.RWMutex
}

func newPeerSet() *peerSet {
	ps := new(peerSet)
	ps.ps = make(map[string]bool)
	return ps
}

55
func (ps *peerSet) Add(p peer.Peer) {
56
	ps.lk.Lock()
57
	ps.ps[string(p.ID())] = true
58 59 60
	ps.lk.Unlock()
}

61
func (ps *peerSet) Contains(p peer.Peer) bool {
62
	ps.lk.RLock()
63
	_, ok := ps.ps[string(p.ID())]
64 65 66 67 68 69 70 71 72
	ps.lk.RUnlock()
	return ok
}

func (ps *peerSet) Size() int {
	ps.lk.RLock()
	defer ps.lk.RUnlock()
	return len(ps.ps)
}
73

74
func (ps *peerSet) AddIfSmallerThan(p peer.Peer, maxsize int) bool {
75 76
	var success bool
	ps.lk.Lock()
77
	if _, ok := ps.ps[string(p.ID())]; !ok && len(ps.ps) < maxsize {
78
		success = true
79
		ps.ps[string(p.ID())] = true
80 81 82 83
	}
	ps.lk.Unlock()
	return success
}