github.com/ethersphere/bee/v2@v2.2.0/pkg/swarm/proximity.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 6 7 // Proximity returns the proximity order of the MSB distance between x and y 8 // 9 // The distance metric MSB(x, y) of two equal length byte sequences x an y is the 10 // value of the binary integer cast of the x^y, ie., x and y bitwise xor-ed. 11 // the binary cast is big endian: most significant bit first (=MSB). 12 // 13 // Proximity(x, y) is a discrete logarithmic scaling of the MSB distance. 14 // It is defined as the reverse rank of the integer part of the base 2 15 // logarithm of the distance. 16 // It is calculated by counting the number of common leading zeros in the (MSB) 17 // binary representation of the x^y. 18 // 19 // (0 farthest, 255 closest, 256 self) 20 func Proximity(one, other []byte) (ret uint8) { 21 b := MaxPO/8 + 1 22 if l := uint8(len(one)); b > l { 23 b = l 24 } 25 if l := uint8(len(other)); b > l { 26 b = l 27 } 28 var m uint8 = 8 29 for i := uint8(0); i < b; i++ { 30 oxo := one[i] ^ other[i] 31 for j := uint8(0); j < m; j++ { 32 if (oxo>>(7-j))&0x01 != 0 { 33 return i*8 + j 34 } 35 } 36 } 37 return MaxPO 38 } 39 40 func ExtendedProximity(one, other []byte) (ret uint8) { 41 b := ExtendedPO/8 + 1 42 if l := uint8(len(one)); b > l { 43 b = l 44 } 45 if l := uint8(len(other)); b > l { 46 b = l 47 } 48 var m uint8 = 8 49 for i := uint8(0); i < b; i++ { 50 oxo := one[i] ^ other[i] 51 for j := uint8(0); j < m; j++ { 52 if (oxo>>(7-j))&0x01 != 0 { 53 return i*8 + j 54 } 55 } 56 } 57 return ExtendedPO 58 }