Skip to content

Optimized mulDiv alternatives for special cases #5093

Open
@3sGgpQ8H

Description

@3sGgpQ8H

🧐 Motivation
The mulDiv function defined in Math.sol is very efficient in a generic case, but for specific cases better approaches could exist. Consider implementing optimized mulDiv alternatives for special cases.

📝 Details
Add the following functions to Math.sol:

  1. mulDivFull(uint x, uint y, uint denominator) returns (uint): like mulDiv but always does full division, skipping the prod1 == 0 check; useful for cases where x*y is very unlikely to fit into 256 bits.
  2. mulDivStatic(uint x, uint y, uint denominator, uint twos, uint inverse) returns (uint): like mulDiv but accepts the twos and inverse values as arguments, instead of than calculates them; useful for cases where denominator is a constant or where the same denominator is used many times. Also consider a separate function to calculate twos and inverse for a given denominator.
  3. shlDiv(uint x, uint sh, uint denominator) returns (uint): like mulDiv but performs left shift instead of multiplication; useful for cases where one of the factors is a known power of two. Also consider functions shlDivFull and shlDivStatic.
  4. mulShr(uint x, uint y, uint sh) returns (uint): like mulDiv but performs right shift instead of division; useful for cases where denominator is a known power of two. Also consider function mulShrFull.
  5. mulDiv128(uint x, uint y, uint128 denominator) returns (uint): like mulDiv but with 128-bit denominator, which more efficient implementation (https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1#4821); useful for cases where denominator is guaranteed to fit into 128 bits.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions