aboutsummaryrefslogtreecommitdiff
path: root/infohash.go
blob: 0ee5879eaa95ae8eeb2826832130011340ccab08 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main

import (
	"crypto/sha1"
	"encoding/hex"
	"fmt"
	"io"
	"math/rand"
	"time"
)

const ihLength = 20

func genInfoHash() string {
	random := rand.New(rand.NewSource(time.Now().UnixNano()))
	hash := sha1.New()
	io.WriteString(hash, time.Now().String())
	io.WriteString(hash, string(random.Int()))
	ih := hash.Sum(nil)
	return string(ih)
}

func genNeighbour(first, second string) string {
	s := second[:10] + first[10:]
	return s
}

func decodeInfoHash(in string) (b string, err error) {
	var h []byte
	h, err = hex.DecodeString(in)
	if len(h) != ihLength {
		return "", fmt.Errorf("Decoded infoHash is incorrect length, got %d", len(h))
	}
	return string(h), err
}

/*
func isValidInfoHash(id string) bool {
	ih, err := hex.DecodeString(id)
	if err != nil {
		return false
	}
	return len(ih) == ihLength
}

func (ih infoHash) xor(other infoHash) (ret []byte) {
	if len(ih) != len(other) {
		return []byte("")
	}
	ret = make([]byte, ihLength)
	for i := 0; i < ihLength; i++ {
		ret[i] = ih[i] ^ other[i]
	}
	return
}

// Effectively the "distance"
// XORed then number of common bits
func (ih infoHash) prefixLen(other infoHash) (ret int) {
	//fmt.Printf("ih = %s, other = %s\n", ih.asHex(), other.asHex())
	id1, id2 := []byte(ih), []byte(other)

	xor := make([]byte, ihLength)
	i := 0
	for ; i < ihLength; i++ {
		xor[i] = id1[i] ^ id2[i]
	}

	for i := 0; i < ihLength; i++ {
		for j := 0; j < 8; j++ {
			if (xor[i]>>uint8(7-j))&0x1 != 0 {
				return i*8 + j
			}
		}
	}
	return ihLength*8 - 1
}

// Comparitor for iterable
func (ih infoHash) Less(other interface{}) bool {
	for i := 0; i < ihLength; i++ {
		if ih[i] != other.(infoHash)[i] {
			return ih[i] < other.(infoHash)[i]
		}
	}
	return false
}
*/