github.com/intfoundation/intchain@v0.0.0-20220727031208-4316ad31ca73/accounts/abi/error.go (about) 1 // Copyright 2016 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum 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 go-ethereum 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 go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package abi 18 19 import ( 20 "errors" 21 "fmt" 22 "reflect" 23 ) 24 25 var ( 26 errBadBool = errors.New("abi: improperly encoded boolean value") 27 ) 28 29 // formatSliceString formats the reflection kind with the given slice size 30 // and returns a formatted string representation. 31 func formatSliceString(kind reflect.Kind, sliceSize int) string { 32 if sliceSize == -1 { 33 return fmt.Sprintf("[]%v", kind) 34 } 35 return fmt.Sprintf("[%d]%v", sliceSize, kind) 36 } 37 38 // sliceTypeCheck checks that the given slice can by assigned to the reflection 39 // type in t. 40 func sliceTypeCheck(t Type, val reflect.Value) error { 41 if val.Kind() != reflect.Slice && val.Kind() != reflect.Array { 42 return typeErr(formatSliceString(t.Kind, t.Size), val.Type()) 43 } 44 45 if t.T == ArrayTy && val.Len() != t.Size { 46 return typeErr(formatSliceString(t.Elem.Kind, t.Size), formatSliceString(val.Type().Elem().Kind(), val.Len())) 47 } 48 49 if t.Elem.T == SliceTy { 50 if val.Len() > 0 { 51 return sliceTypeCheck(*t.Elem, val.Index(0)) 52 } 53 } else if t.Elem.T == ArrayTy { 54 return sliceTypeCheck(*t.Elem, val.Index(0)) 55 } 56 57 if elemKind := val.Type().Elem().Kind(); elemKind != t.Elem.Kind { 58 return typeErr(formatSliceString(t.Elem.Kind, t.Size), val.Type()) 59 } 60 return nil 61 } 62 63 // typeCheck checks that the given reflection value can be assigned to the reflection 64 // type in t. 65 func typeCheck(t Type, value reflect.Value) error { 66 if t.T == SliceTy || t.T == ArrayTy { 67 return sliceTypeCheck(t, value) 68 } 69 70 // Check base type validity. Element types will be checked later on. 71 if t.Kind != value.Kind() { 72 return typeErr(t.Kind, value.Kind()) 73 } else if t.T == FixedBytesTy && t.Size != value.Len() { 74 return typeErr(t.Type, value.Type()) 75 } else { 76 return nil 77 } 78 79 } 80 81 // typeErr returns a formatted type casting error. 82 func typeErr(expected, got interface{}) error { 83 return fmt.Errorf("abi: cannot use %v as type %v as argument", got, expected) 84 }