Cargo clippy --fix seems to not respect black_box

Hi everyone,

One of my colleagues just tried running cargo clippy --fix on our benchmark targets, (using 1.95 on the nightly channel) and it converted this:

 black_box(hasher.write(&data));

To this:

    let _: () = hasher.write(&data);
    black_box(());

This clippy rule is this one:

warning: passing a unit value to a function
  --> crates\fxv_multicas\benches\hash_hashing.rs:11:5
   |
11 |     black_box(hasher.write(&data));
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unit_arg
   = note: `#[warn(clippy::unit_arg)]` on by default

The goal is to ensure that hasher.write is not optimized away in my benchmark, though perhaps that's not even necessary in this case. We do have some other slightly more complex cases where it does the same thing.

Given black_box()'s special status, should this still happen, i.e. is it a bug? It feels like it is a special case bug since black_box is a compiler hint, but I don't know enough to be sure.

Is the workaround just to #[allow(clippy::unit_arg)] in these functions? Is there a way to make it such that it leaves black_box alone always?

Clippy is right. black_box does not do anything here, it only changes the value that passes through it. You may want to do hasher.write(black_box(&data)) or drop(black_box(hasher)), depending on what the benchmark looks like.

2 Likes

From the docs:

There may be additional situations where you want to wrap the result of a function in black_box to force its execution. This is situational though, and may not have any effect (such as when the function returns a zero-sized type such as () unit).

and

Note that black_box has no effect on how its input is treated, only its output. As such, expressions passed to black_box may still be optimized

3 Likes

Ah okay, I think I understand, thanks both for the pointers. It seems what I want here is hasher.write(black_box(&data)), there is an example in the black_box docs that is very close to that.

Much appreciated @steffahn and @drewtato !

1 Like