Skip to content

std: add range(usize) #8663

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed

std: add range(usize) #8663

wants to merge 1 commit into from

Conversation

nektro
Copy link
Contributor

@nektro nektro commented May 1, 2021

Many have requested an easier way to make an incrementing loop. In a way that doesn't dirty the namespace currently being worked in with an i variable with use of a while loop. Or suggesting a syntax change to the for loop or a new loop entirely. However, this is possible in userspace by taking advantage of the semantics of zero sized types.

As written in the doc comment it is used like so:

for (std.range(10)) |_, i| {
    // 'i' will increment from 0 -> 9
}

Justification: #358, #8292, and more

@andrewrk
Copy link
Member

andrewrk commented May 1, 2021

nah just use a while loop

@andrewrk andrewrk closed this May 1, 2021
@nektro nektro deleted the patch-1 branch May 1, 2021 05:51
@Jarred-Sumner
Copy link
Contributor

This would be nice with inline when iterating through lists with comptime-known length but runtime-known values. That also avoids the overhead of creating a temporary array since it would do that at comptime

Before:

const unroll_count = comptime 64 / @sizeOf(PackageID);

while (remaining.len > unroll_count) {
    comptime var i: usize = 0;
    inline while (i < unroll_count) : (i += 1) {
        installer.installPackage(remaining[i], comptime log_level);
    }
    remaining = remaining[unroll_count..];
}

After:

const unroll_count = comptime 64 / @sizeOf(PackageID);

while (remaining.len > unroll_count) {
    inline for (std.range(unroll_count)) |i| {
        installer.installPackage(remaining[i], comptime log_level);
    }
    remaining = remaining[unroll_count..];
}

@nektro
Copy link
Contributor Author

nektro commented Mar 18, 2022

been available as a package at https://github.com/nektro/zig-range for some time now for anyone who still comes across this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants