github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/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 "fmt" 21 "reflect" 22 ) 23 24 // formatSliceString formats the reflection kind with the given slice size 25 // and returns a formatted string representation. 26 func formatSliceString(kind reflect.Kind, sliceSize int) string { 27 if sliceSize == -1 { 28 return fmt.Sprintf("[]%v", kind) 29 } 30 return fmt.Sprintf("[%d]%v", sliceSize, kind) 31 } 32 33 // sliceTypeCheck checks that the given slice can by assigned to the reflection 34 // type in t. 35 func sliceTypeCheck(t Type, val reflect.Value) error { 36 if val.Kind() != reflect.Slice && val.Kind() != reflect.Array { 37 return typeErr(formatSliceString(t.Kind, t.SliceSize), val.Type()) 38 } 39 if t.IsArray && val.Len() != t.SliceSize { 40 return typeErr(formatSliceString(t.Elem.Kind, t.SliceSize), formatSliceString(val.Type().Elem().Kind(), val.Len())) 41 } 42 43 if t.Elem.IsSlice { 44 if val.Len() > 0 { 45 return sliceTypeCheck(*t.Elem, val.Index(0)) 46 } 47 } else if t.Elem.IsArray { 48 return sliceTypeCheck(*t.Elem, val.Index(0)) 49 } 50 51 if elemKind := val.Type().Elem().Kind(); elemKind != t.Elem.Kind { 52 return typeErr(formatSliceString(t.Elem.Kind, t.SliceSize), val.Type()) 53 } 54 return nil 55 } 56 57 // typeCheck checks that the given reflection value can be assigned to the reflection 58 // type in t. 59 func typeCheck(t Type, value reflect.Value) error { 60 if t.IsSlice || t.IsArray { 61 return sliceTypeCheck(t, value) 62 } 63 64 // Check base type validity. Element types will be checked later on. 65 if t.Kind != value.Kind() { 66 return typeErr(t.Kind, value.Kind()) 67 } 68 return nil 69 } 70 71 // typeErr returns a formatted type casting error. 72 func typeErr(expected, got interface{}) error { 73 return fmt.Errorf("abi: cannot use %v as type %v as argument", got, expected) 74 }