Add note, or new method, for full-width integer division

(I'm not sure this should have gone into an Evolution subcategory instead.)

FixedWidthInteger provides three extended division methods. The dividedReportingOverflow and remainderReportingOverflow work like the similar methods for adding, subtracting, and multiplying; they return an overflow flag that's set to true if the user tried dividing by zero or if the result is too big. There is also dividingFullWidth, a counterpart to the full-width multiplication method provided by the protocol.

The problem is that dividingFullWidth does not protect against overflow. If the divisor is zero, or if the quotient is large (absolutely) enough to require two words, then the program stops with a run-time error. That second case could be caused by using a divisor not larger than the dividend's high word. We need a method that combines full-width division with an overflow flag. Or at least, some way to check in advance.

This was caused by me needing to divide a result that came from a call to the full-width multiplication method. Since all the numbers I'm working with are positive, I added a check to see if the divisor is not greater than the dividend's high word. But how does it work if either the divisor and/or dividend high word is negative? If we don't want to add another method, then the docs for dividingFullWidth should provide a guide to how to check the divisor and dividend in advance for overflow.

2 Likes

This seems like an easy documentation note to add. Can you open a bug report for it and CC me and @nnnnnnnn?

For the more general API question, I would hesitate to add yet another function for this, since this is a pretty common restriction (in line with what most other languages provide)--most algorithms that would use this operation have a static guarantee that the overflow doesn't happen, and the algorithms where that isn't the case are better-served by an arbitrary-precision integer type.

SR-11942, "There is no recoverable overflow policy for FixedWidthInteger.dividingFullWidth," has been created. (I don't know how to CC it to others.)

1 Like