Skip to content

false positive when using a function called min on an unsigned integer type, when the function doesn't return a minimum (e.g. in a builder pattern) #13191

Closed
@m4rch3n1ng

Description

@m4rch3n1ng

Summary

when creating a struct with a min: u8/u16/.. field and using the builder pattern to fill that field with a value of 0, it erroneously emits a unnecessary_min_or_max warning, even though the function is used to set a field on a struct, the struct Parser is not a number so it doesn't make sense for it to "never [be] smaller than 0" and the return value of the min() function is not the same as the input value and is not a number at all.

also, when i run cargo --fix i get this message:

image

side note: this lint doesn't get triggered with a usize

Lint Name

unnecessary_min_or_max

Reproducer

I tried this code:

use std::str::FromStr;

struct Parser {
	/// minimum number of values to parse
	min: u16,
}

impl Parser {
	fn new() -> Self {
		Parser { min: 4 }
	}

	/// set [`Parser::min`]
	fn min(mut self, min: u16) -> Self {
		self.min = min;
		self
	}

	fn parse(&self, val: &str) -> Option<Vec<u32>> {
		let values = val
			.split_whitespace()
			.map(u32::from_str)
			.map(Result::unwrap)
			.collect::<Vec<_>>();

		if values.len() < self.min as usize {
			None
		} else {
			Some(values)
		}
	}
}

fn main() {
	let values = Parser::new().min(0).parse("0 1");
	dbg!(values);
}

I saw this happen:

warning: `Parser::new()` is never smaller than `0` and has therefore no effect
  --> src/main.rs:35:15
   |
35 |     let values = Parser::new().min(0).parse("0 1");
   |                  ^^^^^^^^^^^^^^^^^^^^ help: try: `0`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_min_or_max
   = note: `#[warn(clippy::unnecessary_min_or_max)]` on by default

I expected to see this happen:

no warning

Version

rustc 1.82.0-nightly (612a33f20 2024-07-29)
binary: rustc
commit-hash: 612a33f20b9b2c27380edbc4b26a01433ed114bc
commit-date: 2024-07-29
host: x86_64-unknown-linux-gnu
release: 1.82.0-nightly
LLVM version: 18.1.7

Additional Labels

No response

Metadata

Metadata

Assignees

Labels

C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions