github.com/status-im/status-go@v1.1.0/eth-node/types/hex.go (about) 1 // Code extracted from vendor/github.com/ethereum/go-ethereum/common/hexutil/hexutil.go 2 3 package types 4 5 import ( 6 "encoding/hex" 7 "fmt" 8 "reflect" 9 ) 10 11 var ( 12 bytesT = reflect.TypeOf(HexBytes(nil)) 13 ) 14 15 // HexBytes marshals/unmarshals as a JSON string with 0x prefix. 16 // The empty slice marshals as "0x". 17 type HexBytes []byte 18 19 func (b HexBytes) Bytes() []byte { 20 result := make([]byte, len(b)*2+2) 21 copy(result, `0x`) 22 hex.Encode(result[2:], b) 23 return result 24 } 25 26 // MarshalText implements encoding.TextMarshaler 27 func (b HexBytes) MarshalText() ([]byte, error) { 28 return b.Bytes(), nil 29 } 30 31 // UnmarshalJSON implements json.Unmarshaler. 32 func (b *HexBytes) UnmarshalJSON(input []byte) error { 33 if !isString(input) { 34 return errNonString(bytesT) 35 } 36 return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), bytesT) 37 } 38 39 // UnmarshalFixedUnprefixedText decodes the input as a string with optional 0x prefix. The 40 // length of out determines the required input length. This function is commonly used to 41 // implement the UnmarshalText method for fixed-size types. 42 func UnmarshalFixedUnprefixedText(typname string, input, out []byte) error { 43 raw, err := checkText(input, false) 44 if err != nil { 45 return err 46 } 47 if len(raw)/2 != len(out) { 48 return fmt.Errorf("hex string has length %d, want %d for %s", len(raw), len(out)*2, typname) 49 } 50 // Pre-verify syntax before modifying out. 51 for _, b := range raw { 52 if decodeNibble(b) == badNibble { 53 return ErrSyntax 54 } 55 } 56 _, err = hex.Decode(out, raw) 57 return err 58 }