Skip to content

Range::step_by(0) loops forever #26239

@llogiq

Description

@llogiq

I believe that the step_by(_) method of ranges should panic! if the argument is zero. Currently it loops forever, which is a footgun. At the very least, iterating over such a StepBy should panic! on debug builds. However, I think the earlier the error appears, the better.

Note that this may require us to specialize step_by to types whose Add implementation have a known identity element – at the moment that would mean bounding by the num::Zero trait, which is unstable, also it would probably reduce the usefulness of ranges to numeric types. However, special casing numeric ranges could solve this.

I have also filed an issue at rust-clippy to create a lint for cases where it can be statically detected. Still, that lint cannot detect cases where the argument is calculated at runtime.

The documentation of .step_by(_) should at least warn of the possibility of looping forever or panic once it is implemented.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions