Skip to content

Commit 4b2d87d

Browse files
authoredAug 16, 2023
Rollup merge of #114721 - danflapjax:bool-ord-optimization, r=cuviper
Optimizing the rest of bool's Ord implementation After coming across issue #66780, I realized that the other functions provided by Ord (`min`, `max`, and `clamp`) were similarly inefficient for bool. This change provides implementations for them in terms of boolean operators, resulting in much simpler assembly and faster code. Fixes issue #114653 [Comparison on Godbolt](https://rust.godbolt.org/z/5nb5P8e8j) `max` assembly before: ```assembly example::max: mov eax, edi mov ecx, eax neg cl mov edx, esi not dl cmp dl, cl cmove eax, esi ret ``` `max` assembly after: ```assembly example::max: mov eax, edi or eax, esi ret ``` `clamp` assembly before: ```assembly example::clamp: mov eax, esi sub al, dl inc al cmp al, 2 jae .LBB1_1 mov eax, edi sub al, sil movzx ecx, dil sub dil, dl cmp dil, 1 movzx edx, dl cmovne edx, ecx cmp al, -1 movzx eax, sil cmovne eax, edx ret .LBB1_1: ; identical assert! code ``` `clamp` assembly after: ```assembly example::clamp: test edx, edx jne .LBB1_2 test sil, sil jne .LBB1_3 .LBB1_2: or dil, sil and dil, dl mov eax, edi ret .LBB1_3: ; identical assert! code ```
2 parents 4e3ce0e + b75351e commit 4b2d87d

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed
 

‎library/core/src/cmp.rs

+16
Original file line numberDiff line numberDiff line change
@@ -1406,6 +1406,22 @@ mod impls {
14061406
_ => unsafe { unreachable_unchecked() },
14071407
}
14081408
}
1409+
1410+
#[inline]
1411+
fn min(self, other: bool) -> bool {
1412+
self & other
1413+
}
1414+
1415+
#[inline]
1416+
fn max(self, other: bool) -> bool {
1417+
self | other
1418+
}
1419+
1420+
#[inline]
1421+
fn clamp(self, min: bool, max: bool) -> bool {
1422+
assert!(min <= max);
1423+
self.max(min).min(max)
1424+
}
14091425
}
14101426

14111427
ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }

0 commit comments

Comments
 (0)
Please sign in to comment.