@cryptotaxi247 / kubo / commits / 550971fba

equalize sizes

Juan Batiz-Benet committed Jul 29, 2014 at 17:53 UTC 550971fba6d734d8035e7b1ba5d0171df0ebe0d8
1 file changed +50 -36
routing/dht/table.go
+50 -36
@@ -1,61 +1,75 @@
1 package dht
2
3 import (
4 - "container/list"
4 + "bytes"
5 + "container/list"
6 )
7
7 -
8 // ID for IpfsDHT should be a byte slice, to allow for simpler operations
9 // (xor). DHT ids are based on the peer.IDs.
10 //
11 -// NOTE: peer.IDs are biased because they are (a) multihashes (first bytes
12 -// biased), and (b) first bits are zeroes when using the S/Kademlia PoW.
13 -// Thus, may need to re-hash keys (uniform dist). TODO(jbenet)
11 +// NOTE: peer.IDs are biased because they are multihashes (first bytes
12 +// biased). Thus, may need to re-hash keys (uniform dist). TODO(jbenet)
13 type ID []byte
14
15 // Bucket holds a list of peers.
16 type Bucket []*list.List
17
19 -
18 // RoutingTable defines the routing table.
19 type RoutingTable struct {
20
23 - // kBuckets define all the fingers to other nodes.
24 - Buckets []Bucket
21 + // kBuckets define all the fingers to other nodes.
22 + Buckets []Bucket
23 }
24
25 +func (id ID) Equal(other ID) bool {
26 + return bytes.Equal(id, other)
27 +}
28 +
29 +func (id ID) Less(other interface{}) bool {
30 + a, b := equalizeSizes(id, other.(ID))
31 + for i := 0; i < len(a); i++ {
32 + if a[i] != b[i] {
33 + return a[i] < b[i]
34 + }
35 + }
36 + return len(a) < len(b)
37 +}
38
39 func (id ID) commonPrefixLen() int {
29 - for i := 0; i < len(id); i++ {
30 - for j := 0; j < 8; j++ {
31 - if (id[i] >> uint8(7 - j)) & 0x1 != 0 {
32 - return i * 8 + j;
33 - }
34 - }
35 - }
36 - return len(id) * 8 - 1;
40 + for i := 0; i < len(id); i++ {
41 + for j := 0; j < 8; j++ {
42 + if (id[i]>>uint8(7-j))&0x1 != 0 {
43 + return i*8 + j
44 + }
45 + }
46 + }
47 + return len(id)*8 - 1
48 }
49
50 func xor(a, b ID) ID {
51 + a, b = equalizeSizes(a, b)
52 +
53 + c := make(ID, len(a))
54 + for i := 0; i < len(a); i++ {
55 + c[i] = a[i] ^ b[i]
56 + }
57 + return c
58 +}
59 +
60 +func equalizeSizes(a, b ID) (ID, ID) {
61 + la := len(a)
62 + lb := len(b)
63 +
64 + if la < lb {
65 + na := make([]byte, lb)
66 + copy(na, a)
67 + a = na
68 + } else if lb < la {
69 + nb := make([]byte, la)
70 + copy(nb, b)
71 + b = nb
72 + }
73
41 - // ids may actually be of different sizes.
42 - var ba ID
43 - var bb ID
44 - if len(a) >= len(b) {
45 - ba = a
46 - bb = b
47 - } else {
48 - ba = b
49 - bb = a
50 - }
51 -
52 - c := make(ID, len(ba))
53 - for i := 0; i < len(ba); i++ {
54 - if len(bb) > i {
55 - c[i] = ba[i] ^ bb[i]
56 - } else {
57 - c[i] = ba[i] ^ 0
58 - }
59 - }
60 - return c
74 + return a, b
75 }