Skip to content
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

Div by zero #31

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions src/intrinsics/native/divmod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,10 @@ pub fn udivmod4(
// Unfortunately, there is no 256-bit equivalent on x86_64, but we can still
// shortcut if the high and low values of the operands are 0:
if a.high() | b.high() == 0 {
res.write(U256::from_words(0, a.low() / b.low()));
if let Some(rem) = rem {
rem.write(U256::from_words(0, a.low() % b.low()));
}
res.write(U256::from_words(0, a.low() / b.low()));
return;
}

Expand Down Expand Up @@ -164,9 +164,15 @@ pub fn udivmod4(

// See Knuth, TAOCP, Volume 2, section 4.3.1, Algorithm D.
// https://skanthak.homepage.t-online.de/division.html
// The high word of v (the divisor) must be non-zero.
#[inline]
pub fn div_mod_knuth(u: &U256, v: &U256) -> (U256, U256) {
const N_UDWORD_BITS: u32 = 128;
assert_ne!(
*u.high(),
0,
"The second operand must be greater than u128::MAX"
);

#[inline]
fn full_shl(a: &U256, shift: u32) -> [u128; 3] {
Expand Down Expand Up @@ -266,7 +272,6 @@ pub fn div_mod_knuth(u: &U256, v: &U256) -> (U256, U256) {
let shift = v.high().leading_zeros();
debug_assert!(shift < N_UDWORD_BITS);
let v = v << shift;
debug_assert!(v.high() >> (N_UDWORD_BITS - 1) == 1);
// u will store the remainder (shifted)
let mut u = full_shl(u, shift);

Expand All @@ -275,6 +280,14 @@ pub fn div_mod_knuth(u: &U256, v: &U256) -> (U256, U256) {
let v_n_1 = *v.high();
let v_n_2 = *v.low();

if v_n_1 >> (N_UDWORD_BITS - 1) != 1 {
debug_assert!(false);

// SAFETY: `v_n_1` must be normalized because input `v` has
// been checked to be non-zero.
unsafe { core::hint::unreachable_unchecked() }
}

// D2. D7. - unrolled loop j == 0, n == 2, m == 0 (only one possible iteration)
let mut r_hat: u128 = 0;
let u_jn = u[2];
Expand Down