Skip to content

Commit d664758

Browse files
committed
Backport total_cmp for Rust <1.62
1 parent a4c9435 commit d664758

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

build.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ fn main() {
1616
ac.emit_expression_cfg("1f64.copysign(-1f64)", "has_copysign");
1717
}
1818
ac.emit_expression_cfg("1f64.is_subnormal()", "has_is_subnormal");
19+
ac.emit_expression_cfg("1f64.total_cmp(&2f64)", "has_total_cmp");
1920

2021
ac.emit_expression_cfg("1u32.to_ne_bytes()", "has_int_to_from_bytes");
2122
ac.emit_expression_cfg("3.14f64.to_ne_bytes()", "has_float_to_from_bytes");

src/float.rs

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2268,17 +2268,31 @@ pub trait TotalOrder {
22682268
fn total_cmp(&self, other: &Self) -> Ordering;
22692269
}
22702270
macro_rules! totalorder_impl {
2271-
($T:ident) => {
2271+
($T:ident, $I:ident, $U:ident, $bits:expr) => {
22722272
impl TotalOrder for $T {
22732273
#[inline]
2274+
#[cfg(has_total_cmp)]
22742275
fn total_cmp(&self, other: &Self) -> Ordering {
2276+
// Forward to the core implementation
22752277
Self::total_cmp(&self, other)
22762278
}
2279+
#[inline]
2280+
#[cfg(not(has_total_cmp))]
2281+
fn total_cmp(&self, other: &Self) -> Ordering {
2282+
// Backport the core implementation (since 1.62)
2283+
let mut left = self.to_bits() as $I;
2284+
let mut right = other.to_bits() as $I;
2285+
2286+
left ^= (((left >> ($bits - 1)) as $U) >> 1) as $I;
2287+
right ^= (((right >> ($bits - 1)) as $U) >> 1) as $I;
2288+
2289+
left.cmp(&right)
2290+
}
22772291
}
22782292
};
22792293
}
2280-
totalorder_impl!(f64);
2281-
totalorder_impl!(f32);
2294+
totalorder_impl!(f64, i64, u64, 64);
2295+
totalorder_impl!(f32, i32, u32, 32);
22822296

22832297
#[cfg(test)]
22842298
mod tests {

0 commit comments

Comments
 (0)