hermez-node/common/float40_test.go
common/float40_test.goRaw
1package common
2
3import (
4 "math/big"
5 "testing"
6
7 "github.com/stretchr/testify/assert"
8 "github.com/stretchr/testify/require"
9)
10
11func TestConversionsFloat40(t *testing.T) {
12 testVector := map[Float40]string{
13 6*0x800000000 + 123: "123000000",
14 2*0x800000000 + 4545: "454500",
15 30*0x800000000 + 10235: "10235000000000000000000000000000000",
16 0x000000000: "0",
17 0x800000000: "0",
18 0x0001: "1",
19 0x0401: "1025",
20 0x800000000 + 1: "10",
21 0xFFFFFFFFFF: "343597383670000000000000000000000000000000",
22 }
23
24 for test := range testVector {
25 fix, err := test.BigInt()
26 require.NoError(t, err)
27 assert.Equal(t, fix.String(), testVector[test])
28
29 bi, ok := new(big.Int).SetString(testVector[test], 10)
30 require.True(t, ok)
31
32 fl, err := NewFloat40(bi)
33 assert.NoError(t, err)
34
35 fx2, err := fl.BigInt()
36 require.NoError(t, err)
37 assert.Equal(t, fx2.String(), testVector[test])
38 }
39}
40
41func TestExpectError(t *testing.T) {
42 testVector := map[string]error{
43 "9922334455000000000000000000000000000000": nil,
44 "9922334455000000000000000000000000000001": ErrFloat40NotEnoughPrecission,
45 "9922334454999999999999999999999999999999": ErrFloat40NotEnoughPrecission,
46 "42949672950000000000000000000000000000000": nil,
47 "99223344556573838487575": ErrFloat40NotEnoughPrecission,
48 "992233445500000000000000000000000000000000": ErrFloat40E31,
49 "343597383670000000000000000000000000000000": nil,
50 "343597383680000000000000000000000000000000": ErrFloat40NotEnoughPrecission,
51 "343597383690000000000000000000000000000000": ErrFloat40NotEnoughPrecission,
52 "343597383700000000000000000000000000000000": ErrFloat40E31,
53 }
54 for test := range testVector {
55 bi, ok := new(big.Int).SetString(test, 10)
56 require.True(t, ok)
57 _, err := NewFloat40(bi)
58 assert.Equal(t, testVector[test], err)
59 }
60}
61
62func BenchmarkFloat40(b *testing.B) {
63 newBigInt := func(s string) *big.Int {
64 bigInt, ok := new(big.Int).SetString(s, 10)
65 if !ok {
66 panic("Can not convert string to *big.Int")
67 }
68 return bigInt
69 }
70 type pair struct {
71 Float40 Float40
72 BigInt *big.Int
73 }
74 testVector := []pair{
75 {6*0x800000000 + 123, newBigInt("123000000")},
76 {2*0x800000000 + 4545, newBigInt("454500")},
77 {30*0x800000000 + 10235, newBigInt("10235000000000000000000000000000000")},
78 {0x000000000, newBigInt("0")},
79 {0x800000000, newBigInt("0")},
80 {0x0001, newBigInt("1")},
81 {0x0401, newBigInt("1025")},
82 {0x800000000 + 1, newBigInt("10")},
83 {0xFFFFFFFFFF, newBigInt("343597383670000000000000000000000000000000")},
84 }
85 b.Run("NewFloat40()", func(b *testing.B) {
86 for i := 0; i < b.N; i++ {
87 _, _ = NewFloat40(testVector[i%len(testVector)].BigInt)
88 }
89 })
90 b.Run("Float40.BigInt()", func(b *testing.B) {
91 for i := 0; i < b.N; i++ {
92 _, _ = testVector[i%len(testVector)].Float40.BigInt()
93 }
94 })
95}