Skip to content

Add @divCeil #4095

@momumi

Description

@momumi

The / operator for unsigned integers rounds down, but it's also useful to have division that rounds up. You often see it done like this:

// div round up -> (numerator + (denominator - 1)) / denominator
const num_bytes = (bits + 7) / 8;

However, this will break if (numerator + (denominator - 1)) overflows, so for the general case you need something like this:

fn divCeil(numerator: var, denominator: var) @TypeOf(numerator) {
    const quot = @divTrunc(numerator, denominator);
    const rem = @rem(numerator, denominator);
    const round_up = @intCast(@TypeOf(numerator), @boolToInt(rem > 0));
    return quot + round_up;
}

I'm not sure if you'd want it as a builtin @divCeil or under std.math.divCeil.

Metadata

Metadata

Assignees

No one assigned

    Labels

    proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions