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