github.com/ledgerwatch/erigon-lib@v1.0.0/common/hexutility/text.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/hex" 21 "fmt" 22 ) 23 24 const ( 25 badNibble = ^uint64(0) 26 ) 27 28 // UnmarshalFixedText decodes the input as a string with 0x prefix. The length of out 29 // determines the required input length. This function is commonly used to implement the 30 // UnmarshalText method for fixed-size types. 31 func UnmarshalFixedText(typeName string, input, out []byte) error { 32 raw, err := checkText(input, true) 33 if err != nil { 34 return err 35 } 36 if len(raw)/2 != len(out) { 37 return fmt.Errorf("hex string has length %d, want %d for %s", len(raw), len(out)*2, typeName) 38 } 39 // Pre-verify syntax before modifying out. 40 for _, b := range raw { 41 if decodeNibble(b) == badNibble { 42 return ErrSyntax 43 } 44 } 45 _, err = hex.Decode(out, raw) 46 return err 47 } 48 49 func checkText(input []byte, wantPrefix bool) ([]byte, error) { 50 if len(input) == 0 { 51 return nil, nil // empty strings are allowed 52 } 53 if bytesHave0xPrefix(input) { 54 input = input[2:] 55 } else if wantPrefix { 56 return nil, ErrMissingPrefix 57 } 58 if len(input)%2 != 0 { 59 return nil, ErrOddLength 60 } 61 return input, nil 62 } 63 64 func bytesHave0xPrefix(input []byte) bool { 65 return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X') 66 } 67 68 func decodeNibble(in byte) uint64 { 69 switch { 70 case in >= '0' && in <= '9': 71 return uint64(in - '0') 72 case in >= 'A' && in <= 'F': 73 return uint64(in - 'A' + 10) 74 case in >= 'a' && in <= 'f': 75 return uint64(in - 'a' + 10) 76 default: 77 return badNibble 78 } 79 }