Skip to content

Commit

Permalink
used preexisting cmp method
Browse files Browse the repository at this point in the history
  • Loading branch information
FelixMaetzler committed Dec 15, 2023
1 parent 2d36617 commit d1a10bf
Showing 1 changed file with 4 additions and 42 deletions.
46 changes: 4 additions & 42 deletions clippy_lints/src/methods/unnecessary_min.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::LateContext;

use rustc_middle::ty::{self, IntTy};
use rustc_middle::ty;
use rustc_span::Span;

pub fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, recv: &'tcx Expr<'_>, arg: &'tcx Expr<'_>) {
Expand Down Expand Up @@ -72,54 +72,16 @@ fn detect_extrema<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<
_ => None,
}
}
fn cmp_for_signed(a: u128, b: u128, cx: &LateContext<'_>, ty: IntTy) -> Ordering {
let a_sign = Sign::from((a, cx, ty));
let b_sign = Sign::from((b, cx, ty));
// The Ordering of a signed integer interpreted as a unsigned integer is as follows:
// -1 b1111... uX::MAX
// iX::MIN b1000...
// iX::MAX b0111...
// 0 b0000... uX::MIN
match (a_sign, b_sign) {
(Sign::Positive, Sign::Positive) | (Sign::Negative, Sign::Negative) => a.cmp(&b),
(Sign::Positive, Sign::Negative) => Ordering::Greater,
(Sign::Negative, Sign::Positive) => Ordering::Less,
}
}
#[derive(Debug)]
enum Sign {
Positive,
Negative,
}
impl From<(u128, &LateContext<'_>, IntTy)> for Sign {
fn from(value: (u128, &LateContext<'_>, IntTy)) -> Self {
// The MSB decides whether the value has a negative sign in front of it or not
// the value 0 is counting as positive (or as non-negative)
let (value, cx, ity) = value;
// shifting the MSB from a iX (i32, i64, etc) to the MSB from a i128
let value = value << (128 - int_bits(cx.tcx, ity));
let msb = (value.reverse_bits()) & 1_u128; // single out the MSB
match msb {
0 => Self::Positive,
1 => Self::Negative,
_ => unreachable!("Bit can only be 0 or 1"),
}
}
}
fn both_are_constant<'tcx>(
cx: &LateContext<'tcx>,
expr: &'tcx Expr<'_>,
recv: &'tcx Expr<'_>,
arg: &'tcx Expr<'_>,
) -> bool {
let ty = cx.typeck_results().expr_ty(recv);
if let (Some(left), Some(right)) = try_to_eval(cx, recv, arg) {
let ord = match (ty.kind(), left, right) {
(ty::Int(ty), Constant::Int(left), Constant::Int(right)) => cmp_for_signed(left, right, cx, *ty),
(ty::Uint(_), Constant::Int(left), Constant::Int(right)) => left.cmp(&right),
_ => return false,
};

if let (Some(left), Some(right)) = try_to_eval(cx, recv, arg)
&& let Some(ord) = Constant::partial_cmp(cx.tcx, ty, &left, &right)
{
let (sugg, other) = match ord {
Ordering::Less => (recv.span, arg.span),
Ordering::Equal | Ordering::Greater => (arg.span, recv.span),
Expand Down

0 comments on commit d1a10bf

Please sign in to comment.