Skip to content

Commit 5549523

Browse files
committed
Auto merge of #147754 - Dan54:friendly-clamp, r=Mark-Simulacrum
Improve error message for std integer clamp() if min > max For #142309: change the error message for `Ord::clamp()` for std integer types if min > max to be more useful. Message is now `min > max. min = {min:?}, max = {max:?}` Also add `#[track_caller]` to `clamp()`
2 parents ba2142a + 6dbea1f commit 5549523

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

library/core/src/cmp.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1855,6 +1855,7 @@ mod impls {
18551855
use crate::hint::unreachable_unchecked;
18561856
use crate::marker::PointeeSized;
18571857
use crate::ops::ControlFlow::{self, Break, Continue};
1858+
use crate::panic::const_assert;
18581859

18591860
macro_rules! partial_eq_impl {
18601861
($($t:ty)*) => ($(
@@ -1997,6 +1998,26 @@ mod impls {
19971998
fn cmp(&self, other: &Self) -> Ordering {
19981999
crate::intrinsics::three_way_compare(*self, *other)
19992000
}
2001+
2002+
#[inline]
2003+
#[track_caller]
2004+
fn clamp(self, min: Self, max: Self) -> Self
2005+
{
2006+
const_assert!(
2007+
min <= max,
2008+
"min > max",
2009+
"min > max. min = {min:?}, max = {max:?}",
2010+
min: $t,
2011+
max: $t,
2012+
);
2013+
if self < min {
2014+
min
2015+
} else if self > max {
2016+
max
2017+
} else {
2018+
self
2019+
}
2020+
}
20002021
}
20012022
)*)
20022023
}

0 commit comments

Comments
 (0)