Skip to content

Fix buffer resizing overflow and introduce safe power-of-two capacity growth #2984

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from

Conversation

bernardladenthin
Copy link

  • Previously, calculating next capacity for large values like 1_073_741_824 caused overflow and returned Integer.MIN_VALUE.
  • Rewrote ensureCapacity to use Long for arithmetic to guard against exceeding Int.MAX_VALUE.
  • Introduced nextPowerOfTwoCapacity(minCapacity: Int) to safely calculate the next power-of-two ≥ minCapacity.
  • Capped capacity at Int.MAX_VALUE to prevent buffer allocation errors.
  • Added comprehensive unit tests covering negative, small, exact, and large input values to validate correct capacity growth behavior.

Note: You can compare the fixed behavior with the old logic using:

fun nextPowerOfTwoCapacity(minCapacity: Int): Int {
    return minCapacity.takeHighestOneBit() shl 1
}

whyoleg and others added 2 commits April 10, 2025 16:54
… growth

- Previously, calculating next capacity for large values like 1_073_741_824 caused overflow and returned Integer.MIN_VALUE.
- Rewrote `ensureCapacity` to use `Long` for arithmetic to guard against exceeding Int.MAX_VALUE.
- Introduced `nextPowerOfTwoCapacity(minCapacity: Int)` to safely calculate the next power-of-two ≥ minCapacity.
- Capped capacity at Int.MAX_VALUE to prevent buffer allocation errors.
- Added comprehensive unit tests covering negative, small, exact, and large input values to validate correct capacity growth behavior.
@bernardladenthin bernardladenthin changed the base branch from master to dev April 14, 2025 22:44
@bernardladenthin
Copy link
Author

bernardladenthin commented Apr 14, 2025

Wrong branch, new PR in #2985

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants