Skip to content

Suggest the usage of NonZeroU#::from where appropriate #7291

@leonardo-m

Description

@leonardo-m

I think Clippy should start suggesting the usage of NonZeroU#::from from smaller NonZeroU#, as in code like:

#![allow(unused_variables)]
use std::num::{NonZeroU32, NonZeroU64};

fn main() {
    let x: u64 = 100;
    let y = NonZeroU32::new(10).unwrap();

    // Given code:
    let r1 = x / u64::from(y.get());
    let r2 = x % u64::from(y.get());

    // Clippy should suggest:
    let r1 = x / NonZeroU64::from(y);
    let r2 = x % NonZeroU64::from(y);
}

Activity

added
good first issueThese issues are a good way to get started with Clippy
L-restrictionLint: Belongs in the restriction lint group
on Sep 15, 2021
marekdownar

marekdownar commented on Jan 21, 2022

@marekdownar
Contributor

@rustbot claim

Samarth1696

Samarth1696 commented on Jul 22, 2024

@Samarth1696
Contributor

@rustbot claim

added a commit that references this issue on Sep 7, 2024
y21

y21 commented on Oct 19, 2024

@y21
Member

Closing as this was implemented in #13167

warning: consider using `NonZeroU64::from()` for more efficient and type-safe conversion
  --> y.rs:10:18
   |
10 |     let r1 = x / u64::from(y.get());
   |                  ^^^^^^^^^^^^^^^^^^ help: replace with: `NonZeroU64::from(y)`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#non_zero_suggestions
note: the lint level is defined here
  --> y.rs:2:9
   |
2  | #![warn(clippy::non_zero_suggestions)]
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
leonardo-m

leonardo-m commented on Oct 19, 2024

@leonardo-m
Author

Now we have the generic num::NonZero too, so perhaps suggesting this is better?

#![allow(unused_variables)]
#![warn(clippy::all)]
#![warn(clippy::nursery)]
#![warn(clippy::pedantic)]
use std::num::NonZero;

fn main() {
    let x: u64 = 100;
    let y = const { NonZero::<u32>::new(10).unwrap() };

    // Given code:
    let r1 = x / u64::from(y.get());
    let r2 = x % u64::from(y.get());

    // Clippy could suggest:
    let r1 = x / NonZero::<u64>::from(y);
    let r2 = x % NonZero::<u64>::from(y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

A-lintArea: New lintsL-restrictionLint: Belongs in the restriction lint groupgood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

    Development

    No branches or pull requests

      Participants

      @marekdownar@giraffate@leonardo-m@y21@Samarth1696

      Issue actions

        Suggest the usage of NonZeroU#::from where appropriate · Issue #7291 · rust-lang/rust-clippy