github.com/ethersphere/bee/v2@v2.2.0/pkg/swarm/distance_test.go (about) 1 // Copyright 2020 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package swarm_test 6 7 import ( 8 "testing" 9 10 "github.com/ethersphere/bee/v2/pkg/swarm" 11 ) 12 13 type distanceTest struct { 14 x swarm.Address 15 y swarm.Address 16 result string 17 } 18 19 type distanceCmpTest struct { 20 a swarm.Address 21 x swarm.Address 22 y swarm.Address 23 result int 24 } 25 26 var ( 27 distanceTests = []distanceTest{ 28 { 29 x: swarm.MustParseHexAddress("9100000000000000000000000000000000000000000000000000000000000000"), 30 y: swarm.MustParseHexAddress("8200000000000000000000000000000000000000000000000000000000000000"), 31 result: "8593944123082061379093159043613555660984881674403010612303492563087302590464", 32 }, 33 } 34 35 distanceCmpTests = []distanceCmpTest{ 36 { 37 a: swarm.MustParseHexAddress("9100000000000000000000000000000000000000000000000000000000000000"), // 10010001 38 x: swarm.MustParseHexAddress("8200000000000000000000000000000000000000000000000000000000000000"), // 10000010 xor(0x91,0x82) = 19 39 y: swarm.MustParseHexAddress("1200000000000000000000000000000000000000000000000000000000000000"), // 00010010 xor(0x91,0x12) = 131 40 result: 1, 41 }, 42 { 43 a: swarm.MustParseHexAddress("9100000000000000000000000000000000000000000000000000000000000000"), 44 x: swarm.MustParseHexAddress("1200000000000000000000000000000000000000000000000000000000000000"), 45 y: swarm.MustParseHexAddress("8200000000000000000000000000000000000000000000000000000000000000"), 46 result: -1, 47 }, 48 { 49 a: swarm.MustParseHexAddress("9100000000000000000000000000000000000000000000000000000000000000"), 50 x: swarm.MustParseHexAddress("1200000000000000000000000000000000000000000000000000000000000000"), 51 y: swarm.MustParseHexAddress("1200000000000000000000000000000000000000000000000000000000000000"), 52 result: 0, 53 }, 54 } 55 ) 56 57 // TestDistance tests the correctness of the distance calculation. 58 func TestDistance(t *testing.T) { 59 t.Parallel() 60 61 for _, dt := range distanceTests { 62 distance, err := swarm.Distance(dt.x, dt.y) 63 if err != nil { 64 t.Fatal(err) 65 } 66 if distance.String() != dt.result { 67 t.Fatalf("incorrect distance, expected %s, got %s (x: %x, y: %x)", dt.result, distance.String(), dt.x, dt.y) 68 } 69 } 70 } 71 72 // TestDistanceCmp tests the distance comparison method. 73 func TestDistanceCmp(t *testing.T) { 74 t.Parallel() 75 76 for _, dt := range distanceCmpTests { 77 direction, err := swarm.DistanceCmp(dt.a, dt.x, dt.y) 78 if err != nil { 79 t.Fatal(err) 80 } 81 if direction != dt.result { 82 t.Fatalf("incorrect distance compare, expected %d, got %d (a: %x, x: %x, y: %x)", dt.result, direction, dt.a, dt.x, dt.y) 83 } 84 } 85 }