@@ -1115,26 +1115,33 @@ pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
1115
1115
let gcdpow = intrinsics:: cttz_nonzero ( stride) . min ( intrinsics:: cttz_nonzero ( a) ) ;
1116
1116
let gcd = 1usize << gcdpow;
1117
1117
1118
- if p as usize & ( gcd - 1 ) == 0 {
1118
+ if p as usize & ( gcd. wrapping_sub ( 1 ) ) == 0 {
1119
1119
// This branch solves for the following linear congruence equation:
1120
1120
//
1121
- // $$ p + so ≡ 0 mod a $$
1121
+ // ` p + so = 0 mod a `
1122
1122
//
1123
- // $p$ here is the pointer value, $s$ – stride of `T`, $o$ offset in `T`s, and $a$ – the
1123
+ // `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
1124
1124
// requested alignment.
1125
1125
//
1126
- // g = gcd(a, s)
1127
- // o = (a - (p mod a))/g * ((s/g)⁻¹ mod a)
1126
+ // With ` g = gcd(a, s)`, and the above asserting that `p` is also divisible by `g`, we can
1127
+ // denote `a' = a/g`, `s' = s/g`, `p' = p/g`, then this becomes equivalent to:
1128
1128
//
1129
- // The first term is “the relative alignment of p to a”, the second term is “how does
1130
- // incrementing p by s bytes change the relative alignment of p”. Division by `g` is
1131
- // necessary to make this equation well formed if $a$ and $s$ are not co-prime.
1129
+ // ` p' + s'o = 0 mod a' `
1130
+ // ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
1132
1131
//
1133
- // Furthermore, the result produced by this solution is not “minimal”, so it is necessary
1134
- // to take the result $o mod lcm(s, a)$. We can replace $lcm(s, a)$ with just a $a / g$.
1135
- let j = a. wrapping_sub ( pmoda) >> gcdpow;
1136
- let k = smoda >> gcdpow;
1137
- return ( j. wrapping_mul ( mod_inv ( k, a) ) ) & ( ( a >> gcdpow) . wrapping_sub ( 1 ) ) ;
1132
+ // The first term is "the relative alignment of `p` to `a`" (divided by the `g`), the second
1133
+ // term is "how does incrementing `p` by `s` bytes change the relative alignment of `p`" (again
1134
+ // divided by `g`).
1135
+ // Division by `g` is necessary to make the inverse well formed if `a` and `s` are not
1136
+ // co-prime.
1137
+ //
1138
+ // Furthermore, the result produced by this solution is not "minimal", so it is necessary
1139
+ // to take the result `o mod lcm(s, a)`. We can replace `lcm(s, a)` with just a `a'`.
1140
+ let a2 = a >> gcdpow;
1141
+ let a2minus1 = a2. wrapping_sub ( 1 ) ;
1142
+ let s2 = smoda >> gcdpow;
1143
+ let minusp2 = a2. wrapping_sub ( pmoda >> gcdpow) ;
1144
+ return ( minusp2. wrapping_mul ( mod_inv ( s2, a2) ) ) & a2minus1;
1138
1145
}
1139
1146
1140
1147
// Cannot be aligned at all.
0 commit comments