|
| 1 | +// SPDX-License-Identifier: MIT |
| 2 | +pragma solidity >=0.8.19 <0.9.0; |
| 3 | + |
| 4 | +import { sqrt } from "src/Common.sol"; |
| 5 | + |
| 6 | +import { Base_Test } from "../../Base.t.sol"; |
| 7 | + |
| 8 | +/// @dev Collection of tests for the square root function available in `Common.sol`. |
| 9 | +contract Common_Sqrt_Test is Base_Test { |
| 10 | + uint256 internal constant MAX_SQRT = type(uint128).max; |
| 11 | + |
| 12 | + function testFuzz_Sqrt_Of256BitNumber(uint256 x) external pure { |
| 13 | + vm.assertLe(sqrt(x) ** 2, x, "Common sqrt"); |
| 14 | + if (x < MAX_SQRT ** 2) { |
| 15 | + vm.assertGt((sqrt(x) + 1) ** 2, x, "Common sqrt"); |
| 16 | + } else { |
| 17 | + // This case cannot be tested nicely using 'vm.assume()', |
| 18 | + // because the fuzzer fails to find enough valid input. |
| 19 | + // That's why we have to embed it here with an 'if'. |
| 20 | + vm.assertEq(sqrt(x), MAX_SQRT, "Common sqrt"); |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + modifier whenSquareDoesNotOverflow(uint256 x) { |
| 25 | + vm.assume(x <= MAX_SQRT); |
| 26 | + _; |
| 27 | + } |
| 28 | + |
| 29 | + function testFuzz_Sqrt_OfPerfectSquare(uint256 x) external pure whenSquareDoesNotOverflow(x) { |
| 30 | + vm.assertEq(sqrt(x ** 2), x, "Common sqrt"); |
| 31 | + } |
| 32 | + |
| 33 | + modifier whenNotZero(uint256 x) { |
| 34 | + vm.assume(x != 0); |
| 35 | + _; |
| 36 | + } |
| 37 | + |
| 38 | + function testFuzz_Sqrt_OfAlmostPerfectSquare(uint256 x) external pure whenNotZero(x) whenSquareDoesNotOverflow(x) { |
| 39 | + vm.assertEq(sqrt(x ** 2 - 1), x - 1, "Common sqrt"); |
| 40 | + } |
| 41 | + |
| 42 | + modifier whenEven(uint256 x) { |
| 43 | + vm.assume(x % 2 == 0); |
| 44 | + _; |
| 45 | + } |
| 46 | + |
| 47 | + function testFuzz_Sqrt_OfPowerOfTwo(uint8 x) external pure whenEven(x) { |
| 48 | + vm.assertEq(sqrt(2 ** x), 2 ** (x / 2), "Common sqrt"); |
| 49 | + } |
| 50 | +} |
0 commit comments