common.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package ethutil
  2. import (
  3. "fmt"
  4. "math/big"
  5. "runtime"
  6. "time"
  7. )
  8. func IsWindows() bool {
  9. return runtime.GOOS == "windows"
  10. }
  11. func WindonizePath(path string) string {
  12. if string(path[0]) == "/" && IsWindows() {
  13. path = path[1:]
  14. }
  15. return path
  16. }
  17. // The different number of units
  18. var (
  19. Douglas = BigPow(10, 42)
  20. Einstein = BigPow(10, 21)
  21. Ether = BigPow(10, 18)
  22. Finney = BigPow(10, 15)
  23. Szabo = BigPow(10, 12)
  24. Shannon = BigPow(10, 9)
  25. Babbage = BigPow(10, 6)
  26. Ada = BigPow(10, 3)
  27. Wei = big.NewInt(1)
  28. )
  29. //
  30. // Currency to string
  31. // Returns a string representing a human readable format
  32. func CurrencyToString(num *big.Int) string {
  33. var (
  34. fin *big.Int = num
  35. denom string = "Wei"
  36. )
  37. switch {
  38. case num.Cmp(Douglas) >= 0:
  39. fin = new(big.Int).Div(num, Douglas)
  40. denom = "Douglas"
  41. case num.Cmp(Einstein) >= 0:
  42. fin = new(big.Int).Div(num, Einstein)
  43. denom = "Einstein"
  44. case num.Cmp(Ether) >= 0:
  45. fin = new(big.Int).Div(num, Ether)
  46. denom = "Ether"
  47. case num.Cmp(Finney) >= 0:
  48. fin = new(big.Int).Div(num, Finney)
  49. denom = "Finney"
  50. case num.Cmp(Szabo) >= 0:
  51. fin = new(big.Int).Div(num, Szabo)
  52. denom = "Szabo"
  53. case num.Cmp(Shannon) >= 0:
  54. fin = new(big.Int).Div(num, Shannon)
  55. denom = "Shannon"
  56. case num.Cmp(Babbage) >= 0:
  57. fin = new(big.Int).Div(num, Babbage)
  58. denom = "Babbage"
  59. case num.Cmp(Ada) >= 0:
  60. fin = new(big.Int).Div(num, Ada)
  61. denom = "Ada"
  62. }
  63. // TODO add comment clarifying expected behavior
  64. if len(fin.String()) > 5 {
  65. return fmt.Sprintf("%sE%d %s", fin.String()[0:5], len(fin.String())-5, denom)
  66. }
  67. return fmt.Sprintf("%v %s", fin, denom)
  68. }
  69. // Common big integers often used
  70. var (
  71. Big1 = big.NewInt(1)
  72. Big2 = big.NewInt(2)
  73. Big3 = big.NewInt(3)
  74. Big0 = big.NewInt(0)
  75. BigTrue = Big1
  76. BigFalse = Big0
  77. Big32 = big.NewInt(32)
  78. Big256 = big.NewInt(0xff)
  79. Big257 = big.NewInt(257)
  80. )
  81. func Bench(pre string, cb func()) {
  82. start := time.Now()
  83. cb()
  84. fmt.Println(pre, ": took:", time.Since(start))
  85. }