| 1 | package ff |
| 2 | |
| 3 | import ( |
| 4 | "math/big" |
| 5 | "reflect" |
| 6 | "testing" |
| 7 | ) |
| 8 | |
| 9 | func Test_mul128(t *testing.T) { |
| 10 | type args struct { |
| 11 | x [2]uint64 |
| 12 | y [2]uint64 |
| 13 | } |
| 14 | tests := []struct { |
| 15 | name string |
| 16 | args args |
| 17 | wantZ [4]uint64 |
| 18 | }{ |
| 19 | {"2*1", args{[2]uint64{2, 0}, [2]uint64{1, 0}}, [4]uint64{2, 0, 0, 0}}, |
| 20 | {"(2^128 - 1)(2^128 - 1)", args{[2]uint64{0xffffffffffffffff, 0xffffffffffffffff}, [2]uint64{0xffffffffffffffff, 0xffffffffffffffff}}, [4]uint64{0x1, 0, 0xfffffffffffffffe, 0xffffffffffffffff}}, |
| 21 | } |
| 22 | for _, tt := range tests { |
| 23 | t.Run(tt.name, func(t *testing.T) { |
| 24 | if gotZ := mul128(tt.args.x, tt.args.y); !reflect.DeepEqual(gotZ, tt.wantZ) { |
| 25 | t.Errorf("mul128() = %v, want %v", gotZ, tt.wantZ) |
| 26 | } |
| 27 | }) |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | func Test_mul128_random(t *testing.T) { |
| 32 | for i := 0; i < 100; i++ { |
| 33 | x := [2]uint64{randomElement(2 * i)[0], randomElement(2 * i)[1]} |
| 34 | y := [2]uint64{randomElement(2*i + 1)[0], randomElement(2*i + 1)[1]} |
| 35 | got := mul128(x, y) |
| 36 | want := BigIntToElement(new(big.Int).Mul(ElementToBigInt(Element{x[0], x[1], 0, 0}), ElementToBigInt(Element{y[0], y[1], 0, 0}))) |
| 37 | if got != want { |
| 38 | t.Errorf("/%d mul128(%v,%v) = %v, want %v", i, x, y, got, want) |
| 39 | t.FailNow() |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | func Benchmark_mul128(b *testing.B) { |
| 45 | x := [2]uint64{randomElement(1)[0], randomElement(1)[1]} |
| 46 | y := [2]uint64{randomElement(2)[0], randomElement(2)[1]} |
| 47 | b.ResetTimer() |
| 48 | for i := 0; i < b.N; i++ { |
| 49 | mul128(x, y) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | func Benchmark_mul128_BI(b *testing.B) { |
| 54 | x := [4]uint64{randomElement(1)[0], randomElement(1)[1], 0, 0} |
| 55 | y := [4]uint64{randomElement(2)[0], randomElement(2)[1], 0, 0} |
| 56 | A, B := ElementToBigInt(x), ElementToBigInt(y) |
| 57 | C := new(big.Int) |
| 58 | b.ResetTimer() |
| 59 | for i := 0; i < b.N; i++ { |
| 60 | C.Mul(A, B) |
| 61 | } |
| 62 | } |