OSDN Git Service

Merge pull request #41 from Bytom/dev
[bytom/vapor.git] / common / types_template.go
1 // +build none
2 //sed -e 's/_N_/Hash/g' -e 's/_S_/32/g' -e '1d' types_template.go | gofmt -w hash.go
3
4 package common
5
6 import "math/big"
7
8 type _N_ [_S_]byte
9
10 func BytesTo_N_(b []byte) _N_ {
11         var h _N_
12         h.SetBytes(b)
13         return h
14 }
15 func StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) }
16 func BigTo_N_(b *big.Int) _N_  { return BytesTo_N_(b.Bytes()) }
17 func HexTo_N_(s string) _N_    { return BytesTo_N_(FromHex(s)) }
18
19 // Don't use the default 'String' method in case we want to overwrite
20
21 // Get the string representation of the underlying hash
22 func (h _N_) Str() string   { return string(h[:]) }
23 func (h _N_) Bytes() []byte { return h[:] }
24 func (h _N_) Big() *big.Int { return Bytes2Big(h[:]) }
25 func (h _N_) Hex() string   { return "0x" + Bytes2Hex(h[:]) }
26
27 // Sets the hash to the value of b. If b is larger than len(h) it will panic
28 func (h *_N_) SetBytes(b []byte) {
29         // Use the right most bytes
30         if len(b) > len(h) {
31                 b = b[len(b)-_S_:]
32         }
33
34         // Reverse the loop
35         for i := len(b) - 1; i >= 0; i-- {
36                 h[_S_-len(b)+i] = b[i]
37         }
38 }
39
40 // Set string `s` to h. If s is larger than len(h) it will panic
41 func (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) }
42
43 // Sets h to other
44 func (h *_N_) Set(other _N_) {
45         for i, v := range other {
46                 h[i] = v
47         }
48 }