bucket.go 827 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package dht
  2. import (
  3. "time"
  4. "github.com/anacrolix/chansync"
  5. "github.com/anacrolix/dht/v2/int160"
  6. )
  7. type bucket struct {
  8. // Per the "Routing Table" section of BEP 5.
  9. changed chansync.BroadcastCond
  10. lastChanged time.Time
  11. nodes map[*node]struct{}
  12. }
  13. func (b *bucket) Len() int {
  14. return len(b.nodes)
  15. }
  16. func (b *bucket) EachNode(f func(*node) bool) bool {
  17. for n := range b.nodes {
  18. if !f(n) {
  19. return false
  20. }
  21. }
  22. return true
  23. }
  24. func (b *bucket) AddNode(n *node, k int) {
  25. if _, ok := b.nodes[n]; ok {
  26. return
  27. }
  28. if b.nodes == nil {
  29. b.nodes = make(map[*node]struct{}, k)
  30. }
  31. b.nodes[n] = struct{}{}
  32. b.lastChanged = time.Now()
  33. b.changed.Broadcast()
  34. }
  35. func (b *bucket) GetNode(addr Addr, id int160.T) *node {
  36. for n := range b.nodes {
  37. if n.hasAddrAndID(addr, id) {
  38. return n
  39. }
  40. }
  41. return nil
  42. }