github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/accounts/abi/packing.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 "math/big" 21 "reflect" 22 23 "github.com/ethereumproject/go-ethereum/common" 24 ) 25 26 // packBytesSlice packs the given bytes as [L, V] as the canonical representation 27 // bytes slice 28 func packBytesSlice(bytes []byte, l int) []byte { 29 len := packNum(reflect.ValueOf(l)) 30 return append(len, common.RightPadBytes(bytes, (l+31)/32*32)...) 31 } 32 33 // packElement packs the given reflect value according to the abi specification in 34 // t. 35 func packElement(t Type, reflectValue reflect.Value) []byte { 36 switch t.T { 37 case IntTy, UintTy: 38 return packNum(reflectValue) 39 case StringTy: 40 return packBytesSlice([]byte(reflectValue.String()), reflectValue.Len()) 41 case AddressTy: 42 if reflectValue.Kind() == reflect.Array { 43 reflectValue = mustArrayToByteSlice(reflectValue) 44 } 45 46 return common.LeftPadBytes(reflectValue.Bytes(), 32) 47 case BoolTy: 48 if reflectValue.Bool() { 49 return common.LeftPadBytes(common.Big1.Bytes(), 32) 50 } else { 51 return common.LeftPadBytes(new(big.Int).Bytes(), 32) 52 } 53 case BytesTy: 54 if reflectValue.Kind() == reflect.Array { 55 reflectValue = mustArrayToByteSlice(reflectValue) 56 } 57 return packBytesSlice(reflectValue.Bytes(), reflectValue.Len()) 58 case FixedBytesTy: 59 if reflectValue.Kind() == reflect.Array { 60 reflectValue = mustArrayToByteSlice(reflectValue) 61 } 62 63 return common.RightPadBytes(reflectValue.Bytes(), 32) 64 } 65 panic("abi: fatal error") 66 }