Skip to content

Fix automatic result type of % when the divisor excludes zero - #153

Open
vera-rubin wants to merge 1 commit into
boostorg:developfrom
vera-rubin:fix/automatic-modulus-type
Open

vera-rubin wants to merge 1 commit into
boostorg:developfrom
vera-rubin:fix/automatic-modulus-type

Conversation

@vera-rubin

Copy link
Copy Markdown

modulus_result used t_interval / u_interval storage under automatic for zero-excluding divisor ranges, truncating unfit operands during %: 999 % 1001 with safe_unsigned_range<0, 1000, automatic> and safe_unsigned_literal<1001, automatic> returned 231 using 8-bit storage.

Only storage selection changes: (t_interval / u_interval) | t_interval | u_interval fits operands, preserving supported widening for signed minima modulo -1 because C++ requires representable quotients.

Bounds still use interval corners in safe_base_operations.hpp (#132): safe<std::uint32_t, automatic> modulo literal 10 declares [0,5]. Zero-containing divisor ranges and safe<std::int64_t, automatic> minimum modulo literal -1 undefined behavior stay unchanged.

test3() (test/test_range.cpp): fails base headers, passes fix. Direct test/Jamfile.v2 matches base: 90/90 debug, 91/91 release. b2/CI, MSVC, other standards untested.

Version: fix 42ae4c11ad4d06b325e495ccdbfa3e2160ea2b1f, base be8f6473d3bbb5c546b0a031a9e78f9ba91579c9, GCC 13.3, Clang 18, C++14, Boost 1.83 headers, Linux x86_64.

Fixes #152

— ChipLab

With automatic promotion, modulus_result chose the result type from
t_interval / u_interval when the divisor range excludes zero. The
operation is done in that type, so a dividend or divisor which
doesn't fit was truncated. For example 999 % 1001 with
safe_unsigned_range<0, 1000, automatic> and
safe_unsigned_literal<1001, automatic> used 8 bit storage and
returned 231.

Keep the quotient interval and add both operand intervals to it.
a % b is undefined if a / b doesn't fit, so the quotient still has
to fit. The remainder lies between zero and the dividend, so it fits
as well.
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.

Automatic promotion gives 231 for 999 % 1001

1 participant