github.com/ledgerwatch/erigon-lib@v1.0.0/common/hexutility/json.go (about) 1 /* 2 Copyright 2021 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/json" 21 "errors" 22 "reflect" 23 ) 24 25 // UnmarshalFixedJSON decodes the input as a string with 0x prefix. The length of out 26 // determines the required input length. This function is commonly used to implement the 27 // UnmarshalJSON method for fixed-size types. 28 func UnmarshalFixedJSON(typ reflect.Type, input, out []byte) error { 29 if !isString(input) { 30 return &json.UnmarshalTypeError{Value: "non-string", Type: typ} 31 } 32 return wrapTypeError(UnmarshalFixedText(typ.String(), input[1:len(input)-1], out), typ) 33 } 34 35 func isString(input []byte) bool { 36 return len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' 37 } 38 39 func wrapTypeError(err error, typ reflect.Type) error { 40 var dec *decError 41 if errors.As(err, &dec) { 42 return &json.UnmarshalTypeError{Value: err.Error(), Type: typ} 43 } 44 return err 45 }