]> Sergey Matveev's repositories - btrtrc.git/blob - metainfo/hash.go
Fixes for wasm
[btrtrc.git] / metainfo / hash.go
1 package metainfo
2
3 import (
4         "crypto/sha1"
5         "encoding"
6         "encoding/hex"
7         "fmt"
8 )
9
10 const HashSize = 20
11
12 // 20-byte SHA1 hash used for info and pieces.
13 type Hash [HashSize]byte
14
15 var _ fmt.Formatter = (*Hash)(nil)
16
17 func (h Hash) 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(h.HexString()))
21 }
22
23 func (h Hash) Bytes() []byte {
24         return h[:]
25 }
26
27 func (h Hash) AsString() string {
28         return string(h[:])
29 }
30
31 func (h Hash) String() string {
32         return h.HexString()
33 }
34
35 func (h Hash) HexString() string {
36         return fmt.Sprintf("%x", h[:])
37 }
38
39 func (h *Hash) FromHexString(s string) (err error) {
40         if len(s) != 2*HashSize {
41                 err = fmt.Errorf("hash hex string has bad length: %d", len(s))
42                 return
43         }
44         n, err := hex.Decode(h[:], []byte(s))
45         if err != nil {
46                 return
47         }
48         if n != HashSize {
49                 panic(n)
50         }
51         return
52 }
53
54 var (
55         _ encoding.TextUnmarshaler = (*Hash)(nil)
56         _ encoding.TextMarshaler   = Hash{}
57 )
58
59 func (h *Hash) UnmarshalText(b []byte) error {
60         return h.FromHexString(string(b))
61 }
62 func (h Hash) MarshalText() (text []byte, err error) {
63         return []byte(h.HexString()), nil
64 }
65
66 func NewHashFromHex(s string) (h Hash) {
67         err := h.FromHexString(s)
68         if err != nil {
69                 panic(err)
70         }
71         return
72 }
73
74 func HashBytes(b []byte) (ret Hash) {
75         hasher := sha1.New()
76         hasher.Write(b)
77         copy(ret[:], hasher.Sum(nil))
78         return
79 }