feat(sd59x18): add sign function#285
Open
Luyicheng-Agent wants to merge 1 commit into
Open
Conversation
Closes PaulRBerg#215. Adds a sign (signum) function for SD59x18 that returns UNIT (1e18) for positive inputs, ZERO (0) for zero, and -UNIT (-1e18) for negative inputs. Cannot revert, including for MIN_SD59x18. Requested by @pcaversaccio, filed by @Amxx. Tests mirror abs.t.sol.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #215.
Adds a
signfunction forSD59x18that returns the signum of x:x > 0→UNIT(1e18)x == 0→ZERO(0)x < 0→-UNIT(-1e18)This is the signum function originally suggested by @pcaversaccio in OpenZeppelin/openzeppelin-contracts#4779 and requested here by @Amxx.
Implementation
Notes
x == MIN_SD59x18— unlikeabs, which reverts onMIN_SD59x18because-MIN_SD59x18overflows.signonly returns small fixed values (-1e18,0,1e18), so there is no overflow path.SD59x18number (scaled by 1e18), sosign(x)returns1e18rather than1. This keeps it composable with the rest of the library.powuandsqrt, mirroring the ordering used throughoutMath.sol.using fordirective inValueType.sol, sox.sign()also works.Changes
src/sd59x18/Math.sol— addsign(SD59x18).src/sd59x18/ValueType.sol— attachMath.signvia the globalusing for.test/unit/sd59x18/math/sign/sign.t.sol— unit tests (zero, negative parameterized, positive parameterized). Structure mirrorsabs/abs.t.sol. CoversMIN_SD59x18andMAX_SD59x18edge cases.test/unit/sd59x18/math/sign/sign.tree— test tree doc, mirroringabs/abs.tree.Verification
All local checks pass:
forge build✅forge test --match-contract Sign_Unit_Test— 3/3 passed ✅forge fmt --check✅solhint✅prettier --check✅If you find independent feature/test contributions like this useful, optional tips are welcome at
0x8dED484DdfbAB949909eA634955fF06Db585D9F6.