]> Sergey Matveev's repositories - btrtrc.git/blob - metainfo/hash.go
Panic if NewHashFromHex gets a bad string
[btrtrc.git] / metainfo / hash.go
1 package metainfo
2
3 import (
4         "crypto/sha1"
5         "encoding/hex"
6         "fmt"
7 )
8
9 // 20-byte SHA1 hash used for info and pieces.
10 type Hash [20]byte
11
12 func (h Hash) Bytes() []byte {
13         return h[:]
14 }
15
16 func (h Hash) AsString() string {
17         return string(h[:])
18 }
19
20 func (h Hash) HexString() string {
21         return fmt.Sprintf("%x", h[:])
22 }
23
24 func (h *Hash) FromHexString(s string) (err error) {
25         if len(s) != 40 {
26                 err = fmt.Errorf("hash hex string has bad length: %d", len(s))
27                 return
28         }
29         n, err := hex.Decode(h[:], []byte(s))
30         if err != nil {
31                 return
32         }
33         if n != 20 {
34                 panic(n)
35         }
36         return
37 }
38
39 func NewHashFromHex(s string) (h Hash) {
40         err := h.FromHexString(s)
41         if err != nil {
42                 panic(err)
43         }
44         return
45 }
46
47 func HashBytes(b []byte) (ret Hash) {
48         hasher := sha1.New()
49         hasher.Write(b)
50         copy(ret[:], hasher.Sum(nil))
51         return
52 }