static-assertions icon indicating copy to clipboard operation
static-assertions copied to clipboard

Recommended way to avoid clippy error?

Open bramp opened this issue 4 years ago • 1 comments

I have the following code:


const INITIAL_BIAS: u32 = 72;
const BASE: u32         = 36;
const TMIN: u32         = 1;

const_assert!(INITIAL_BIAS % BASE <= BASE - TMIN); 
error: this comparison involving the minimum or maximum element for this type contains a case that is always true or always false
  --> src/punycode.rs:18:15
   |
18 | const_assert!(INITIAL_BIAS % BASE <= BASE - TMIN);
   |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: `#[deny(clippy::absurd_extreme_comparisons)]` on by default
   = help: because `INITIAL_BIAS % BASE` is the minimum value for this type, this comparison is always true
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#absurd_extreme_comparisons

Basically in this example the constant expression INITIAL_BIAS % BASE = 0, and for unsigned ints 0 is always the smallest value, thus doing <= is always true.

I can disable the clippy warning for my file, but I'm curious if there is some way for const_assert to suppress this error? Otherwise is reduces the value of these const_assert a little bit, without disabling the clippy warning.

bramp avatar May 31 '21 23:05 bramp

Yeah, I've also experienced warnings on constants.

/// the amount of lives the player starts with
const STARTING_LIVES: usize = 3;
/// game cannot graphically handle more than this, so ensure we don't later change `STARTING_LIVES`
/// to anything greater
const LIVES_CAP: usize = 10;

const_assert!(STARTING_LIVES <= LIVES_CAP);

warning: constant `LIVES_CAP` is never used
  --> src/main.rs:18:7
   |
18 | const LIVES_CAP: usize = 10;
   |       ^^^^^^^^^
   |
   = note: `#[warn(dead_code)]` on by default

I've solved this by adding #[allow(unused)], though in your case you'll need rust nightly to fix it.

#![feature(stmt_expr_attributes)]

const INITIAL_BIAS: u32 = 72;
const BASE: u32 = 36;
const TMIN: u32 = 1;
const_assert!(
    #[allow(clippy::absurd_extreme_comparisons)]
    INITIAL_BIAS
        % BASE
        <= BASE - TMIN
);

DazorPlasma avatar Mar 17 '24 19:03 DazorPlasma