]> Sergey Matveev's repositories - btrtrc.git/blob - types/infohash/infohash.go
Add BitTorrent v2 fields, consts and reference torrents
[btrtrc.git] / types / infohash / infohash.go
1 package infohash
2
3 import (
4         "crypto/sha1"
5         "crypto/sha256"
6         "encoding"
7         "encoding/hex"
8         "fmt"
9 )
10
11 const Size = 20
12
13 // 20-byte SHA1 hash used for info and pieces.
14 type T [Size]byte
15
16 var _ fmt.Formatter = (*T)(nil)
17
18 func (t T) Format(f fmt.State, c rune) {
19         // TODO: I can't figure out a nice way to just override the 'x' rune, since it's meaningless
20         // with the "default" 'v', or .String() already returning the hex.
21         f.Write([]byte(t.HexString()))
22 }
23
24 func (t T) Bytes() []byte {
25         return t[:]
26 }
27
28 func (t T) AsString() string {
29         return string(t[:])
30 }
31
32 func (t T) String() string {
33         return t.HexString()
34 }
35
36 func (t T) HexString() string {
37         return fmt.Sprintf("%x", t[:])
38 }
39
40 func (t *T) FromHexString(s string) (err error) {
41         if len(s) != 2*Size {
42                 err = fmt.Errorf("hash hex string has bad length: %d", len(s))
43                 return
44         }
45         n, err := hex.Decode(t[:], []byte(s))
46         if err != nil {
47                 return
48         }
49         if n != Size {
50                 panic(n)
51         }
52         return
53 }
54
55 var (
56         _ encoding.TextUnmarshaler = (*T)(nil)
57         _ encoding.TextMarshaler   = T{}
58 )
59
60 func (t *T) UnmarshalText(b []byte) error {
61         return t.FromHexString(string(b))
62 }
63
64 func (t T) MarshalText() (text []byte, err error) {
65         return []byte(t.HexString()), nil
66 }
67
68 func FromHexString(s string) (h T) {
69         err := h.FromHexString(s)
70         if err != nil {
71                 panic(err)
72         }
73         return
74 }
75
76 func HashBytes(b []byte) (ret T) {
77         hasher := sha1.New()
78         hasher.Write(b)
79         copy(ret[:], hasher.Sum(nil))
80         return
81 }
82
83 func HashBytesV2(b []byte) (ret T) {
84         hasher := sha256.New()
85         hasher.Write(b)
86         copy(ret[:], hasher.Sum(nil))
87         return
88 }