Skip to content

Integer overflow false positive with (0u8..).take(256) #25708

Closed
@Kimundi

Description

@Kimundi

Half open ranges like 0u8.. are defined as counting upwards without doing bound checks until their last value.

However, due to the way they are implemented they will panic in debug mode before yielding the last element:

fn main() {
    for i in (0u8..).take(256).skip(250) {
        println!("{}", i);
    }
}
250
251
252
253
254
thread '<main>' panicked at 'arithmetic operation overflowed', /home/rustbuild/src/rust-buildbot/slave/stable-dist-rustc-linux/build/src/libcore/ops.rs:203
playpen: application terminated with error code 101

(https://play.rust-lang.org/?gist=db5b640e1a6c015c03f5&version=stable)

The issue here is that while the yielded values do not depend on a integer overflow occurring, it does so as part for preparing the state for the next, invalid iteration.

It is therefore not possible to use them for counting through the whole range of an integer value in debug mode.

A possible solution would be to use conditional compilation to add a overflow flag to the struct in debug mode, have it use wrapping operation and panic on the next next() call.

See also #20249

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions