zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

blob 9bc5d75a (48680B) - Raw


      1 // SPDX-License-Identifier: MIT
      2 // Copyright (c) 2015-2021 Zig Contributors
      3 // This file is part of [zig](https://ziglang.org/), which is MIT licensed.
      4 // The MIT license requires this copyright notice to be included in all copies
      5 // and substantial portions of the software.
      6 const std = @import("std.zig");
      7 const assert = std.debug.assert;
      8 const mem = std.mem;
      9 const testing = std.testing;
     10 
     11 /// Euler's number (e)
     12 pub const e = 2.71828182845904523536028747135266249775724709369995;
     13 
     14 /// Archimedes' constant (π)
     15 pub const pi = 3.14159265358979323846264338327950288419716939937510;
     16 
     17 /// Circle constant (τ)
     18 pub const tau = 2 * pi;
     19 
     20 /// log2(e)
     21 pub const log2e = 1.442695040888963407359924681001892137;
     22 
     23 /// log10(e)
     24 pub const log10e = 0.434294481903251827651128918916605082;
     25 
     26 /// ln(2)
     27 pub const ln2 = 0.693147180559945309417232121458176568;
     28 
     29 /// ln(10)
     30 pub const ln10 = 2.302585092994045684017991454684364208;
     31 
     32 /// 2/sqrt(π)
     33 pub const two_sqrtpi = 1.128379167095512573896158903121545172;
     34 
     35 /// sqrt(2)
     36 pub const sqrt2 = 1.414213562373095048801688724209698079;
     37 
     38 /// 1/sqrt(2)
     39 pub const sqrt1_2 = 0.707106781186547524400844362104849039;
     40 
     41 // From a small c++ [program using boost float128](https://github.com/winksaville/cpp_boost_float128)
     42 pub const f128_true_min = @bitCast(f128, @as(u128, 0x00000000000000000000000000000001));
     43 pub const f128_min = @bitCast(f128, @as(u128, 0x00010000000000000000000000000000));
     44 pub const f128_max = @bitCast(f128, @as(u128, 0x7FFEFFFFFFFFFFFFFFFFFFFFFFFFFFFF));
     45 pub const f128_epsilon = @bitCast(f128, @as(u128, 0x3F8F0000000000000000000000000000));
     46 pub const f128_toint = 1.0 / f128_epsilon;
     47 
     48 // float.h details
     49 pub const f64_true_min = 4.94065645841246544177e-324;
     50 pub const f64_min = 2.2250738585072014e-308;
     51 pub const f64_max = 1.79769313486231570815e+308;
     52 pub const f64_epsilon = 2.22044604925031308085e-16;
     53 pub const f64_toint = 1.0 / f64_epsilon;
     54 
     55 pub const f32_true_min = 1.40129846432481707092e-45;
     56 pub const f32_min = 1.17549435082228750797e-38;
     57 pub const f32_max = 3.40282346638528859812e+38;
     58 pub const f32_epsilon = 1.1920928955078125e-07;
     59 pub const f32_toint = 1.0 / f32_epsilon;
     60 
     61 pub const f16_true_min = 0.000000059604644775390625; // 2**-24
     62 pub const f16_min = 0.00006103515625; // 2**-14
     63 pub const f16_max = 65504;
     64 pub const f16_epsilon = 0.0009765625; // 2**-10
     65 pub const f16_toint = 1.0 / f16_epsilon;
     66 
     67 pub const epsilon = @import("math/epsilon.zig").epsilon;
     68 
     69 pub const nan_u16 = @as(u16, 0x7C01);
     70 pub const nan_f16 = @bitCast(f16, nan_u16);
     71 
     72 pub const qnan_u16 = @as(u16, 0x7E00);
     73 pub const qnan_f16 = @bitCast(f16, qnan_u16);
     74 
     75 pub const inf_u16 = @as(u16, 0x7C00);
     76 pub const inf_f16 = @bitCast(f16, inf_u16);
     77 
     78 pub const nan_u32 = @as(u32, 0x7F800001);
     79 pub const nan_f32 = @bitCast(f32, nan_u32);
     80 
     81 pub const qnan_u32 = @as(u32, 0x7FC00000);
     82 pub const qnan_f32 = @bitCast(f32, qnan_u32);
     83 
     84 pub const inf_u32 = @as(u32, 0x7F800000);
     85 pub const inf_f32 = @bitCast(f32, inf_u32);
     86 
     87 pub const nan_u64 = @as(u64, 0x7FF << 52) | 1;
     88 pub const nan_f64 = @bitCast(f64, nan_u64);
     89 
     90 pub const qnan_u64 = @as(u64, 0x7ff8000000000000);
     91 pub const qnan_f64 = @bitCast(f64, qnan_u64);
     92 
     93 pub const inf_u64 = @as(u64, 0x7FF << 52);
     94 pub const inf_f64 = @bitCast(f64, inf_u64);
     95 
     96 pub const nan_u128 = @as(u128, 0x7fff0000000000000000000000000001);
     97 pub const nan_f128 = @bitCast(f128, nan_u128);
     98 
     99 pub const qnan_u128 = @as(u128, 0x7fff8000000000000000000000000000);
    100 pub const qnan_f128 = @bitCast(f128, qnan_u128);
    101 
    102 pub const inf_u128 = @as(u128, 0x7fff0000000000000000000000000000);
    103 pub const inf_f128 = @bitCast(f128, inf_u128);
    104 
    105 pub const nan = @import("math/nan.zig").nan;
    106 pub const snan = @import("math/nan.zig").snan;
    107 pub const inf = @import("math/inf.zig").inf;
    108 
    109 /// Performs an approximate comparison of two floating point values `x` and `y`.
    110 /// Returns true if the absolute difference between them is less or equal than
    111 /// the specified tolerance.
    112 ///
    113 /// The `tolerance` parameter is the absolute tolerance used when determining if
    114 /// the two numbers are close enough, a good value for this parameter is a small
    115 /// multiple of `epsilon(T)`.
    116 ///
    117 /// Note that this function is recommended for for comparing small numbers
    118 /// around zero, using `approxEqRel` is suggested otherwise.
    119 ///
    120 /// NaN values are never considered equal to any value.
    121 pub fn approxEqAbs(comptime T: type, x: T, y: T, tolerance: T) bool {
    122     assert(@typeInfo(T) == .Float);
    123     assert(tolerance >= 0);
    124 
    125     // Fast path for equal values (and signed zeros and infinites).
    126     if (x == y)
    127         return true;
    128 
    129     if (isNan(x) or isNan(y))
    130         return false;
    131 
    132     return fabs(x - y) <= tolerance;
    133 }
    134 
    135 /// Performs an approximate comparison of two floating point values `x` and `y`.
    136 /// Returns true if the absolute difference between them is less or equal than
    137 /// `max(|x|, |y|) * tolerance`, where `tolerance` is a positive number greater
    138 /// than zero.
    139 ///
    140 /// The `tolerance` parameter is the relative tolerance used when determining if
    141 /// the two numbers are close enough, a good value for this parameter is usually
    142 /// `sqrt(epsilon(T))`, meaning that the two numbers are considered equal if at
    143 /// least half of the digits are equal.
    144 ///
    145 /// Note that for comparisons of small numbers around zero this function won't
    146 /// give meaningful results, use `approxEqAbs` instead.
    147 ///
    148 /// NaN values are never considered equal to any value.
    149 pub fn approxEqRel(comptime T: type, x: T, y: T, tolerance: T) bool {
    150     assert(@typeInfo(T) == .Float);
    151     assert(tolerance > 0);
    152 
    153     // Fast path for equal values (and signed zeros and infinites).
    154     if (x == y)
    155         return true;
    156 
    157     if (isNan(x) or isNan(y))
    158         return false;
    159 
    160     return fabs(x - y) <= max(fabs(x), fabs(y)) * tolerance;
    161 }
    162 
    163 /// Deprecated, use `approxEqAbs` or `approxEqRel`.
    164 pub const approxEq = approxEqAbs;
    165 
    166 test "approxEqAbs and approxEqRel" {
    167     inline for ([_]type{ f16, f32, f64, f128 }) |T| {
    168         const eps_value = comptime epsilon(T);
    169         const sqrt_eps_value = comptime sqrt(eps_value);
    170         const nan_value = comptime nan(T);
    171         const inf_value = comptime inf(T);
    172         const min_value: T = switch (T) {
    173             f16 => f16_min,
    174             f32 => f32_min,
    175             f64 => f64_min,
    176             f128 => f128_min,
    177             else => unreachable,
    178         };
    179 
    180         testing.expect(approxEqAbs(T, 0.0, 0.0, eps_value));
    181         testing.expect(approxEqAbs(T, -0.0, -0.0, eps_value));
    182         testing.expect(approxEqAbs(T, 0.0, -0.0, eps_value));
    183         testing.expect(approxEqRel(T, 1.0, 1.0, sqrt_eps_value));
    184         testing.expect(!approxEqRel(T, 1.0, 0.0, sqrt_eps_value));
    185         testing.expect(!approxEqAbs(T, 1.0 + 2 * epsilon(T), 1.0, eps_value));
    186         testing.expect(approxEqAbs(T, 1.0 + 1 * epsilon(T), 1.0, eps_value));
    187         testing.expect(!approxEqRel(T, 1.0, nan_value, sqrt_eps_value));
    188         testing.expect(!approxEqRel(T, nan_value, nan_value, sqrt_eps_value));
    189         testing.expect(approxEqRel(T, inf_value, inf_value, sqrt_eps_value));
    190         testing.expect(approxEqRel(T, min_value, min_value, sqrt_eps_value));
    191         testing.expect(approxEqRel(T, -min_value, -min_value, sqrt_eps_value));
    192         testing.expect(approxEqAbs(T, min_value, 0.0, eps_value * 2));
    193         testing.expect(approxEqAbs(T, -min_value, 0.0, eps_value * 2));
    194     }
    195 }
    196 
    197 pub fn doNotOptimizeAway(value: anytype) void {
    198     // TODO: use @declareSideEffect() when it is available.
    199     // https://github.com/ziglang/zig/issues/6168
    200     const T = @TypeOf(value);
    201     var x: T = undefined;
    202     const p = @ptrCast(*volatile T, &x);
    203     p.* = x;
    204 }
    205 
    206 pub fn raiseInvalid() void {
    207     // Raise INVALID fpu exception
    208 }
    209 
    210 pub fn raiseUnderflow() void {
    211     // Raise UNDERFLOW fpu exception
    212 }
    213 
    214 pub fn raiseOverflow() void {
    215     // Raise OVERFLOW fpu exception
    216 }
    217 
    218 pub fn raiseInexact() void {
    219     // Raise INEXACT fpu exception
    220 }
    221 
    222 pub fn raiseDivByZero() void {
    223     // Raise INEXACT fpu exception
    224 }
    225 
    226 pub const isNan = @import("math/isnan.zig").isNan;
    227 pub const isSignalNan = @import("math/isnan.zig").isSignalNan;
    228 pub const fabs = @import("math/fabs.zig").fabs;
    229 pub const ceil = @import("math/ceil.zig").ceil;
    230 pub const floor = @import("math/floor.zig").floor;
    231 pub const trunc = @import("math/trunc.zig").trunc;
    232 pub const round = @import("math/round.zig").round;
    233 pub const frexp = @import("math/frexp.zig").frexp;
    234 pub const frexp32_result = @import("math/frexp.zig").frexp32_result;
    235 pub const frexp64_result = @import("math/frexp.zig").frexp64_result;
    236 pub const modf = @import("math/modf.zig").modf;
    237 pub const modf32_result = @import("math/modf.zig").modf32_result;
    238 pub const modf64_result = @import("math/modf.zig").modf64_result;
    239 pub const copysign = @import("math/copysign.zig").copysign;
    240 pub const isFinite = @import("math/isfinite.zig").isFinite;
    241 pub const isInf = @import("math/isinf.zig").isInf;
    242 pub const isPositiveInf = @import("math/isinf.zig").isPositiveInf;
    243 pub const isNegativeInf = @import("math/isinf.zig").isNegativeInf;
    244 pub const isNormal = @import("math/isnormal.zig").isNormal;
    245 pub const signbit = @import("math/signbit.zig").signbit;
    246 pub const scalbn = @import("math/scalbn.zig").scalbn;
    247 pub const pow = @import("math/pow.zig").pow;
    248 pub const powi = @import("math/powi.zig").powi;
    249 pub const sqrt = @import("math/sqrt.zig").sqrt;
    250 pub const cbrt = @import("math/cbrt.zig").cbrt;
    251 pub const acos = @import("math/acos.zig").acos;
    252 pub const asin = @import("math/asin.zig").asin;
    253 pub const atan = @import("math/atan.zig").atan;
    254 pub const atan2 = @import("math/atan2.zig").atan2;
    255 pub const hypot = @import("math/hypot.zig").hypot;
    256 pub const exp = @import("math/exp.zig").exp;
    257 pub const exp2 = @import("math/exp2.zig").exp2;
    258 pub const expm1 = @import("math/expm1.zig").expm1;
    259 pub const ilogb = @import("math/ilogb.zig").ilogb;
    260 pub const ln = @import("math/ln.zig").ln;
    261 pub const log = @import("math/log.zig").log;
    262 pub const log2 = @import("math/log2.zig").log2;
    263 pub const log10 = @import("math/log10.zig").log10;
    264 pub const log1p = @import("math/log1p.zig").log1p;
    265 pub const fma = @import("math/fma.zig").fma;
    266 pub const asinh = @import("math/asinh.zig").asinh;
    267 pub const acosh = @import("math/acosh.zig").acosh;
    268 pub const atanh = @import("math/atanh.zig").atanh;
    269 pub const sinh = @import("math/sinh.zig").sinh;
    270 pub const cosh = @import("math/cosh.zig").cosh;
    271 pub const tanh = @import("math/tanh.zig").tanh;
    272 pub const cos = @import("math/cos.zig").cos;
    273 pub const sin = @import("math/sin.zig").sin;
    274 pub const tan = @import("math/tan.zig").tan;
    275 
    276 pub const complex = @import("math/complex.zig");
    277 pub const Complex = complex.Complex;
    278 
    279 pub const big = @import("math/big.zig");
    280 
    281 test "" {
    282     std.testing.refAllDecls(@This());
    283 }
    284 
    285 pub fn floatMantissaBits(comptime T: type) comptime_int {
    286     assert(@typeInfo(T) == .Float);
    287 
    288     return switch (@typeInfo(T).Float.bits) {
    289         16 => 10,
    290         32 => 23,
    291         64 => 52,
    292         80 => 64,
    293         128 => 112,
    294         else => @compileError("unknown floating point type " ++ @typeName(T)),
    295     };
    296 }
    297 
    298 pub fn floatExponentBits(comptime T: type) comptime_int {
    299     assert(@typeInfo(T) == .Float);
    300 
    301     return switch (@typeInfo(T).Float.bits) {
    302         16 => 5,
    303         32 => 8,
    304         64 => 11,
    305         80 => 15,
    306         128 => 15,
    307         else => @compileError("unknown floating point type " ++ @typeName(T)),
    308     };
    309 }
    310 
    311 /// Given two types, returns the smallest one which is capable of holding the
    312 /// full range of the minimum value.
    313 pub fn Min(comptime A: type, comptime B: type) type {
    314     switch (@typeInfo(A)) {
    315         .Int => |a_info| switch (@typeInfo(B)) {
    316             .Int => |b_info| if (a_info.signedness == .unsigned and b_info.signedness == .unsigned) {
    317                 if (a_info.bits < b_info.bits) {
    318                     return A;
    319                 } else {
    320                     return B;
    321                 }
    322             },
    323             else => {},
    324         },
    325         else => {},
    326     }
    327     return @TypeOf(@as(A, 0) + @as(B, 0));
    328 }
    329 
    330 /// Returns the smaller number. When one of the parameter's type's full range fits in the other,
    331 /// the return type is the smaller type.
    332 pub fn min(x: anytype, y: anytype) Min(@TypeOf(x), @TypeOf(y)) {
    333     const Result = Min(@TypeOf(x), @TypeOf(y));
    334     if (x < y) {
    335         // TODO Zig should allow this as an implicit cast because x is immutable and in this
    336         // scope it is known to fit in the return type.
    337         switch (@typeInfo(Result)) {
    338             .Int => return @intCast(Result, x),
    339             else => return x,
    340         }
    341     } else {
    342         // TODO Zig should allow this as an implicit cast because y is immutable and in this
    343         // scope it is known to fit in the return type.
    344         switch (@typeInfo(Result)) {
    345             .Int => return @intCast(Result, y),
    346             else => return y,
    347         }
    348     }
    349 }
    350 
    351 test "math.min" {
    352     testing.expect(min(@as(i32, -1), @as(i32, 2)) == -1);
    353     {
    354         var a: u16 = 999;
    355         var b: u32 = 10;
    356         var result = min(a, b);
    357         testing.expect(@TypeOf(result) == u16);
    358         testing.expect(result == 10);
    359     }
    360     {
    361         var a: f64 = 10.34;
    362         var b: f32 = 999.12;
    363         var result = min(a, b);
    364         testing.expect(@TypeOf(result) == f64);
    365         testing.expect(result == 10.34);
    366     }
    367     {
    368         var a: i8 = -127;
    369         var b: i16 = -200;
    370         var result = min(a, b);
    371         testing.expect(@TypeOf(result) == i16);
    372         testing.expect(result == -200);
    373     }
    374     {
    375         const a = 10.34;
    376         var b: f32 = 999.12;
    377         var result = min(a, b);
    378         testing.expect(@TypeOf(result) == f32);
    379         testing.expect(result == 10.34);
    380     }
    381 }
    382 
    383 pub fn max(x: anytype, y: anytype) @TypeOf(x, y) {
    384     return if (x > y) x else y;
    385 }
    386 
    387 test "math.max" {
    388     testing.expect(max(@as(i32, -1), @as(i32, 2)) == 2);
    389 }
    390 
    391 pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper) {
    392     assert(lower <= upper);
    393     return max(lower, min(val, upper));
    394 }
    395 test "math.clamp" {
    396     // Within range
    397     testing.expect(std.math.clamp(@as(i32, -1), @as(i32, -4), @as(i32, 7)) == -1);
    398     // Below
    399     testing.expect(std.math.clamp(@as(i32, -5), @as(i32, -4), @as(i32, 7)) == -4);
    400     // Above
    401     testing.expect(std.math.clamp(@as(i32, 8), @as(i32, -4), @as(i32, 7)) == 7);
    402 
    403     // Floating point
    404     testing.expect(std.math.clamp(@as(f32, 1.1), @as(f32, 0.0), @as(f32, 1.0)) == 1.0);
    405     testing.expect(std.math.clamp(@as(f32, -127.5), @as(f32, -200), @as(f32, -100)) == -127.5);
    406 
    407     // Mix of comptime and non-comptime
    408     var i: i32 = 1;
    409     testing.expect(std.math.clamp(i, 0, 1) == 1);
    410 }
    411 
    412 pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T) {
    413     var answer: T = undefined;
    414     return if (@mulWithOverflow(T, a, b, &answer)) error.Overflow else answer;
    415 }
    416 
    417 pub fn add(comptime T: type, a: T, b: T) (error{Overflow}!T) {
    418     var answer: T = undefined;
    419     return if (@addWithOverflow(T, a, b, &answer)) error.Overflow else answer;
    420 }
    421 
    422 pub fn sub(comptime T: type, a: T, b: T) (error{Overflow}!T) {
    423     var answer: T = undefined;
    424     return if (@subWithOverflow(T, a, b, &answer)) error.Overflow else answer;
    425 }
    426 
    427 pub fn negate(x: anytype) !@TypeOf(x) {
    428     return sub(@TypeOf(x), 0, x);
    429 }
    430 
    431 pub fn shlExact(comptime T: type, a: T, shift_amt: Log2Int(T)) !T {
    432     var answer: T = undefined;
    433     return if (@shlWithOverflow(T, a, shift_amt, &answer)) error.Overflow else answer;
    434 }
    435 
    436 /// Shifts left. Overflowed bits are truncated.
    437 /// A negative shift amount results in a right shift.
    438 pub fn shl(comptime T: type, a: T, shift_amt: anytype) T {
    439     const abs_shift_amt = absCast(shift_amt);
    440 
    441     const casted_shift_amt = blk: {
    442         if (@typeInfo(T) == .Vector) {
    443             const C = @typeInfo(T).Vector.child;
    444             const len = @typeInfo(T).Vector.len;
    445             if (abs_shift_amt >= @typeInfo(C).Int.bits) return @splat(len, @as(C, 0));
    446             break :blk @splat(len, @intCast(Log2Int(C), abs_shift_amt));
    447         } else {
    448             if (abs_shift_amt >= @typeInfo(T).Int.bits) return 0;
    449             break :blk @intCast(Log2Int(T), abs_shift_amt);
    450         }
    451     };
    452 
    453     if (@TypeOf(shift_amt) == comptime_int or @typeInfo(@TypeOf(shift_amt)).Int.signedness == .signed) {
    454         if (shift_amt < 0) {
    455             return a >> casted_shift_amt;
    456         }
    457     }
    458 
    459     return a << casted_shift_amt;
    460 }
    461 
    462 test "math.shl" {
    463     testing.expect(shl(u8, 0b11111111, @as(usize, 3)) == 0b11111000);
    464     testing.expect(shl(u8, 0b11111111, @as(usize, 8)) == 0);
    465     testing.expect(shl(u8, 0b11111111, @as(usize, 9)) == 0);
    466     testing.expect(shl(u8, 0b11111111, @as(isize, -2)) == 0b00111111);
    467     testing.expect(shl(u8, 0b11111111, 3) == 0b11111000);
    468     testing.expect(shl(u8, 0b11111111, 8) == 0);
    469     testing.expect(shl(u8, 0b11111111, 9) == 0);
    470     testing.expect(shl(u8, 0b11111111, -2) == 0b00111111);
    471     testing.expect(shl(std.meta.Vector(1, u32), std.meta.Vector(1, u32){42}, @as(usize, 1))[0] == @as(u32, 42) << 1);
    472     testing.expect(shl(std.meta.Vector(1, u32), std.meta.Vector(1, u32){42}, @as(isize, -1))[0] == @as(u32, 42) >> 1);
    473     testing.expect(shl(std.meta.Vector(1, u32), std.meta.Vector(1, u32){42}, 33)[0] == 0);
    474 }
    475 
    476 /// Shifts right. Overflowed bits are truncated.
    477 /// A negative shift amount results in a left shift.
    478 pub fn shr(comptime T: type, a: T, shift_amt: anytype) T {
    479     const abs_shift_amt = absCast(shift_amt);
    480 
    481     const casted_shift_amt = blk: {
    482         if (@typeInfo(T) == .Vector) {
    483             const C = @typeInfo(T).Vector.child;
    484             const len = @typeInfo(T).Vector.len;
    485             if (abs_shift_amt >= @typeInfo(C).Int.bits) return @splat(len, @as(C, 0));
    486             break :blk @splat(len, @intCast(Log2Int(C), abs_shift_amt));
    487         } else {
    488             if (abs_shift_amt >= @typeInfo(T).Int.bits) return 0;
    489             break :blk @intCast(Log2Int(T), abs_shift_amt);
    490         }
    491     };
    492 
    493     if (@TypeOf(shift_amt) == comptime_int or @typeInfo(@TypeOf(shift_amt)).Int.signedness == .signed) {
    494         if (shift_amt < 0) {
    495             return a << casted_shift_amt;
    496         }
    497     }
    498 
    499     return a >> casted_shift_amt;
    500 }
    501 
    502 test "math.shr" {
    503     testing.expect(shr(u8, 0b11111111, @as(usize, 3)) == 0b00011111);
    504     testing.expect(shr(u8, 0b11111111, @as(usize, 8)) == 0);
    505     testing.expect(shr(u8, 0b11111111, @as(usize, 9)) == 0);
    506     testing.expect(shr(u8, 0b11111111, @as(isize, -2)) == 0b11111100);
    507     testing.expect(shr(u8, 0b11111111, 3) == 0b00011111);
    508     testing.expect(shr(u8, 0b11111111, 8) == 0);
    509     testing.expect(shr(u8, 0b11111111, 9) == 0);
    510     testing.expect(shr(u8, 0b11111111, -2) == 0b11111100);
    511     testing.expect(shr(std.meta.Vector(1, u32), std.meta.Vector(1, u32){42}, @as(usize, 1))[0] == @as(u32, 42) >> 1);
    512     testing.expect(shr(std.meta.Vector(1, u32), std.meta.Vector(1, u32){42}, @as(isize, -1))[0] == @as(u32, 42) << 1);
    513     testing.expect(shr(std.meta.Vector(1, u32), std.meta.Vector(1, u32){42}, 33)[0] == 0);
    514 }
    515 
    516 /// Rotates right. Only unsigned values can be rotated.
    517 /// Negative shift values results in shift modulo the bit count.
    518 pub fn rotr(comptime T: type, x: T, r: anytype) T {
    519     if (@typeInfo(T) == .Vector) {
    520         const C = @typeInfo(T).Vector.child;
    521         if (@typeInfo(C).Int.signedness == .signed) {
    522             @compileError("cannot rotate signed integers");
    523         }
    524         const ar = @intCast(Log2Int(C), @mod(r, @typeInfo(C).Int.bits));
    525         return (x >> @splat(@typeInfo(T).Vector.len, ar)) | (x << @splat(@typeInfo(T).Vector.len, 1 + ~ar));
    526     } else if (@typeInfo(T).Int.signedness == .signed) {
    527         @compileError("cannot rotate signed integer");
    528     } else {
    529         const ar = @mod(r, @typeInfo(T).Int.bits);
    530         return shr(T, x, ar) | shl(T, x, @typeInfo(T).Int.bits - ar);
    531     }
    532 }
    533 
    534 test "math.rotr" {
    535     testing.expect(rotr(u8, 0b00000001, @as(usize, 0)) == 0b00000001);
    536     testing.expect(rotr(u8, 0b00000001, @as(usize, 9)) == 0b10000000);
    537     testing.expect(rotr(u8, 0b00000001, @as(usize, 8)) == 0b00000001);
    538     testing.expect(rotr(u8, 0b00000001, @as(usize, 4)) == 0b00010000);
    539     testing.expect(rotr(u8, 0b00000001, @as(isize, -1)) == 0b00000010);
    540     testing.expect(rotr(std.meta.Vector(1, u32), std.meta.Vector(1, u32){1}, @as(usize, 1))[0] == @as(u32, 1) << 31);
    541     testing.expect(rotr(std.meta.Vector(1, u32), std.meta.Vector(1, u32){1}, @as(isize, -1))[0] == @as(u32, 1) << 1);
    542 }
    543 
    544 /// Rotates left. Only unsigned values can be rotated.
    545 /// Negative shift values results in shift modulo the bit count.
    546 pub fn rotl(comptime T: type, x: T, r: anytype) T {
    547     if (@typeInfo(T) == .Vector) {
    548         const C = @typeInfo(T).Vector.child;
    549         if (@typeInfo(C).Int.signedness == .signed) {
    550             @compileError("cannot rotate signed integers");
    551         }
    552         const ar = @intCast(Log2Int(C), @mod(r, @typeInfo(C).Int.bits));
    553         return (x << @splat(@typeInfo(T).Vector.len, ar)) | (x >> @splat(@typeInfo(T).Vector.len, 1 +% ~ar));
    554     } else if (@typeInfo(T).Int.signedness == .signed) {
    555         @compileError("cannot rotate signed integer");
    556     } else {
    557         const ar = @mod(r, @typeInfo(T).Int.bits);
    558         return shl(T, x, ar) | shr(T, x, @typeInfo(T).Int.bits - ar);
    559     }
    560 }
    561 
    562 test "math.rotl" {
    563     testing.expect(rotl(u8, 0b00000001, @as(usize, 0)) == 0b00000001);
    564     testing.expect(rotl(u8, 0b00000001, @as(usize, 9)) == 0b00000010);
    565     testing.expect(rotl(u8, 0b00000001, @as(usize, 8)) == 0b00000001);
    566     testing.expect(rotl(u8, 0b00000001, @as(usize, 4)) == 0b00010000);
    567     testing.expect(rotl(u8, 0b00000001, @as(isize, -1)) == 0b10000000);
    568     testing.expect(rotl(std.meta.Vector(1, u32), std.meta.Vector(1, u32){1 << 31}, @as(usize, 1))[0] == 1);
    569     testing.expect(rotl(std.meta.Vector(1, u32), std.meta.Vector(1, u32){1 << 31}, @as(isize, -1))[0] == @as(u32, 1) << 30);
    570 }
    571 
    572 pub fn Log2Int(comptime T: type) type {
    573     // comptime ceil log2
    574     comptime var count = 0;
    575     comptime var s = @typeInfo(T).Int.bits - 1;
    576     inline while (s != 0) : (s >>= 1) {
    577         count += 1;
    578     }
    579 
    580     return std.meta.Int(.unsigned, count);
    581 }
    582 
    583 pub fn IntFittingRange(comptime from: comptime_int, comptime to: comptime_int) type {
    584     assert(from <= to);
    585     if (from == 0 and to == 0) {
    586         return u0;
    587     }
    588     const sign: std.builtin.Signedness = if (from < 0) .signed else .unsigned;
    589     const largest_positive_integer = max(if (from < 0) (-from) - 1 else from, to); // two's complement
    590     const base = log2(largest_positive_integer);
    591     const upper = (1 << base) - 1;
    592     var magnitude_bits = if (upper >= largest_positive_integer) base else base + 1;
    593     if (sign == .signed) {
    594         magnitude_bits += 1;
    595     }
    596     return std.meta.Int(sign, magnitude_bits);
    597 }
    598 
    599 test "math.IntFittingRange" {
    600     testing.expect(IntFittingRange(0, 0) == u0);
    601     testing.expect(IntFittingRange(0, 1) == u1);
    602     testing.expect(IntFittingRange(0, 2) == u2);
    603     testing.expect(IntFittingRange(0, 3) == u2);
    604     testing.expect(IntFittingRange(0, 4) == u3);
    605     testing.expect(IntFittingRange(0, 7) == u3);
    606     testing.expect(IntFittingRange(0, 8) == u4);
    607     testing.expect(IntFittingRange(0, 9) == u4);
    608     testing.expect(IntFittingRange(0, 15) == u4);
    609     testing.expect(IntFittingRange(0, 16) == u5);
    610     testing.expect(IntFittingRange(0, 17) == u5);
    611     testing.expect(IntFittingRange(0, 4095) == u12);
    612     testing.expect(IntFittingRange(2000, 4095) == u12);
    613     testing.expect(IntFittingRange(0, 4096) == u13);
    614     testing.expect(IntFittingRange(2000, 4096) == u13);
    615     testing.expect(IntFittingRange(0, 4097) == u13);
    616     testing.expect(IntFittingRange(2000, 4097) == u13);
    617     testing.expect(IntFittingRange(0, 123456789123456798123456789) == u87);
    618     testing.expect(IntFittingRange(0, 123456789123456798123456789123456789123456798123456789) == u177);
    619 
    620     testing.expect(IntFittingRange(-1, -1) == i1);
    621     testing.expect(IntFittingRange(-1, 0) == i1);
    622     testing.expect(IntFittingRange(-1, 1) == i2);
    623     testing.expect(IntFittingRange(-2, -2) == i2);
    624     testing.expect(IntFittingRange(-2, -1) == i2);
    625     testing.expect(IntFittingRange(-2, 0) == i2);
    626     testing.expect(IntFittingRange(-2, 1) == i2);
    627     testing.expect(IntFittingRange(-2, 2) == i3);
    628     testing.expect(IntFittingRange(-1, 2) == i3);
    629     testing.expect(IntFittingRange(-1, 3) == i3);
    630     testing.expect(IntFittingRange(-1, 4) == i4);
    631     testing.expect(IntFittingRange(-1, 7) == i4);
    632     testing.expect(IntFittingRange(-1, 8) == i5);
    633     testing.expect(IntFittingRange(-1, 9) == i5);
    634     testing.expect(IntFittingRange(-1, 15) == i5);
    635     testing.expect(IntFittingRange(-1, 16) == i6);
    636     testing.expect(IntFittingRange(-1, 17) == i6);
    637     testing.expect(IntFittingRange(-1, 4095) == i13);
    638     testing.expect(IntFittingRange(-4096, 4095) == i13);
    639     testing.expect(IntFittingRange(-1, 4096) == i14);
    640     testing.expect(IntFittingRange(-4097, 4095) == i14);
    641     testing.expect(IntFittingRange(-1, 4097) == i14);
    642     testing.expect(IntFittingRange(-1, 123456789123456798123456789) == i88);
    643     testing.expect(IntFittingRange(-1, 123456789123456798123456789123456789123456798123456789) == i178);
    644 }
    645 
    646 test "math overflow functions" {
    647     testOverflow();
    648     comptime testOverflow();
    649 }
    650 
    651 fn testOverflow() void {
    652     testing.expect((mul(i32, 3, 4) catch unreachable) == 12);
    653     testing.expect((add(i32, 3, 4) catch unreachable) == 7);
    654     testing.expect((sub(i32, 3, 4) catch unreachable) == -1);
    655     testing.expect((shlExact(i32, 0b11, 4) catch unreachable) == 0b110000);
    656 }
    657 
    658 pub fn absInt(x: anytype) !@TypeOf(x) {
    659     const T = @TypeOf(x);
    660     comptime assert(@typeInfo(T) == .Int); // must pass an integer to absInt
    661     comptime assert(@typeInfo(T).Int.signedness == .signed); // must pass a signed integer to absInt
    662 
    663     if (x == minInt(@TypeOf(x))) {
    664         return error.Overflow;
    665     } else {
    666         @setRuntimeSafety(false);
    667         return if (x < 0) -x else x;
    668     }
    669 }
    670 
    671 test "math.absInt" {
    672     testAbsInt();
    673     comptime testAbsInt();
    674 }
    675 fn testAbsInt() void {
    676     testing.expect((absInt(@as(i32, -10)) catch unreachable) == 10);
    677     testing.expect((absInt(@as(i32, 10)) catch unreachable) == 10);
    678 }
    679 
    680 pub const absFloat = fabs;
    681 
    682 test "math.absFloat" {
    683     testAbsFloat();
    684     comptime testAbsFloat();
    685 }
    686 fn testAbsFloat() void {
    687     testing.expect(absFloat(@as(f32, -10.05)) == 10.05);
    688     testing.expect(absFloat(@as(f32, 10.05)) == 10.05);
    689 }
    690 
    691 pub fn divTrunc(comptime T: type, numerator: T, denominator: T) !T {
    692     @setRuntimeSafety(false);
    693     if (denominator == 0) return error.DivisionByZero;
    694     if (@typeInfo(T) == .Int and @typeInfo(T).Int.signedness == .signed and numerator == minInt(T) and denominator == -1) return error.Overflow;
    695     return @divTrunc(numerator, denominator);
    696 }
    697 
    698 test "math.divTrunc" {
    699     testDivTrunc();
    700     comptime testDivTrunc();
    701 }
    702 fn testDivTrunc() void {
    703     testing.expect((divTrunc(i32, 5, 3) catch unreachable) == 1);
    704     testing.expect((divTrunc(i32, -5, 3) catch unreachable) == -1);
    705     testing.expectError(error.DivisionByZero, divTrunc(i8, -5, 0));
    706     testing.expectError(error.Overflow, divTrunc(i8, -128, -1));
    707 
    708     testing.expect((divTrunc(f32, 5.0, 3.0) catch unreachable) == 1.0);
    709     testing.expect((divTrunc(f32, -5.0, 3.0) catch unreachable) == -1.0);
    710 }
    711 
    712 pub fn divFloor(comptime T: type, numerator: T, denominator: T) !T {
    713     @setRuntimeSafety(false);
    714     if (denominator == 0) return error.DivisionByZero;
    715     if (@typeInfo(T) == .Int and @typeInfo(T).Int.signedness == .signed and numerator == minInt(T) and denominator == -1) return error.Overflow;
    716     return @divFloor(numerator, denominator);
    717 }
    718 
    719 test "math.divFloor" {
    720     testDivFloor();
    721     comptime testDivFloor();
    722 }
    723 fn testDivFloor() void {
    724     testing.expect((divFloor(i32, 5, 3) catch unreachable) == 1);
    725     testing.expect((divFloor(i32, -5, 3) catch unreachable) == -2);
    726     testing.expectError(error.DivisionByZero, divFloor(i8, -5, 0));
    727     testing.expectError(error.Overflow, divFloor(i8, -128, -1));
    728 
    729     testing.expect((divFloor(f32, 5.0, 3.0) catch unreachable) == 1.0);
    730     testing.expect((divFloor(f32, -5.0, 3.0) catch unreachable) == -2.0);
    731 }
    732 
    733 pub fn divCeil(comptime T: type, numerator: T, denominator: T) !T {
    734     @setRuntimeSafety(false);
    735     if (comptime std.meta.trait.isNumber(T) and denominator == 0) return error.DivisionByZero;
    736     const info = @typeInfo(T);
    737     switch (info) {
    738         .ComptimeFloat, .Float => return @ceil(numerator / denominator),
    739         .ComptimeInt, .Int => {
    740             if (numerator < 0 and denominator < 0) {
    741                 if (info == .Int and numerator == minInt(T) and denominator == -1)
    742                     return error.Overflow;
    743                 return @divFloor(numerator + 1, denominator) + 1;
    744             }
    745             if (numerator > 0 and denominator > 0)
    746                 return @divFloor(numerator - 1, denominator) + 1;
    747             return @divTrunc(numerator, denominator);
    748         },
    749         else => @compileError("divCeil unsupported on " ++ @typeName(T)),
    750     }
    751 }
    752 
    753 test "math.divCeil" {
    754     testDivCeil();
    755     comptime testDivCeil();
    756 }
    757 fn testDivCeil() void {
    758     testing.expectEqual(@as(i32, 2), divCeil(i32, 5, 3) catch unreachable);
    759     testing.expectEqual(@as(i32, -1), divCeil(i32, -5, 3) catch unreachable);
    760     testing.expectEqual(@as(i32, -1), divCeil(i32, 5, -3) catch unreachable);
    761     testing.expectEqual(@as(i32, 2), divCeil(i32, -5, -3) catch unreachable);
    762     testing.expectEqual(@as(i32, 0), divCeil(i32, 0, 5) catch unreachable);
    763     testing.expectEqual(@as(u32, 0), divCeil(u32, 0, 5) catch unreachable);
    764     testing.expectError(error.DivisionByZero, divCeil(i8, -5, 0));
    765     testing.expectError(error.Overflow, divCeil(i8, -128, -1));
    766 
    767     testing.expectEqual(@as(f32, 0.0), divCeil(f32, 0.0, 5.0) catch unreachable);
    768     testing.expectEqual(@as(f32, 2.0), divCeil(f32, 5.0, 3.0) catch unreachable);
    769     testing.expectEqual(@as(f32, -1.0), divCeil(f32, -5.0, 3.0) catch unreachable);
    770     testing.expectEqual(@as(f32, -1.0), divCeil(f32, 5.0, -3.0) catch unreachable);
    771     testing.expectEqual(@as(f32, 2.0), divCeil(f32, -5.0, -3.0) catch unreachable);
    772 
    773     testing.expectEqual(6, divCeil(comptime_int, 23, 4) catch unreachable);
    774     testing.expectEqual(-5, divCeil(comptime_int, -23, 4) catch unreachable);
    775     testing.expectEqual(-5, divCeil(comptime_int, 23, -4) catch unreachable);
    776     testing.expectEqual(6, divCeil(comptime_int, -23, -4) catch unreachable);
    777     testing.expectError(error.DivisionByZero, divCeil(comptime_int, 23, 0));
    778 
    779     testing.expectEqual(6.0, divCeil(comptime_float, 23.0, 4.0) catch unreachable);
    780     testing.expectEqual(-5.0, divCeil(comptime_float, -23.0, 4.0) catch unreachable);
    781     testing.expectEqual(-5.0, divCeil(comptime_float, 23.0, -4.0) catch unreachable);
    782     testing.expectEqual(6.0, divCeil(comptime_float, -23.0, -4.0) catch unreachable);
    783     testing.expectError(error.DivisionByZero, divCeil(comptime_float, 23.0, 0.0));
    784 }
    785 
    786 pub fn divExact(comptime T: type, numerator: T, denominator: T) !T {
    787     @setRuntimeSafety(false);
    788     if (denominator == 0) return error.DivisionByZero;
    789     if (@typeInfo(T) == .Int and @typeInfo(T).Int.signedness == .signed and numerator == minInt(T) and denominator == -1) return error.Overflow;
    790     const result = @divTrunc(numerator, denominator);
    791     if (result * denominator != numerator) return error.UnexpectedRemainder;
    792     return result;
    793 }
    794 
    795 test "math.divExact" {
    796     testDivExact();
    797     comptime testDivExact();
    798 }
    799 fn testDivExact() void {
    800     testing.expect((divExact(i32, 10, 5) catch unreachable) == 2);
    801     testing.expect((divExact(i32, -10, 5) catch unreachable) == -2);
    802     testing.expectError(error.DivisionByZero, divExact(i8, -5, 0));
    803     testing.expectError(error.Overflow, divExact(i8, -128, -1));
    804     testing.expectError(error.UnexpectedRemainder, divExact(i32, 5, 2));
    805 
    806     testing.expect((divExact(f32, 10.0, 5.0) catch unreachable) == 2.0);
    807     testing.expect((divExact(f32, -10.0, 5.0) catch unreachable) == -2.0);
    808     testing.expectError(error.UnexpectedRemainder, divExact(f32, 5.0, 2.0));
    809 }
    810 
    811 pub fn mod(comptime T: type, numerator: T, denominator: T) !T {
    812     @setRuntimeSafety(false);
    813     if (denominator == 0) return error.DivisionByZero;
    814     if (denominator < 0) return error.NegativeDenominator;
    815     return @mod(numerator, denominator);
    816 }
    817 
    818 test "math.mod" {
    819     testMod();
    820     comptime testMod();
    821 }
    822 fn testMod() void {
    823     testing.expect((mod(i32, -5, 3) catch unreachable) == 1);
    824     testing.expect((mod(i32, 5, 3) catch unreachable) == 2);
    825     testing.expectError(error.NegativeDenominator, mod(i32, 10, -1));
    826     testing.expectError(error.DivisionByZero, mod(i32, 10, 0));
    827 
    828     testing.expect((mod(f32, -5, 3) catch unreachable) == 1);
    829     testing.expect((mod(f32, 5, 3) catch unreachable) == 2);
    830     testing.expectError(error.NegativeDenominator, mod(f32, 10, -1));
    831     testing.expectError(error.DivisionByZero, mod(f32, 10, 0));
    832 }
    833 
    834 pub fn rem(comptime T: type, numerator: T, denominator: T) !T {
    835     @setRuntimeSafety(false);
    836     if (denominator == 0) return error.DivisionByZero;
    837     if (denominator < 0) return error.NegativeDenominator;
    838     return @rem(numerator, denominator);
    839 }
    840 
    841 test "math.rem" {
    842     testRem();
    843     comptime testRem();
    844 }
    845 fn testRem() void {
    846     testing.expect((rem(i32, -5, 3) catch unreachable) == -2);
    847     testing.expect((rem(i32, 5, 3) catch unreachable) == 2);
    848     testing.expectError(error.NegativeDenominator, rem(i32, 10, -1));
    849     testing.expectError(error.DivisionByZero, rem(i32, 10, 0));
    850 
    851     testing.expect((rem(f32, -5, 3) catch unreachable) == -2);
    852     testing.expect((rem(f32, 5, 3) catch unreachable) == 2);
    853     testing.expectError(error.NegativeDenominator, rem(f32, 10, -1));
    854     testing.expectError(error.DivisionByZero, rem(f32, 10, 0));
    855 }
    856 
    857 /// Returns the absolute value of the integer parameter.
    858 /// Result is an unsigned integer.
    859 pub fn absCast(x: anytype) switch (@typeInfo(@TypeOf(x))) {
    860     .ComptimeInt => comptime_int,
    861     .Int => |intInfo| std.meta.Int(.unsigned, intInfo.bits),
    862     else => @compileError("absCast only accepts integers"),
    863 } {
    864     switch (@typeInfo(@TypeOf(x))) {
    865         .ComptimeInt => {
    866             if (x < 0) {
    867                 return -x;
    868             } else {
    869                 return x;
    870             }
    871         },
    872         .Int => |intInfo| {
    873             const Uint = std.meta.Int(.unsigned, intInfo.bits);
    874             if (x < 0) {
    875                 return ~@bitCast(Uint, x +% -1);
    876             } else {
    877                 return @intCast(Uint, x);
    878             }
    879         },
    880         else => unreachable,
    881     }
    882 }
    883 
    884 test "math.absCast" {
    885     testing.expectEqual(@as(u1, 1), absCast(@as(i1, -1)));
    886     testing.expectEqual(@as(u32, 999), absCast(@as(i32, -999)));
    887     testing.expectEqual(@as(u32, 999), absCast(@as(i32, 999)));
    888     testing.expectEqual(@as(u32, -minInt(i32)), absCast(@as(i32, minInt(i32))));
    889     testing.expectEqual(999, absCast(-999));
    890 }
    891 
    892 /// Returns the negation of the integer parameter.
    893 /// Result is a signed integer.
    894 pub fn negateCast(x: anytype) !std.meta.Int(.signed, std.meta.bitCount(@TypeOf(x))) {
    895     if (@typeInfo(@TypeOf(x)).Int.signedness == .signed) return negate(x);
    896 
    897     const int = std.meta.Int(.signed, std.meta.bitCount(@TypeOf(x)));
    898     if (x > -minInt(int)) return error.Overflow;
    899 
    900     if (x == -minInt(int)) return minInt(int);
    901 
    902     return -@intCast(int, x);
    903 }
    904 
    905 test "math.negateCast" {
    906     testing.expect((negateCast(@as(u32, 999)) catch unreachable) == -999);
    907     testing.expect(@TypeOf(negateCast(@as(u32, 999)) catch unreachable) == i32);
    908 
    909     testing.expect((negateCast(@as(u32, -minInt(i32))) catch unreachable) == minInt(i32));
    910     testing.expect(@TypeOf(negateCast(@as(u32, -minInt(i32))) catch unreachable) == i32);
    911 
    912     testing.expectError(error.Overflow, negateCast(@as(u32, maxInt(i32) + 10)));
    913 }
    914 
    915 /// Cast an integer to a different integer type. If the value doesn't fit,
    916 /// return an error.
    917 /// TODO make this an optional not an error.
    918 pub fn cast(comptime T: type, x: anytype) (error{Overflow}!T) {
    919     comptime assert(@typeInfo(T) == .Int); // must pass an integer
    920     comptime assert(@typeInfo(@TypeOf(x)) == .Int); // must pass an integer
    921     if (maxInt(@TypeOf(x)) > maxInt(T) and x > maxInt(T)) {
    922         return error.Overflow;
    923     } else if (minInt(@TypeOf(x)) < minInt(T) and x < minInt(T)) {
    924         return error.Overflow;
    925     } else {
    926         return @intCast(T, x);
    927     }
    928 }
    929 
    930 test "math.cast" {
    931     testing.expectError(error.Overflow, cast(u8, @as(u32, 300)));
    932     testing.expectError(error.Overflow, cast(i8, @as(i32, -200)));
    933     testing.expectError(error.Overflow, cast(u8, @as(i8, -1)));
    934     testing.expectError(error.Overflow, cast(u64, @as(i8, -1)));
    935 
    936     testing.expect((try cast(u8, @as(u32, 255))) == @as(u8, 255));
    937     testing.expect(@TypeOf(try cast(u8, @as(u32, 255))) == u8);
    938 }
    939 
    940 pub const AlignCastError = error{UnalignedMemory};
    941 
    942 /// Align cast a pointer but return an error if it's the wrong alignment
    943 pub fn alignCast(comptime alignment: u29, ptr: anytype) AlignCastError!@TypeOf(@alignCast(alignment, ptr)) {
    944     const addr = @ptrToInt(ptr);
    945     if (addr % alignment != 0) {
    946         return error.UnalignedMemory;
    947     }
    948     return @alignCast(alignment, ptr);
    949 }
    950 
    951 pub fn isPowerOfTwo(v: anytype) bool {
    952     assert(v != 0);
    953     return (v & (v - 1)) == 0;
    954 }
    955 
    956 pub fn floorPowerOfTwo(comptime T: type, value: T) T {
    957     var x = value;
    958 
    959     comptime var i = 1;
    960     inline while (@typeInfo(T).Int.bits > i) : (i *= 2) {
    961         x |= (x >> i);
    962     }
    963 
    964     return x - (x >> 1);
    965 }
    966 
    967 test "math.floorPowerOfTwo" {
    968     testFloorPowerOfTwo();
    969     comptime testFloorPowerOfTwo();
    970 }
    971 
    972 fn testFloorPowerOfTwo() void {
    973     testing.expect(floorPowerOfTwo(u32, 63) == 32);
    974     testing.expect(floorPowerOfTwo(u32, 64) == 64);
    975     testing.expect(floorPowerOfTwo(u32, 65) == 64);
    976     testing.expect(floorPowerOfTwo(u4, 7) == 4);
    977     testing.expect(floorPowerOfTwo(u4, 8) == 8);
    978     testing.expect(floorPowerOfTwo(u4, 9) == 8);
    979 }
    980 
    981 /// Returns the next power of two (if the value is not already a power of two).
    982 /// Only unsigned integers can be used. Zero is not an allowed input.
    983 /// Result is a type with 1 more bit than the input type.
    984 pub fn ceilPowerOfTwoPromote(comptime T: type, value: T) std.meta.Int(@typeInfo(T).Int.signedness, @typeInfo(T).Int.bits + 1) {
    985     comptime assert(@typeInfo(T) == .Int);
    986     comptime assert(@typeInfo(T).Int.signedness == .unsigned);
    987     assert(value != 0);
    988     comptime const PromotedType = std.meta.Int(@typeInfo(T).Int.signedness, @typeInfo(T).Int.bits + 1);
    989     comptime const shiftType = std.math.Log2Int(PromotedType);
    990     return @as(PromotedType, 1) << @intCast(shiftType, @typeInfo(T).Int.bits - @clz(T, value - 1));
    991 }
    992 
    993 /// Returns the next power of two (if the value is not already a power of two).
    994 /// Only unsigned integers can be used. Zero is not an allowed input.
    995 /// If the value doesn't fit, returns an error.
    996 pub fn ceilPowerOfTwo(comptime T: type, value: T) (error{Overflow}!T) {
    997     comptime assert(@typeInfo(T) == .Int);
    998     const info = @typeInfo(T).Int;
    999     comptime assert(info.signedness == .unsigned);
   1000     comptime const PromotedType = std.meta.Int(info.signedness, info.bits + 1);
   1001     comptime const overflowBit = @as(PromotedType, 1) << info.bits;
   1002     var x = ceilPowerOfTwoPromote(T, value);
   1003     if (overflowBit & x != 0) {
   1004         return error.Overflow;
   1005     }
   1006     return @intCast(T, x);
   1007 }
   1008 
   1009 pub fn ceilPowerOfTwoAssert(comptime T: type, value: T) T {
   1010     return ceilPowerOfTwo(T, value) catch unreachable;
   1011 }
   1012 
   1013 test "math.ceilPowerOfTwoPromote" {
   1014     testCeilPowerOfTwoPromote();
   1015     comptime testCeilPowerOfTwoPromote();
   1016 }
   1017 
   1018 fn testCeilPowerOfTwoPromote() void {
   1019     testing.expectEqual(@as(u33, 1), ceilPowerOfTwoPromote(u32, 1));
   1020     testing.expectEqual(@as(u33, 2), ceilPowerOfTwoPromote(u32, 2));
   1021     testing.expectEqual(@as(u33, 64), ceilPowerOfTwoPromote(u32, 63));
   1022     testing.expectEqual(@as(u33, 64), ceilPowerOfTwoPromote(u32, 64));
   1023     testing.expectEqual(@as(u33, 128), ceilPowerOfTwoPromote(u32, 65));
   1024     testing.expectEqual(@as(u6, 8), ceilPowerOfTwoPromote(u5, 7));
   1025     testing.expectEqual(@as(u6, 8), ceilPowerOfTwoPromote(u5, 8));
   1026     testing.expectEqual(@as(u6, 16), ceilPowerOfTwoPromote(u5, 9));
   1027     testing.expectEqual(@as(u5, 16), ceilPowerOfTwoPromote(u4, 9));
   1028 }
   1029 
   1030 test "math.ceilPowerOfTwo" {
   1031     try testCeilPowerOfTwo();
   1032     comptime try testCeilPowerOfTwo();
   1033 }
   1034 
   1035 fn testCeilPowerOfTwo() !void {
   1036     testing.expectEqual(@as(u32, 1), try ceilPowerOfTwo(u32, 1));
   1037     testing.expectEqual(@as(u32, 2), try ceilPowerOfTwo(u32, 2));
   1038     testing.expectEqual(@as(u32, 64), try ceilPowerOfTwo(u32, 63));
   1039     testing.expectEqual(@as(u32, 64), try ceilPowerOfTwo(u32, 64));
   1040     testing.expectEqual(@as(u32, 128), try ceilPowerOfTwo(u32, 65));
   1041     testing.expectEqual(@as(u5, 8), try ceilPowerOfTwo(u5, 7));
   1042     testing.expectEqual(@as(u5, 8), try ceilPowerOfTwo(u5, 8));
   1043     testing.expectEqual(@as(u5, 16), try ceilPowerOfTwo(u5, 9));
   1044     testing.expectError(error.Overflow, ceilPowerOfTwo(u4, 9));
   1045 }
   1046 
   1047 pub fn log2_int(comptime T: type, x: T) Log2Int(T) {
   1048     assert(x != 0);
   1049     return @intCast(Log2Int(T), @typeInfo(T).Int.bits - 1 - @clz(T, x));
   1050 }
   1051 
   1052 pub fn log2_int_ceil(comptime T: type, x: T) Log2Int(T) {
   1053     assert(x != 0);
   1054     const log2_val = log2_int(T, x);
   1055     if (@as(T, 1) << log2_val == x)
   1056         return log2_val;
   1057     return log2_val + 1;
   1058 }
   1059 
   1060 test "std.math.log2_int_ceil" {
   1061     testing.expect(log2_int_ceil(u32, 1) == 0);
   1062     testing.expect(log2_int_ceil(u32, 2) == 1);
   1063     testing.expect(log2_int_ceil(u32, 3) == 2);
   1064     testing.expect(log2_int_ceil(u32, 4) == 2);
   1065     testing.expect(log2_int_ceil(u32, 5) == 3);
   1066     testing.expect(log2_int_ceil(u32, 6) == 3);
   1067     testing.expect(log2_int_ceil(u32, 7) == 3);
   1068     testing.expect(log2_int_ceil(u32, 8) == 3);
   1069     testing.expect(log2_int_ceil(u32, 9) == 4);
   1070     testing.expect(log2_int_ceil(u32, 10) == 4);
   1071 }
   1072 
   1073 pub fn lossyCast(comptime T: type, value: anytype) T {
   1074     switch (@typeInfo(@TypeOf(value))) {
   1075         .Int => return @intToFloat(T, value),
   1076         .Float => return @floatCast(T, value),
   1077         .ComptimeInt => return @as(T, value),
   1078         .ComptimeFloat => return @as(T, value),
   1079         else => @compileError("bad type"),
   1080     }
   1081 }
   1082 
   1083 test "math.f64_min" {
   1084     const f64_min_u64 = 0x0010000000000000;
   1085     const fmin: f64 = f64_min;
   1086     testing.expect(@bitCast(u64, fmin) == f64_min_u64);
   1087 }
   1088 
   1089 pub fn maxInt(comptime T: type) comptime_int {
   1090     const info = @typeInfo(T);
   1091     const bit_count = info.Int.bits;
   1092     if (bit_count == 0) return 0;
   1093     return (1 << (bit_count - @boolToInt(info.Int.signedness == .signed))) - 1;
   1094 }
   1095 
   1096 pub fn minInt(comptime T: type) comptime_int {
   1097     const info = @typeInfo(T);
   1098     const bit_count = info.Int.bits;
   1099     if (info.Int.signedness == .unsigned) return 0;
   1100     if (bit_count == 0) return 0;
   1101     return -(1 << (bit_count - 1));
   1102 }
   1103 
   1104 test "minInt and maxInt" {
   1105     testing.expect(maxInt(u0) == 0);
   1106     testing.expect(maxInt(u1) == 1);
   1107     testing.expect(maxInt(u8) == 255);
   1108     testing.expect(maxInt(u16) == 65535);
   1109     testing.expect(maxInt(u32) == 4294967295);
   1110     testing.expect(maxInt(u64) == 18446744073709551615);
   1111     testing.expect(maxInt(u128) == 340282366920938463463374607431768211455);
   1112 
   1113     testing.expect(maxInt(i0) == 0);
   1114     testing.expect(maxInt(i1) == 0);
   1115     testing.expect(maxInt(i8) == 127);
   1116     testing.expect(maxInt(i16) == 32767);
   1117     testing.expect(maxInt(i32) == 2147483647);
   1118     testing.expect(maxInt(i63) == 4611686018427387903);
   1119     testing.expect(maxInt(i64) == 9223372036854775807);
   1120     testing.expect(maxInt(i128) == 170141183460469231731687303715884105727);
   1121 
   1122     testing.expect(minInt(u0) == 0);
   1123     testing.expect(minInt(u1) == 0);
   1124     testing.expect(minInt(u8) == 0);
   1125     testing.expect(minInt(u16) == 0);
   1126     testing.expect(minInt(u32) == 0);
   1127     testing.expect(minInt(u63) == 0);
   1128     testing.expect(minInt(u64) == 0);
   1129     testing.expect(minInt(u128) == 0);
   1130 
   1131     testing.expect(minInt(i0) == 0);
   1132     testing.expect(minInt(i1) == -1);
   1133     testing.expect(minInt(i8) == -128);
   1134     testing.expect(minInt(i16) == -32768);
   1135     testing.expect(minInt(i32) == -2147483648);
   1136     testing.expect(minInt(i63) == -4611686018427387904);
   1137     testing.expect(minInt(i64) == -9223372036854775808);
   1138     testing.expect(minInt(i128) == -170141183460469231731687303715884105728);
   1139 }
   1140 
   1141 test "max value type" {
   1142     const x: u32 = maxInt(i32);
   1143     testing.expect(x == 2147483647);
   1144 }
   1145 
   1146 pub fn mulWide(comptime T: type, a: T, b: T) std.meta.Int(@typeInfo(T).Int.signedness, @typeInfo(T).Int.bits * 2) {
   1147     const ResultInt = std.meta.Int(@typeInfo(T).Int.signedness, @typeInfo(T).Int.bits * 2);
   1148     return @as(ResultInt, a) * @as(ResultInt, b);
   1149 }
   1150 
   1151 test "math.mulWide" {
   1152     testing.expect(mulWide(u8, 5, 5) == 25);
   1153     testing.expect(mulWide(i8, 5, -5) == -25);
   1154     testing.expect(mulWide(u8, 100, 100) == 10000);
   1155 }
   1156 
   1157 /// See also `CompareOperator`.
   1158 pub const Order = enum {
   1159     /// Less than (`<`)
   1160     lt,
   1161 
   1162     /// Equal (`==`)
   1163     eq,
   1164 
   1165     /// Greater than (`>`)
   1166     gt,
   1167 
   1168     pub fn invert(self: Order) Order {
   1169         return switch (self) {
   1170             .lt => .gt,
   1171             .eq => .eq,
   1172             .gt => .lt,
   1173         };
   1174     }
   1175 
   1176     pub fn compare(self: Order, op: CompareOperator) bool {
   1177         return switch (self) {
   1178             .lt => switch (op) {
   1179                 .lt => true,
   1180                 .lte => true,
   1181                 .eq => false,
   1182                 .gte => false,
   1183                 .gt => false,
   1184                 .neq => true,
   1185             },
   1186             .eq => switch (op) {
   1187                 .lt => false,
   1188                 .lte => true,
   1189                 .eq => true,
   1190                 .gte => true,
   1191                 .gt => false,
   1192                 .neq => false,
   1193             },
   1194             .gt => switch (op) {
   1195                 .lt => false,
   1196                 .lte => false,
   1197                 .eq => false,
   1198                 .gte => true,
   1199                 .gt => true,
   1200                 .neq => true,
   1201             },
   1202         };
   1203     }
   1204 };
   1205 
   1206 /// Given two numbers, this function returns the order they are with respect to each other.
   1207 pub fn order(a: anytype, b: anytype) Order {
   1208     if (a == b) {
   1209         return .eq;
   1210     } else if (a < b) {
   1211         return .lt;
   1212     } else if (a > b) {
   1213         return .gt;
   1214     } else {
   1215         unreachable;
   1216     }
   1217 }
   1218 
   1219 /// See also `Order`.
   1220 pub const CompareOperator = enum {
   1221     /// Less than (`<`)
   1222     lt,
   1223     /// Less than or equal (`<=`)
   1224     lte,
   1225     /// Equal (`==`)
   1226     eq,
   1227     /// Greater than or equal (`>=`)
   1228     gte,
   1229     /// Greater than (`>`)
   1230     gt,
   1231     /// Not equal (`!=`)
   1232     neq,
   1233 };
   1234 
   1235 /// This function does the same thing as comparison operators, however the
   1236 /// operator is a runtime-known enum value. Works on any operands that
   1237 /// support comparison operators.
   1238 pub fn compare(a: anytype, op: CompareOperator, b: anytype) bool {
   1239     return switch (op) {
   1240         .lt => a < b,
   1241         .lte => a <= b,
   1242         .eq => a == b,
   1243         .neq => a != b,
   1244         .gt => a > b,
   1245         .gte => a >= b,
   1246     };
   1247 }
   1248 
   1249 test "compare between signed and unsigned" {
   1250     testing.expect(compare(@as(i8, -1), .lt, @as(u8, 255)));
   1251     testing.expect(compare(@as(i8, 2), .gt, @as(u8, 1)));
   1252     testing.expect(!compare(@as(i8, -1), .gte, @as(u8, 255)));
   1253     testing.expect(compare(@as(u8, 255), .gt, @as(i8, -1)));
   1254     testing.expect(!compare(@as(u8, 255), .lte, @as(i8, -1)));
   1255     testing.expect(compare(@as(i8, -1), .lt, @as(u9, 255)));
   1256     testing.expect(!compare(@as(i8, -1), .gte, @as(u9, 255)));
   1257     testing.expect(compare(@as(u9, 255), .gt, @as(i8, -1)));
   1258     testing.expect(!compare(@as(u9, 255), .lte, @as(i8, -1)));
   1259     testing.expect(compare(@as(i9, -1), .lt, @as(u8, 255)));
   1260     testing.expect(!compare(@as(i9, -1), .gte, @as(u8, 255)));
   1261     testing.expect(compare(@as(u8, 255), .gt, @as(i9, -1)));
   1262     testing.expect(!compare(@as(u8, 255), .lte, @as(i9, -1)));
   1263     testing.expect(compare(@as(u8, 1), .lt, @as(u8, 2)));
   1264     testing.expect(@bitCast(u8, @as(i8, -1)) == @as(u8, 255));
   1265     testing.expect(!compare(@as(u8, 255), .eq, @as(i8, -1)));
   1266     testing.expect(compare(@as(u8, 1), .eq, @as(u8, 1)));
   1267 }
   1268 
   1269 test "order" {
   1270     testing.expect(order(0, 0) == .eq);
   1271     testing.expect(order(1, 0) == .gt);
   1272     testing.expect(order(-1, 0) == .lt);
   1273 }
   1274 
   1275 test "order.invert" {
   1276     testing.expect(Order.invert(order(0, 0)) == .eq);
   1277     testing.expect(Order.invert(order(1, 0)) == .lt);
   1278     testing.expect(Order.invert(order(-1, 0)) == .gt);
   1279 }
   1280 
   1281 test "order.compare" {
   1282     testing.expect(order(-1, 0).compare(.lt));
   1283     testing.expect(order(-1, 0).compare(.lte));
   1284     testing.expect(order(0, 0).compare(.lte));
   1285     testing.expect(order(0, 0).compare(.eq));
   1286     testing.expect(order(0, 0).compare(.gte));
   1287     testing.expect(order(1, 0).compare(.gte));
   1288     testing.expect(order(1, 0).compare(.gt));
   1289     testing.expect(order(1, 0).compare(.neq));
   1290 }
   1291 
   1292 test "math.comptime" {
   1293     comptime const v = sin(@as(f32, 1)) + ln(@as(f32, 5));
   1294     testing.expect(v == sin(@as(f32, 1)) + ln(@as(f32, 5)));
   1295 }