ziglint icon indicating copy to clipboard operation
ziglint copied to clipboard

new rule: having else block where then block ends with return

Open nektro opened this issue 3 years ago • 1 comments

fn sqrt_int(comptime T: type, value: T) Sqrt(T) {
    if (@typeInfo(T).Int.bits <= 2) {
        return if (value == 0) 0 else 1; // shortcut for small number of bits to simplify general case
    } else {
        var op = value;
        var res: T = 0;
        var one: T = 1 << ((@typeInfo(T).Int.bits - 1) & -2); // highest power of four that fits into T

        // "one" starts at the highest power of four <= than the argument.
        while (one > op) {
            one >>= 2;
        }

        while (one != 0) {
            var c = op >= res + one;
            if (c) op -= res + one;
            res >>= 1;
            if (c) res += one;
            one >>= 2;
        }

        return @intCast(Sqrt(T), res);
    }
}
./test.zig:4:6: remove else block when final statement of if is return

nektro avatar Dec 10 '22 04:12 nektro

this is to promote code that "fails early" and doesn't pollute the function with unnecessary indentation that hurts readability

fn sqrt_int(comptime T: type, value: T) Sqrt(T) {
    if (@typeInfo(T).Int.bits <= 2) {
        return if (value == 0) 0 else 1; // shortcut for small number of bits to simplify general case
    }

    var op = value;
    var res: T = 0;
    var one: T = 1 << ((@typeInfo(T).Int.bits - 1) & -2); // highest power of four that fits into T

    // "one" starts at the highest power of four <= than the argument.
    while (one > op) {
        one >>= 2;
    }

    while (one != 0) {
        var c = op >= res + one;
        if (c) op -= res + one;
        res >>= 1;
        if (c) res += one;
        one >>= 2;
    }

    return @intCast(Sqrt(T), res);
}

nektro avatar Dec 20 '22 21:12 nektro