sorting.go 1.24 KB
Newer Older
1 2 3 4
package kbucket

import (
	"container/list"
Jeromy's avatar
Jeromy committed
5
	peer "gx/ipfs/QmQGwpJy9P4yXZySmqkZEXCmbBpJUb8xntCv8Ca4taZwDC/go-libp2p-peer"
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 43 44 45 46 47 48 49 50 51 52 53 54 55
	"sort"
)

// A helper struct to sort peers by their distance to the local node
type peerDistance struct {
	p        peer.ID
	distance ID
}

// peerSorterArr implements sort.Interface to sort peers by xor distance
type peerSorterArr []*peerDistance

func (p peerSorterArr) Len() int      { return len(p) }
func (p peerSorterArr) Swap(a, b int) { p[a], p[b] = p[b], p[a] }
func (p peerSorterArr) Less(a, b int) bool {
	return p[a].distance.less(p[b].distance)
}

//

func copyPeersFromList(target ID, peerArr peerSorterArr, peerList *list.List) peerSorterArr {
	for e := peerList.Front(); e != nil; e = e.Next() {
		p := e.Value.(peer.ID)
		pID := ConvertPeerID(p)
		pd := peerDistance{
			p:        p,
			distance: xor(target, pID),
		}
		peerArr = append(peerArr, &pd)
	}
	return peerArr
}

func SortClosestPeers(peers []peer.ID, target ID) []peer.ID {
	var psarr peerSorterArr
	for _, p := range peers {
		pID := ConvertPeerID(p)
		pd := &peerDistance{
			p:        p,
			distance: xor(target, pID),
		}
		psarr = append(psarr, pd)
	}
	sort.Sort(psarr)
	var out []peer.ID
	for _, p := range psarr {
		out = append(out, p.p)
	}
	return out
}