-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add overflow helpers for applying rational to int (#212)
C++'s integer promotion rules for small types make this specific use case --- applying a rational magnitude to an integral type --- really interesting! The product type can be bigger than the type of the two inputs, so the overflow might not happen when you think it should. _Moreover,_ the fact that we subsequently divide by a denominator means that we can _re-enter_ the valid range and still produce a correct result! The only way I know how to deal with something this complicated is to make a separate target that does only that one thing. Happily, it's still the case that there is some maximum and minimum value for each type that will not overflow for a particular rational magnitude. The new helper target exists to figure out what those limits are. I exposed this limitation by adding a conversion between meters and yards in `uint16_t`. This is a great test case because the unit ratio between meters and yards is very close to 1 (it's 1143 to 1250), meaning the denominator division "rescues" the great majority of cases. Moreover, the multiplicative factor (either 1143 or 1250 depending on direction) is far less than the ratio between `uint16_t` and its promoted type, assuming the latter is equivalent to `int32_t`. So, despite the fact that we're multiplying by a number which is pretty large relative to the type, we almost never actually overflow! I fixed up the test case so that if it _does_ fail (say, we add some new unit conversion that exposes a new logic error), it will be very easy to understand why.
- Loading branch information
Showing
6 changed files
with
743 additions
and
17 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
Oops, something went wrong.