diff options
| author | Jacob Kiesel <kieseljake@gmail.com> | 2017-08-26 00:06:13 -0600 |
|---|---|---|
| committer | Jacob Kiesel <kieseljake@gmail.com> | 2017-08-26 10:21:17 -0600 |
| commit | c589f867f89d4e6e48c6602aed8e878208d4822f (patch) | |
| tree | e75a84d4876d5286b95a04f1b3419656fd873537 /src/libcore | |
| parent | 398aaffc94367ed59420f5ac0b0238c04c9e4fa5 (diff) | |
| download | rust-c589f867f89d4e6e48c6602aed8e878208d4822f.tar.gz rust-c589f867f89d4e6e48c6602aed8e878208d4822f.zip | |
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 ec6525485f7..174ceb6b8a7 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -481,6 +481,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")] |
