Integer parsing: always detect overflows #544
Merged
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.
Fixes #440
The current logic for detecting overflows while parsing large integer only detects some overflows. Each calculation like multiplication and addition has to be verified to be in bounds because otherwise it might silently overflow.
This PR fixes overflow detection and out of bounds checks for integer numbers with large absolute value. It replaces the current bounds checking and overflow checking logic.
The implementation should be quite efficient because the checks only use additions and comparisons of 64bit integers in the parsing loop and it handles negative numbers without additional checks. Furthermore it correctly parses LLONG_MIN on 2s complement architectures, where -LLONG_MIN - 1 = LLONG_MAX should be satisfied. I haven't added a test for this because there is no guarantee that it will work on all architectures, i.e. -LLONG_MIN = LLONG_MAX is also possible. Maybe a test should be added because basically all CPUs use 2s complement representation of signed integers.
PR #543 seems to use a similar idea, but I only noticed it after writing the patch. It uses divisions in the parsing loop and I'm not sure whether it would parse all negative integers correctly.
Changes proposed in this pull request: