github.com/ledgerwatch/erigon-lib@v1.0.0/common/hexutility/bytes.go (about) 1 /* 2 Copyright 2023 The Erigon contributors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package hexutility 18 19 import ( 20 "encoding/hex" 21 "encoding/json" 22 "reflect" 23 ) 24 25 var bytesT = reflect.TypeOf(Bytes(nil)) 26 27 // Bytes marshals/unmarshals as a JSON string with 0x prefix. 28 // The empty slice marshals as "0x". 29 type Bytes []byte 30 31 const hexPrefix = `0x` 32 33 // MarshalText implements encoding.TextMarshaler 34 func (b Bytes) MarshalText() ([]byte, error) { 35 result := make([]byte, len(b)*2+2) 36 copy(result, hexPrefix) 37 hex.Encode(result[2:], b) 38 return result, nil 39 } 40 41 // UnmarshalJSON implements json.Unmarshaler. 42 func (b *Bytes) UnmarshalJSON(input []byte) error { 43 if !isString(input) { 44 return &json.UnmarshalTypeError{Value: "non-string", Type: bytesT} 45 } 46 return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), bytesT) 47 } 48 49 // UnmarshalText implements encoding.TextUnmarshaler. 50 func (b *Bytes) UnmarshalText(input []byte) error { 51 raw, err := checkText(input, true) 52 if err != nil { 53 return err 54 } 55 dec := make([]byte, len(raw)/2) 56 _, err = hex.Decode(dec, raw) 57 if err == nil { 58 *b = dec 59 } 60 return err 61 } 62 63 // String returns the hex encoding of b. 64 func (b Bytes) String() string { 65 return Encode(b) 66 }