Skip to content

Clarify black_box() docs when passed a unit-returning function #133923

Closed
@BD103

Description

@BD103

Location

The API documentation for black_box().

Summary

Please see rust-lang/rust-clippy#12707 for more context!

I believe the API docs for black_box() are unclear when passed a unit-returning function. For example:

let x: () = black_box(thread::sleep(...));

The black_box() call makes the returned value treated as volatile, which is pointless because it is a zero-sized type. The above code is equivalent1 to just:

let x: () = thread::sleep(...);

This is unclear in the documentation for black_box(), though. The docs make it seem like the actual call to thread::sleep(...) will be barred from optimizations, which isn't true. As pointed out by y21, constant-folding and other optimizations are still present:

// This...
let y = black_box(42 * 42);
// ...gets compiled to this:
let y = black_box(1764);

I propose that the docs be updated to mention that black_box() makes the value appear volatile to the compiler, and does not affect the argument passed to it.

Footnotes

  1. Mostly equivalent. black_box() does prevent optimizations from call to jmp instructions, even when the function returns unit. See Godbolt. Are there any other possible optimizations that may make this meaningful?

Metadata

Metadata

Assignees

Labels

A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsT-libsRelevant to the library team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions