github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/common/types_template.go (about) 1 // This file is part of the go-sberex library. The go-sberex library is 2 // free software: you can redistribute it and/or modify it under the terms 3 // of the GNU Lesser General Public License as published by the Free 4 // Software Foundation, either version 3 of the License, or (at your option) 5 // any later version. 6 // 7 // The go-sberex library is distributed in the hope that it will be useful, 8 // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 10 // General Public License <http://www.gnu.org/licenses/> for more details. 11 12 // +build none 13 //sed -e 's/_N_/Hash/g' -e 's/_S_/32/g' -e '1d' types_template.go | gofmt -w hash.go 14 15 package common 16 17 import "math/big" 18 19 type _N_ [_S_]byte 20 21 func BytesTo_N_(b []byte) _N_ { 22 var h _N_ 23 h.SetBytes(b) 24 return h 25 } 26 func StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) } 27 func BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) } 28 func HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) } 29 30 // Don't use the default 'String' method in case we want to overwrite 31 32 // Get the string representation of the underlying hash 33 func (h _N_) Str() string { return string(h[:]) } 34 func (h _N_) Bytes() []byte { return h[:] } 35 func (h _N_) Big() *big.Int { return new(big.Int).SetBytes(h[:]) } 36 func (h _N_) Hex() string { return "0x" + Bytes2Hex(h[:]) } 37 38 // Sets the hash to the value of b. If b is larger than len(h) it will panic 39 func (h *_N_) SetBytes(b []byte) { 40 // Use the right most bytes 41 if len(b) > len(h) { 42 b = b[len(b)-_S_:] 43 } 44 45 // Reverse the loop 46 for i := len(b) - 1; i >= 0; i-- { 47 h[_S_-len(b)+i] = b[i] 48 } 49 } 50 51 // Set string `s` to h. If s is larger than len(h) it will panic 52 func (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) } 53 54 // Sets h to other 55 func (h *_N_) Set(other _N_) { 56 for i, v := range other { 57 h[i] = v 58 } 59 }