diff options
| author | Dirk Leifeld <leifeld@posteo.de> | 2019-03-09 19:16:54 +0100 |
|---|---|---|
| committer | Dirk Leifeld <leifeld@posteo.de> | 2019-03-09 19:16:54 +0100 |
| commit | bd2e12609f190e7bf206dac2de2d68dbb4b1b5e6 (patch) | |
| tree | 1ea51da28d589f5d354ad0830a55c1f651c18370 /src/libcore | |
| parent | 097c04cf433048585dd9e3f63b30e03cc3509e4b (diff) | |
| download | rust-bd2e12609f190e7bf206dac2de2d68dbb4b1b5e6.tar.gz rust-bd2e12609f190e7bf206dac2de2d68dbb4b1b5e6.zip | |
Revert "Revert "Add clamp functions""
Diffstat (limited to 'src/libcore')
| -rw-r--r-- | src/libcore/cmp.rs | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index 81fcdeee12d..259135b9ca0 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -567,6 +567,32 @@ pub trait Ord: Eq + PartialOrd<Self> { where Self: Sized { if self <= other { self } else { other } } + + /// Returns max if self is greater than max, and min if self is less than min. + /// Otherwise this will return self. Panics if min > max. + /// + /// # Examples + /// + /// ``` + /// #![feature(clamp)] + /// + /// assert!((-3).clamp(-2, 1) == -2); + /// assert!(0.clamp(-2, 1) == 0); + /// assert!(2.clamp(-2, 1) == 1); + /// ``` + #[unstable(feature = "clamp", issue = "44095")] + fn clamp(self, min: Self, max: Self) -> Self + where Self: Sized { + assert!(min <= max); + if self < min { + min + } + else if self > max { + max + } else { + self + } + } } #[stable(feature = "rust1", since = "1.0.0")] |
