bytes.go 4.7 KB

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