{
    "Function": "log2",
    "File": "src/libraries/Math128x128.sol",
    "Parent Contracts": [],
    "High-Level Calls": [
        "BitMath"
    ],
    "Internal Calls": [
        "revert Math128x128__LogUnderflow()"
    ],
    "Library Calls": [
        "mostSignificantBit"
    ],
    "Low-Level Calls": [],
    "Code": "function log2(uint256 x) internal pure returns (int256 result) {\n        // Convert x to a unsigned 129.127-binary fixed-point number to optimize the multiplication.\n        // If we use an offset of 128 bits, y would need 129 bits and y**2 would would overflow and we would have to\n        // use mulDiv, by reducing x to 129.127-binary fixed-point number we assert that y will use 128 bits, and we\n        // can use the regular multiplication\n\n        if (x == 1) return 0;\n        if (x == 0) revert Math128x128__LogUnderflow();\n\n        x >>= 1;\n\n        unchecked {\n            // This works because log2(x) = -log2(1/x).\n            int256 sign;\n            if (x >= LOG_SCALE) {\n                sign = 1;\n            } else {\n                sign = -1;\n                // Do the fixed-point inversion inline to save gas\n                x = LOG_SCALE_SQUARED / x;\n            }\n\n            // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).\n            uint256 n = (x >> LOG_SCALE_OFFSET).mostSignificantBit();\n\n            // The integer part of the logarithm as a signed 129.127-binary fixed-point number. The operation can't overflow\n            // because n is maximum 255, LOG_SCALE_OFFSET is 127 bits and sign is either 1 or -1.\n            result = int256(n) << LOG_SCALE_OFFSET;\n\n            // This is y = x * 2^(-n).\n            uint256 y = x >> n;\n\n            // If y = 1, the fractional part is zero.\n            if (y != LOG_SCALE) {\n                // Calculate the fractional part via the iterative approximation.\n                // The \"delta >>= 1\" part is equivalent to \"delta /= 2\", but shifting bits is faster.\n                for (int256 delta = int256(1 << (LOG_SCALE_OFFSET - 1)); delta > 0; delta >>= 1) {\n                    y = (y * y) >> LOG_SCALE_OFFSET;\n\n                    // Is y^2 > 2 and so in the range [2,4)?\n                    if (y >= 1 << (LOG_SCALE_OFFSET + 1)) {\n                        // Add the 2^(-m) factor to the logarithm.\n                        result += delta;\n\n                        // Corresponds to z/2 on Wikipedia.\n                        y >>= 1;\n                    }\n                }\n            }\n            // Convert x back to unsigned 128.128-binary fixed-point number\n            result = (result * sign) << 1;\n        }\n    }"
}