Possible to cause infinite loop?
andrews05 opened this issue · comments
I was just looking at the latest properties for Options
and it seems it could infinite loop if both iteration_count
and iterations_without_improvement
are None
. Sure, you would be silly to deliberately set them both to None, but I'm concerned it could quite easily happen unintentionally if you did something like this:
Options {
iteration_count: NonZeroU64::new(get_value_from_args()),
..Default::default()
}
If get_value_from_args()
returned 0
then you might have a problem.
Previously iteration_count
wasn't an option so you were required to unwrap the NonZero. I think it was safer like this - you could always set it to NonZeroU64::MAX
if you wanted to rely solely on iterations_without_improvement
.
I think your analysis of the situation is spot on. Client code resorting to NonZeroU64::new
with variable input can be a footgun I didn't realize when this feature was merged, and while such a mistake would be on the user's end, the fact that it is easy for client code to make this mistake suggests that a better API could help.
Dropping the Option
here is a good way to go. For practical purposes, there is no difference between 264 - 1 iterations and potentially infinite iterations. In fact, I think it'd be good to drop the Option
from both, so it is not possible to do too few iterations without improvement if a NonZero
is constructed from a zero iterations_without_improvement
number.