Skip to content

Commit 3948c65

Browse files
committed
Rebased Partial comparisons for NonZeroes
1 parent 829d69b commit 3948c65

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

library/core/src/num/mod.rs

+29
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
55
#![stable(feature = "rust1", since = "1.0.0")]
66

7+
use crate::cmp::Ordering;
78
use crate::convert::Infallible;
89
use crate::fmt;
910
use crate::intrinsics;
@@ -170,6 +171,34 @@ assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", s
170171
}
171172
}
172173

174+
#[stable(feature = "nonzero_cmp_to_int", since = "1.47.0")]
175+
impl PartialEq<$Int> for $Ty {
176+
fn eq(&self, rhs: &$Int) -> bool {
177+
self.0 == *rhs
178+
}
179+
}
180+
181+
#[stable(feature = "nonzero_cmp_to_int", since = "1.47.0")]
182+
impl PartialOrd<$Int> for $Ty {
183+
fn partial_cmp(&self, rhs: &$Int) -> Option<Ordering> {
184+
Some(self.0.cmp(rhs))
185+
}
186+
}
187+
188+
#[stable(feature = "nonzero_cmp_to_int", since = "1.47.0")]
189+
impl PartialEq<$Ty> for $Int {
190+
fn eq(&self, rhs: &$Ty) -> bool {
191+
*self == rhs.0
192+
}
193+
}
194+
195+
#[stable(feature = "nonzero_cmp_to_int", since = "1.47.0")]
196+
impl PartialOrd<$Ty> for $Int {
197+
fn partial_cmp(&self, rhs: &$Ty) -> Option<Ordering> {
198+
Some(self.cmp(&rhs.0))
199+
}
200+
}
201+
173202
impl_nonzero_fmt! {
174203
#[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
175204
}

library/core/tests/nonzero.rs

+46
Original file line numberDiff line numberDiff line change
@@ -195,3 +195,49 @@ fn test_nonzero_from_int_on_err() {
195195
assert!(NonZeroI8::try_from(0).is_err());
196196
assert!(NonZeroI32::try_from(0).is_err());
197197
}
198+
199+
#[test]
200+
fn test_compare_regular_int() {
201+
let nonzero = NonZeroI32::new(125).unwrap();
202+
203+
assert_eq!(nonzero, 125);
204+
assert_ne!(nonzero, 0);
205+
assert_ne!(nonzero, -125);
206+
207+
assert!(nonzero == 125);
208+
assert!(nonzero != 0);
209+
assert!(nonzero != -125);
210+
211+
assert!(nonzero < 200);
212+
assert!(nonzero <= 125);
213+
assert!(nonzero <= 200);
214+
215+
assert!(nonzero > 0);
216+
assert!(nonzero > -200);
217+
assert!(nonzero >= 125);
218+
assert!(nonzero >= 0);
219+
assert!(nonzero >= -100);
220+
}
221+
222+
#[test]
223+
fn test_compare_regular_int_reversed() {
224+
let nonzero = NonZeroI32::new(125).unwrap();
225+
226+
assert_eq!(125, nonzero);
227+
assert_ne!(0, nonzero);
228+
assert_ne!(-125, nonzero);
229+
230+
assert!(125 == nonzero);
231+
assert!(0 != nonzero);
232+
assert!(-125 != nonzero);
233+
234+
assert!(200 > nonzero);
235+
assert!(125 >= nonzero);
236+
assert!(200 >= nonzero);
237+
238+
assert!(0 < nonzero);
239+
assert!(-200 < nonzero);
240+
assert!(125 <= nonzero);
241+
assert!(0 <= nonzero);
242+
assert!(-100 <= nonzero);
243+
}

0 commit comments

Comments
 (0)