Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recommend NonZero*::new.unwrap() over NonZero*::new_unchecked in consts #13991

Closed
zacknewman opened this issue Jan 13, 2025 · 2 comments · Fixed by #13993
Closed

Recommend NonZero*::new.unwrap() over NonZero*::new_unchecked in consts #13991

zacknewman opened this issue Jan 13, 2025 · 2 comments · Fixed by #13993
Assignees
Labels
A-lint Area: New lints

Comments

@zacknewman
Copy link

zacknewman commented Jan 13, 2025

What it does

Just found out that Option::unwrap is now a const fn; had I not ran into that, I wouldn't have changed my use of NonZero*::new_unchecked for const variables.

Advantage

  • Removes one more case where unsafe code is needed.

Drawbacks

  • Conflicts with unwrap_used.

Example

use core::num::NonZeroUsize;
const FOO: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(1) };

Could be written as:

use core::num::NonZeroUsize;
const FOO: NonZeroUsize =  NonZeroUsize::new(1).unwrap();
@zacknewman zacknewman added the A-lint Area: New lints label Jan 13, 2025
@zacknewman zacknewman changed the title Recommend NonZero*:new.unwrap() over NonZero*::new_unchecked in consts Recommend NonZero*::new.unwrap() over NonZero*::new_unchecked in consts Jan 13, 2025
@samueltardieu
Copy link
Contributor

@rustbot claim

github-merge-queue bot pushed a commit that referenced this issue Jan 15, 2025
changelog: [`useless-nonzero-new_unchecked`]: new lint

Close #13991

### What it does

Checks for `NonZero*::new_unchecked(<literal>)` being used in a `const`
context.

### Why is this bad?

Using `NonZero*::new_unchecked()` is an `unsafe` function and requires
an `unsafe` context. When used with an
integer literal in a `const` context, `NonZero*::new().unwrap()` will
provide the same result with identical
runtime performances while not requiring `unsafe`.

### Example
```no_run
const PLAYERS: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(3) };
```
Use instead:
```no_run
const PLAYERS: NonZeroUsize = NonZeroUsize::new(3).unwrap();
```
@leonardo-m
Copy link

To avoid seeing the unwrap, sometimes I'd like to use a compile-time function like this:

const FOO: NonZeroUsize = non_zero<usize, 1>();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants