SortByDistance copy fix
Juan Batiz-Benet committed
Sep 17, 2014 at 01:51 UTC
ab04137853bc59ce0daa99ac8946b856a87af929
2 files changed
+12
-2
routing/dht/keyspace/keyspace.go
+3
-1
@@ -86,9 +86,11 @@ func (s byDistanceToCenter) Less(i, j int) bool {
86
// It returns a new list, where the Keys toSort have been sorted by their
87
// distance to the center Key.
88
func SortByDistance(sp KeySpace, center Key, toSort []Key) []Key {
89
+ toSortCopy := make([]Key, len(toSort))
90
+ copy(toSortCopy, toSort)
91
bdtc := &byDistanceToCenter{
92
Center: center,
91
- Keys: toSort[:], // copy
93
+ Keys: toSortCopy, // copy
94
}
95
sort.Sort(bdtc)
96
return bdtc.Keys
routing/dht/keyspace/xor_test.go
+9
-1
@@ -97,7 +97,7 @@ func TestXorKeySpace(t *testing.T) {
97
}
98
}
99
100
-func TestCenterSorting(t *testing.T) {
100
+func TestDistancesAndCenterSorting(t *testing.T) {
101
102
adjs := [][]byte{
103
[]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) {
136
t.Errorf("2<<32 should be smaller")
137
}
138
139
+ keys2 := SortByDistance(XORKeySpace, keys[2], keys)
140
+ order := []int{2, 3, 4, 5, 1, 0}
141
+ for i, o := range order {
142
+ if !bytes.Equal(keys[o].Adjusted, keys2[i].Adjusted) {
143
+ t.Errorf("order is wrong. %d?? %v == %v", o, keys[o], keys2[i])
144
+ }
145
+ }
146
+
147
}