github.com/cockroachdb/apd/v3@v3.2.0/bigint_go1.15_test.go (about) 1 // Copyright 2022 The Cockroach Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 // implied. See the License for the specific language governing 13 // permissions and limitations under the License. 14 15 //go:build go1.15 16 // +build go1.15 17 18 package apd 19 20 import ( 21 "testing" 22 "testing/quick" 23 ) 24 25 // TestBigIntMatchesMathBigInt15 is like TestBigIntMatchesMathBigInt, but for 26 // parts of the shared BigInt/big.Int API that were introduced in go1.15. 27 func TestBigIntMatchesMathBigInt15(t *testing.T) { 28 t.Run("FillBytes", func(t *testing.T) { 29 apd := func(z number) []byte { 30 return z.toApd(t).FillBytes(make([]byte, len(z))) 31 } 32 math := func(z number) []byte { 33 return z.toMath(t).FillBytes(make([]byte, len(z))) 34 } 35 require(t, quick.CheckEqual(apd, math, nil)) 36 }) 37 } 38 39 ////////////////////////////////////////////////////////////////////////////////// 40 // The following tests were copied from the standard library's math/big package // 41 ////////////////////////////////////////////////////////////////////////////////// 42 43 func TestBigIntFillBytes(t *testing.T) { 44 checkResult := func(t *testing.T, buf []byte, want *BigInt) { 45 t.Helper() 46 got := new(BigInt).SetBytes(buf) 47 if got.CmpAbs(want) != 0 { 48 t.Errorf("got 0x%x, want 0x%x: %x", got, want, buf) 49 } 50 } 51 panics := func(f func()) (panic bool) { 52 defer func() { panic = recover() != nil }() 53 f() 54 return 55 } 56 57 for _, n := range []string{ 58 "0", 59 "1000", 60 "0xffffffff", 61 "-0xffffffff", 62 "0xffffffffffffffff", 63 "0x10000000000000000", 64 "0xabababababababababababababababababababababababababa", 65 "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 66 } { 67 t.Run(n, func(t *testing.T) { 68 t.Logf(n) 69 x, ok := new(BigInt).SetString(n, 0) 70 if !ok { 71 panic("invalid test entry") 72 } 73 74 // Perfectly sized buffer. 75 byteLen := (x.BitLen() + 7) / 8 76 buf := make([]byte, byteLen) 77 checkResult(t, x.FillBytes(buf), x) 78 79 // Way larger, checking all bytes get zeroed. 80 buf = make([]byte, 100) 81 for i := range buf { 82 buf[i] = 0xff 83 } 84 checkResult(t, x.FillBytes(buf), x) 85 86 // Too small. 87 if byteLen > 0 { 88 buf = make([]byte, byteLen-1) 89 if !panics(func() { x.FillBytes(buf) }) { 90 t.Errorf("expected panic for small buffer and value %x", x) 91 } 92 } 93 }) 94 } 95 }