bytes.go 5.5 KB

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