From 911736dd8527bad44f7d939ebab484a6530123ba Mon Sep 17 00:00:00 2001 From: Dylan MacKenzie Date: Mon, 29 Nov 2021 19:06:44 -0800 Subject: [PATCH 1/2] Mark defaulted `PartialEq`/`PartialOrd` methods as const --- library/core/src/cmp.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index 7456f886ea5d8..deed9901cc9e4 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -215,6 +215,7 @@ pub trait PartialEq { #[inline] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] + #[default_method_body_is_const] fn ne(&self, other: &Rhs) -> bool { !self.eq(other) } @@ -1031,6 +1032,7 @@ pub trait PartialOrd: PartialEq { #[inline] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] + #[default_method_body_is_const] fn lt(&self, other: &Rhs) -> bool { matches!(self.partial_cmp(other), Some(Less)) } @@ -1050,6 +1052,7 @@ pub trait PartialOrd: PartialEq { #[inline] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] + #[default_method_body_is_const] fn le(&self, other: &Rhs) -> bool { // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`. // FIXME: The root cause was fixed upstream in LLVM with: @@ -1072,6 +1075,7 @@ pub trait PartialOrd: PartialEq { #[inline] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] + #[default_method_body_is_const] fn gt(&self, other: &Rhs) -> bool { matches!(self.partial_cmp(other), Some(Greater)) } @@ -1091,6 +1095,7 @@ pub trait PartialOrd: PartialEq { #[inline] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] + #[default_method_body_is_const] fn ge(&self, other: &Rhs) -> bool { matches!(self.partial_cmp(other), Some(Greater | Equal)) } From dc18d507de30c0e27ed41994a863b9b54b445c67 Mon Sep 17 00:00:00 2001 From: Dylan MacKenzie Date: Wed, 1 Dec 2021 14:37:51 -0800 Subject: [PATCH 2/2] Test const impl of `cmp` traits --- library/core/tests/cmp.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/library/core/tests/cmp.rs b/library/core/tests/cmp.rs index 11cf7add07ada..c9d29ed3a83f4 100644 --- a/library/core/tests/cmp.rs +++ b/library/core/tests/cmp.rs @@ -203,3 +203,31 @@ fn cmp_default() { assert!(Fool(false) != Fool(false)); assert_eq!(Fool(false), Fool(true)); } + +struct S(i32); + +impl const PartialEq for S { + fn eq(&self, other: &Self) -> bool { + self.0 == other.0 + } +} + +impl const PartialOrd for S { + fn partial_cmp(&self, other: &Self) -> Option { + let ret = match (self.0, other.0) { + (a, b) if a > b => Ordering::Greater, + (a, b) if a < b => Ordering::Less, + _ => Ordering::Equal, + }; + + Some(ret) + } +} + +const _: () = assert!(S(1) == S(1)); +const _: () = assert!(S(0) != S(1)); + +const _: () = assert!(S(1) <= S(1)); +const _: () = assert!(S(1) >= S(1)); +const _: () = assert!(S(0) < S(1)); +const _: () = assert!(S(1) > S(0));