bytes.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // Copyright 2014 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 common contains various helper functions.
  17. package common
  18. import (
  19. "bytes"
  20. "encoding/binary"
  21. "encoding/hex"
  22. "fmt"
  23. "math/big"
  24. "strings"
  25. )
  26. func ToHex(b []byte) string {
  27. hex := Bytes2Hex(b)
  28. // Prefer output of "0x0" instead of "0x"
  29. if len(hex) == 0 {
  30. hex = "0"
  31. }
  32. return "0x" + hex
  33. }
  34. func FromHex(s string) []byte {
  35. if len(s) > 1 {
  36. if s[0:2] == "0x" || s[0:2] == "0X" {
  37. s = s[2:]
  38. }
  39. if len(s)%2 == 1 {
  40. s = "0" + s
  41. }
  42. return Hex2Bytes(s)
  43. }
  44. return nil
  45. }
  46. // Number to bytes
  47. //
  48. // Returns the number in bytes with the specified base
  49. func NumberToBytes(num interface{}, bits int) []byte {
  50. buf := new(bytes.Buffer)
  51. err := binary.Write(buf, binary.BigEndian, num)
  52. if err != nil {
  53. fmt.Println("NumberToBytes failed:", err)
  54. }
  55. return buf.Bytes()[buf.Len()-(bits/8):]
  56. }
  57. // Bytes to number
  58. //
  59. // Attempts to cast a byte slice to a unsigned integer
  60. func BytesToNumber(b []byte) uint64 {
  61. var number uint64
  62. // Make sure the buffer is 64bits
  63. data := make([]byte, 8)
  64. data = append(data[:len(b)], b...)
  65. buf := bytes.NewReader(data)
  66. err := binary.Read(buf, binary.BigEndian, &number)
  67. if err != nil {
  68. fmt.Println("BytesToNumber failed:", err)
  69. }
  70. return number
  71. }
  72. // Read variable int
  73. //
  74. // Read a variable length number in big endian byte order
  75. func ReadVarInt(buff []byte) (ret uint64) {
  76. switch l := len(buff); {
  77. case l > 4:
  78. d := LeftPadBytes(buff, 8)
  79. binary.Read(bytes.NewReader(d), binary.BigEndian, &ret)
  80. case l > 2:
  81. var num uint32
  82. d := LeftPadBytes(buff, 4)
  83. binary.Read(bytes.NewReader(d), binary.BigEndian, &num)
  84. ret = uint64(num)
  85. case l > 1:
  86. var num uint16
  87. d := LeftPadBytes(buff, 2)
  88. binary.Read(bytes.NewReader(d), binary.BigEndian, &num)
  89. ret = uint64(num)
  90. default:
  91. var num uint8
  92. binary.Read(bytes.NewReader(buff), binary.BigEndian, &num)
  93. ret = uint64(num)
  94. }
  95. return
  96. }
  97. // Copy bytes
  98. //
  99. // Returns an exact copy of the provided bytes
  100. func CopyBytes(b []byte) (copiedBytes []byte) {
  101. copiedBytes = make([]byte, len(b))
  102. copy(copiedBytes, b)
  103. return
  104. }
  105. func HasHexPrefix(str string) bool {
  106. l := len(str)
  107. return l >= 2 && str[0:2] == "0x"
  108. }
  109. func IsHex(str string) bool {
  110. l := len(str)
  111. return l >= 4 && l%2 == 0 && str[0:2] == "0x"
  112. }
  113. func Bytes2Hex(d []byte) string {
  114. return hex.EncodeToString(d)
  115. }
  116. func Hex2Bytes(str string) []byte {
  117. h, _ := hex.DecodeString(str)
  118. return h
  119. }
  120. func Hex2BytesFixed(str string, flen int) []byte {
  121. h, _ := hex.DecodeString(str)
  122. if len(h) == flen {
  123. return h
  124. } else {
  125. if len(h) > flen {
  126. return h[len(h)-flen:]
  127. } else {
  128. hh := make([]byte, flen)
  129. copy(hh[flen-len(h):flen], h[:])
  130. return hh
  131. }
  132. }
  133. }
  134. func StringToByteFunc(str string, cb func(str string) []byte) (ret []byte) {
  135. if len(str) > 1 && str[0:2] == "0x" && !strings.Contains(str, "\n") {
  136. ret = Hex2Bytes(str[2:])
  137. } else {
  138. ret = cb(str)
  139. }
  140. return
  141. }
  142. func FormatData(data string) []byte {
  143. if len(data) == 0 {
  144. return nil
  145. }
  146. // Simple stupid
  147. d := new(big.Int)
  148. if data[0:1] == "\"" && data[len(data)-1:] == "\"" {
  149. return RightPadBytes([]byte(data[1:len(data)-1]), 32)
  150. } else if len(data) > 1 && data[:2] == "0x" {
  151. d.SetBytes(Hex2Bytes(data[2:]))
  152. } else {
  153. d.SetString(data, 0)
  154. }
  155. return BigToBytes(d, 256)
  156. }
  157. func ParseData(data ...interface{}) (ret []byte) {
  158. for _, item := range data {
  159. switch t := item.(type) {
  160. case string:
  161. var str []byte
  162. if IsHex(t) {
  163. str = Hex2Bytes(t[2:])
  164. } else {
  165. str = []byte(t)
  166. }
  167. ret = append(ret, RightPadBytes(str, 32)...)
  168. case []byte:
  169. ret = append(ret, LeftPadBytes(t, 32)...)
  170. }
  171. }
  172. return
  173. }
  174. func RightPadBytes(slice []byte, l int) []byte {
  175. if l < len(slice) {
  176. return slice
  177. }
  178. padded := make([]byte, l)
  179. copy(padded[0:len(slice)], slice)
  180. return padded
  181. }
  182. func LeftPadBytes(slice []byte, l int) []byte {
  183. if l < len(slice) {
  184. return slice
  185. }
  186. padded := make([]byte, l)
  187. copy(padded[l-len(slice):], slice)
  188. return padded
  189. }
  190. func LeftPadString(str string, l int) string {
  191. if l < len(str) {
  192. return str
  193. }
  194. zeros := Bytes2Hex(make([]byte, (l-len(str))/2))
  195. return zeros + str
  196. }
  197. func RightPadString(str string, l int) string {
  198. if l < len(str) {
  199. return str
  200. }
  201. zeros := Bytes2Hex(make([]byte, (l-len(str))/2))
  202. return str + zeros
  203. }
  204. func ToAddress(slice []byte) (addr []byte) {
  205. if len(slice) < 20 {
  206. addr = LeftPadBytes(slice, 20)
  207. } else if len(slice) > 20 {
  208. addr = slice[len(slice)-20:]
  209. } else {
  210. addr = slice
  211. }
  212. addr = CopyBytes(addr)
  213. return
  214. }
  215. func ByteSliceToInterface(slice [][]byte) (ret []interface{}) {
  216. for _, i := range slice {
  217. ret = append(ret, i)
  218. }
  219. return
  220. }