2014-06-24 13:20:49 +00:00
|
|
|
package dht
|
|
|
|
|
|
|
|
import (
|
|
|
|
"container/heap"
|
|
|
|
)
|
|
|
|
|
|
|
|
type nodeMaxHeap struct {
|
2014-12-26 06:21:48 +00:00
|
|
|
IDs []nodeID
|
|
|
|
Target nodeID
|
2014-06-24 13:20:49 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (mh nodeMaxHeap) Len() int { return len(mh.IDs) }
|
2014-06-24 13:20:49 +00:00
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (mh nodeMaxHeap) Less(i, j int) bool {
|
|
|
|
m := mh.IDs[i].Distance(&mh.Target)
|
|
|
|
n := mh.IDs[j].Distance(&mh.Target)
|
2014-12-26 06:21:48 +00:00
|
|
|
return m.Cmp(&n) > 0
|
2014-06-24 13:20:49 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (mh *nodeMaxHeap) Pop() (ret interface{}) {
|
|
|
|
ret, mh.IDs = mh.IDs[len(mh.IDs)-1], mh.IDs[:len(mh.IDs)-1]
|
2014-06-24 13:20:49 +00:00
|
|
|
return
|
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
func (mh *nodeMaxHeap) Push(val interface{}) {
|
|
|
|
mh.IDs = append(mh.IDs, val.(nodeID))
|
2014-06-24 13:20:49 +00:00
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
func (mh nodeMaxHeap) Swap(i, j int) {
|
|
|
|
mh.IDs[i], mh.IDs[j] = mh.IDs[j], mh.IDs[i]
|
2014-06-24 13:20:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type closestNodesSelector struct {
|
|
|
|
closest nodeMaxHeap
|
|
|
|
k int
|
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cns *closestNodesSelector) Push(id nodeID) {
|
|
|
|
heap.Push(&cns.closest, id)
|
|
|
|
if cns.closest.Len() > cns.k {
|
|
|
|
heap.Pop(&cns.closest)
|
2014-06-24 13:20:49 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cns *closestNodesSelector) IDs() []nodeID {
|
|
|
|
return cns.closest.IDs
|
2014-06-24 13:20:49 +00:00
|
|
|
}
|
|
|
|
|
2014-12-26 06:21:48 +00:00
|
|
|
func newKClosestNodesSelector(k int, targetID nodeID) (ret closestNodesSelector) {
|
2014-06-24 13:20:49 +00:00
|
|
|
ret.k = k
|
|
|
|
ret.closest.Target = targetID
|
|
|
|
return
|
|
|
|
}
|