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