ajhahn.de
← Flash
Flash 46 lines
// math — integer bounds, in pure Flash.
//
// `minInt` / `maxInt` mirror Zig's `std.math` bounds: the smallest and
// largest value of an integer type as a comptime_int, computed from the
// type's own bit width so the result is exact at any width and no
// negation can overflow.

use "base"

// The smallest value representable by the integer type `T`.
pub fn minInt(comptime T type) comptime_int {
    info := #typeInfo(T).int
    if info.signedness == .signed {
        return -(1 << (info.bits - 1))
    }
    return 0
}

// The largest value representable by the integer type `T`.
pub fn maxInt(comptime T type) comptime_int {
    info := #typeInfo(T).int
    if info.signedness == .signed {
        return (1 << (info.bits - 1)) - 1
    }
    return (1 << info.bits) - 1
}

test "minInt spans signed and unsigned widths" {
    try base.expectEqual(0, minInt(u8))
    try base.expectEqual(0, minInt(usize))
    try base.expectEqual(-128, minInt(i8))
    try base.expectEqual(-32768, minInt(i16))
    const min i128 = minInt(i128)
    try base.expectEqual(-170141183460469231731687303715884105728, min)
}

test "maxInt spans signed and unsigned widths" {
    try base.expectEqual(255, maxInt(u8))
    try base.expectEqual(127, maxInt(i8))
    try base.expectEqual(32767, maxInt(i16))
    try base.expectEqual(0, maxInt(u0))
    try base.expectEqual(18446744073709551615, maxInt(u64))
    const max i128 = maxInt(i128)
    try base.expectEqual(170141183460469231731687303715884105727, max)
}