bytes.go 5.4 KB

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