packing.go 2.1 KB

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