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