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