geometry: floor_i32 saturates below i32::MIN, as (int) Math.floor

Vanilla 26.3 Mth.floor(double) is (int) Math.floor(v), so a value below
i32::MIN floors to i32::MIN. The truncate-and-step version wrapped to
i32::MAX there (block_collision_scan parity failed at the chunk of
x = -2147483648.8: Rust 134217727, vanilla -134217728). Step down with
saturating_sub; the fast path is unchanged, and the test now checks
the ends of the i32 range, infinities and f64::MIN/MAX against
f64::floor as i32.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-22 15:37:37 +02:00
parent 5bad717213
commit a49cf5502d
+20 -6
View File
@@ -602,13 +602,15 @@ pub(crate) fn clamp(value: f64, min: f64, max: f64) -> f64 {
java_min(value, max)
}
}
/// `Mth.floor`: truncate, then step down for negative fractions. A truncating
/// conversion and a compare, where `f64::floor` is a libm call on baseline x86-64.
/// `Mth.floor`, which is `(int) Math.floor(v)`: truncate, then step down for
/// negative fractions. A truncating conversion and a compare, where
/// `f64::floor` is a libm call on baseline x86-64. Both casts saturate (NaN is
/// 0), so the step down saturates too: below `i32::MIN` stays `i32::MIN`.
#[inline]
pub(crate) fn floor_i32(value: f64) -> i32 {
let truncated = value as i32;
if value < f64::from(truncated) {
truncated.wrapping_sub(1)
truncated.saturating_sub(1)
} else {
truncated
}
@@ -659,13 +661,25 @@ mod tests {
-1e-300,
16_777_215.5,
-16_777_215.5,
// Past the i32 range `(int) Math.floor` saturates (vanilla 26.3's
// BlockCollisions and BlockPos.containing rely on it).
2_147_483_647.5,
2_147_483_648.0,
-2_147_483_648.0,
-2_147_483_648.5,
-2_147_483_649.0,
3e9,
-3e9,
f64::MAX,
f64::MIN,
f64::INFINITY,
f64::NEG_INFINITY,
] {
assert_eq!(floor_i32(v), v.floor() as i32, "{v}");
}
assert_eq!(floor_i32(f64::NAN), 0);
assert_eq!(floor_i32(3e9), i32::MAX);
// Java's (int) cast saturates, then the step down wraps.
assert_eq!(floor_i32(-3e9), i32::MAX);
assert_eq!(floor_i32(-3e9), i32::MIN);
assert_eq!(floor_i32(-2_147_483_648.5), i32::MIN);
}
#[test]
fn ray_faces_and_half_open_bounds() {