Zig 0.17.0-dev (Split by item)

This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig library itself.

div_u32

int.div_u32
inline fn div_u32(n: u32, d: u32) u32

File

lib/compiler_rt/int.zig:303

Code

inline fn div_u32(n: u32, d: u32) u32 {
    const n_uword_bits: c_uint = 32;
    // special cases
    if (d == 0) return 0; // ?!
    if (n == 0) return 0;
    var sr = @as(c_uint, @bitCast(@as(c_int, @clz(d)) - @as(c_int, @clz(n))));
    // 0 <= sr <= n_uword_bits - 1 or sr large
    if (sr > n_uword_bits - 1) {
        // d > r
        return 0;
    }
    if (sr == n_uword_bits - 1) {
        // d == 1
        return n;
    }
    sr += 1;
    // 1 <= sr <= n_uword_bits - 1
    // Not a special case
    var q: u32 = n << @intCast(n_uword_bits - sr);
    var r: u32 = n >> @intCast(sr);
    var carry: u32 = 0;
    while (sr > 0) : (sr -= 1) {
        // r:q = ((r:q)  << 1) | carry
        r = (r << 1) | (q >> @intCast(n_uword_bits - 1));
        q = (q << 1) | carry;
        // carry = 0;
        // if (r.all >= d.all)
        // {
        //      r.all -= d.all;
        //      carry = 1;
        // }
        const s = @as(i32, @bitCast(d -% r -% 1)) >> @intCast(n_uword_bits - 1);
        carry = @intCast(s & 1);
        r -= d & @as(u32, @bitCast(s));
    }
    q = (q << 1) | carry;
    return q;
}