From ab04137853bc59ce0daa99ac8946b856a87af929 Mon Sep 17 00:00:00 2001
From: Juan Batiz-Benet <juan@benet.ai>
Date: Wed, 17 Sep 2014 01:51:03 -0700
Subject: [PATCH] SortByDistance copy fix

---
 routing/dht/keyspace/keyspace.go |  4 +++-
 routing/dht/keyspace/xor_test.go | 10 +++++++++-
 2 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/routing/dht/keyspace/keyspace.go b/routing/dht/keyspace/keyspace.go
index 3d3260b2..a385e9a0 100644
--- a/routing/dht/keyspace/keyspace.go
+++ b/routing/dht/keyspace/keyspace.go
@@ -86,9 +86,11 @@ func (s byDistanceToCenter) Less(i, j int) bool {
 // It returns a new list, where the Keys toSort have been sorted by their
 // distance to the center Key.
 func SortByDistance(sp KeySpace, center Key, toSort []Key) []Key {
+	toSortCopy := make([]Key, len(toSort))
+	copy(toSortCopy, toSort)
 	bdtc := &byDistanceToCenter{
 		Center: center,
-		Keys:   toSort[:], // copy
+		Keys:   toSortCopy, // copy
 	}
 	sort.Sort(bdtc)
 	return bdtc.Keys
diff --git a/routing/dht/keyspace/xor_test.go b/routing/dht/keyspace/xor_test.go
index 58987ad1..46757b7f 100644
--- a/routing/dht/keyspace/xor_test.go
+++ b/routing/dht/keyspace/xor_test.go
@@ -97,7 +97,7 @@ func TestXorKeySpace(t *testing.T) {
 	}
 }
 
-func TestCenterSorting(t *testing.T) {
+func TestDistancesAndCenterSorting(t *testing.T) {
 
 	adjs := [][]byte{
 		[]byte{173, 149, 19, 27, 192, 183, 153, 192, 177, 175, 71, 127, 177, 79, 207, 38, 166, 169, 247, 96, 121, 228, 139, 240, 144, 172, 183, 232, 54, 123, 253, 14},
@@ -136,4 +136,12 @@ func TestCenterSorting(t *testing.T) {
 		t.Errorf("2<<32 should be smaller")
 	}
 
+	keys2 := SortByDistance(XORKeySpace, keys[2], keys)
+	order := []int{2, 3, 4, 5, 1, 0}
+	for i, o := range order {
+		if !bytes.Equal(keys[o].Adjusted, keys2[i].Adjusted) {
+			t.Errorf("order is wrong. %d?? %v == %v", o, keys[o], keys2[i])
+		}
+	}
+
 }
-- 
GitLab