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
|
|
|
}
|
|
|
|
|
|
|
|
func (me nodeMaxHeap) Len() int { return len(me.IDs) }
|
|
|
|
|
|
|
|
func (me nodeMaxHeap) Less(i, j int) bool {
|
2014-12-26 06:21:48 +00:00
|
|
|
m := me.IDs[i].Distance(&me.Target)
|
|
|
|
n := me.IDs[j].Distance(&me.Target)
|
|
|
|
return m.Cmp(&n) > 0
|
2014-06-24 13:20:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (me *nodeMaxHeap) Pop() (ret interface{}) {
|
|
|
|
ret, me.IDs = me.IDs[len(me.IDs)-1], me.IDs[:len(me.IDs)-1]
|
|
|
|
return
|
|
|
|
}
|
|
|
|
func (me *nodeMaxHeap) Push(val interface{}) {
|
2014-12-26 06:21:48 +00:00
|
|
|
me.IDs = append(me.IDs, val.(nodeID))
|
2014-06-24 13:20:49 +00:00
|
|
|
}
|
|
|
|
func (me nodeMaxHeap) Swap(i, j int) {
|
2014-07-09 16:59:37 +00:00
|
|
|
me.IDs[i], me.IDs[j] = me.IDs[j], me.IDs[i]
|
2014-06-24 13:20:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type closestNodesSelector struct {
|
|
|
|
closest nodeMaxHeap
|
|
|
|
k int
|
|
|
|
}
|
|
|
|
|
2014-12-26 06:21:48 +00:00
|
|
|
func (me *closestNodesSelector) Push(id nodeID) {
|
2014-06-24 13:20:49 +00:00
|
|
|
heap.Push(&me.closest, id)
|
|
|
|
if me.closest.Len() > me.k {
|
|
|
|
heap.Pop(&me.closest)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-12-26 06:21:48 +00:00
|
|
|
func (me *closestNodesSelector) IDs() []nodeID {
|
2014-06-24 13:20:49 +00:00
|
|
|
return me.closest.IDs
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|