| 1 | const builtin = @import("builtin"); |
| 2 | const std = @import("std.zig"); |
| 3 | const float = @import("math/float.zig"); |
| 4 | const assert = std.debug.assert; |
| 5 | const mem = std.mem; |
| 6 | const testing = std.testing; |
| 7 | const Alignment = std.mem.Alignment; |
| 8 | |
| 9 | /// Euler's number (e) |
| 10 | pub const e = 2.71828182845904523536028747135266249775724709369995; |
| 11 | |
| 12 | /// Archimedes' constant (π) |
| 13 | pub const pi = 3.14159265358979323846264338327950288419716939937510; |
| 14 | |
| 15 | /// Phi or Golden ratio constant (Φ) = (1 + sqrt(5))/2 |
| 16 | pub const phi = 1.6180339887498948482045868343656381177203091798057628621; |
| 17 | |
| 18 | /// Circle constant (τ) |
| 19 | pub const tau = 2 * pi; |
| 20 | |
| 21 | /// log2(e) |
| 22 | pub const log2e = 1.442695040888963407359924681001892137; |
| 23 | |
| 24 | /// log10(e) |
| 25 | pub const log10e = 0.434294481903251827651128918916605082; |
| 26 | |
| 27 | /// ln(2) |
| 28 | pub const ln2 = 0.693147180559945309417232121458176568; |
| 29 | |
| 30 | /// ln(10) |
| 31 | pub const ln10 = 2.302585092994045684017991454684364208; |
| 32 | |
| 33 | /// 2/sqrt(π) |
| 34 | pub const two_sqrtpi = 1.128379167095512573896158903121545172; |
| 35 | |
| 36 | /// sqrt(2) |
| 37 | pub const sqrt2 = 1.414213562373095048801688724209698079; |
| 38 | |
| 39 | /// 1/sqrt(2) |
| 40 | pub const sqrt1_2 = 0.707106781186547524400844362104849039; |
| 41 | |
| 42 | /// pi/180.0 |
| 43 | pub const rad_per_deg = 0.0174532925199432957692369076848861271344287188854172545609719144; |
| 44 | |
| 45 | /// 180.0/pi |
| 46 | pub const deg_per_rad = 57.295779513082320876798154814105170332405472466564321549160243861; |
| 47 | |
| 48 | pub const Sign = enum(u1) { positive, negative }; |
| 49 | pub const FloatRepr = float.FloatRepr; |
| 50 | pub const floatExponentBits = float.floatExponentBits; |
| 51 | pub const floatMantissaBits = float.floatMantissaBits; |
| 52 | pub const floatFractionalBits = float.floatFractionalBits; |
| 53 | pub const floatExponentMin = float.floatExponentMin; |
| 54 | pub const floatExponentMax = float.floatExponentMax; |
| 55 | pub const floatTrueMin = float.floatTrueMin; |
| 56 | pub const floatMin = float.floatMin; |
| 57 | pub const floatMax = float.floatMax; |
| 58 | pub const floatEps = float.floatEps; |
| 59 | pub const floatEpsAt = float.floatEpsAt; |
| 60 | pub const inf = float.inf; |
| 61 | pub const long_double = float.long_double; |
| 62 | pub const nan = float.nan; |
| 63 | pub const snan = float.snan; |
| 64 | |
| 65 | /// Performs an approximate comparison of two floating point values `x` and `y`. |
| 66 | /// Returns true if the absolute difference between them is less or equal than |
| 67 | /// the specified tolerance. |
| 68 | /// |
| 69 | /// The `tolerance` parameter is the absolute tolerance used when determining if |
| 70 | /// the two numbers are close enough; a good value for this parameter is a small |
| 71 | /// multiple of `floatEps(T)`. |
| 72 | /// |
| 73 | /// Note that this function is recommended for comparing small numbers |
| 74 | /// around zero; using `approxEqRel` is suggested otherwise. |
| 75 | /// |
| 76 | /// NaN values are never considered equal to any value. |
| 77 | pub fn approxEqAbs(comptime T: type, x: T, y: T, tolerance: T) bool { |
| 78 | comptime assert(@typeInfo(T) == .float or @typeInfo(T) == .comptime_float); |
| 79 | assert(tolerance >= 0); |
| 80 | |
| 81 | // Fast path for equal values (and signed zeros and infinites). |
| 82 | if (x == y) |
| 83 | return true; |
| 84 | |
| 85 | if (isNan(x) or isNan(y)) |
| 86 | return false; |
| 87 | |
| 88 | return @abs(x - y) <= tolerance; |
| 89 | } |
| 90 | |
| 91 | /// Performs an approximate comparison of two floating point values `x` and `y`. |
| 92 | /// Returns true if the absolute difference between them is less or equal than |
| 93 | /// `max(|x|, |y|) * tolerance`, where `tolerance` is a positive number greater |
| 94 | /// than zero. |
| 95 | /// |
| 96 | /// The `tolerance` parameter is the relative tolerance used when determining if |
| 97 | /// the two numbers are close enough; a good value for this parameter is usually |
| 98 | /// `sqrt(floatEps(T))`, meaning that the two numbers are considered equal if at |
| 99 | /// least half of the digits are equal. |
| 100 | /// |
| 101 | /// Note that for comparisons of small numbers around zero this function won't |
| 102 | /// give meaningful results, use `approxEqAbs` instead. |
| 103 | /// |
| 104 | /// NaN values are never considered equal to any value. |
| 105 | pub fn approxEqRel(comptime T: type, x: T, y: T, tolerance: T) bool { |
| 106 | comptime assert(@typeInfo(T) == .float or @typeInfo(T) == .comptime_float); |
| 107 | assert(tolerance > 0); |
| 108 | |
| 109 | // Fast path for equal values (and signed zeros and infinites). |
| 110 | if (x == y) |
| 111 | return true; |
| 112 | |
| 113 | if (isNan(x) or isNan(y)) |
| 114 | return false; |
| 115 | |
| 116 | return @abs(x - y) <= @max(@abs(x), @abs(y)) * tolerance; |
| 117 | } |
| 118 | |
| 119 | test approxEqAbs { |
| 120 | inline for ([_]type{ f16, f32, f64, f128 }) |T| { |
| 121 | const eps_value = comptime floatEps(T); |
| 122 | const min_value = comptime floatMin(T); |
| 123 | |
| 124 | try testing.expect(approxEqAbs(T, 0.0, 0.0, eps_value)); |
| 125 | try testing.expect(approxEqAbs(T, -0.0, -0.0, eps_value)); |
| 126 | try testing.expect(approxEqAbs(T, 0.0, -0.0, eps_value)); |
| 127 | try testing.expect(!approxEqAbs(T, 1.0 + 2 * eps_value, 1.0, eps_value)); |
| 128 | try testing.expect(approxEqAbs(T, 1.0 + 1 * eps_value, 1.0, eps_value)); |
| 129 | try testing.expect(approxEqAbs(T, min_value, 0.0, eps_value * 2)); |
| 130 | try testing.expect(approxEqAbs(T, -min_value, 0.0, eps_value * 2)); |
| 131 | } |
| 132 | |
| 133 | comptime { |
| 134 | // `comptime_float` is guaranteed to have the same precision and operations of |
| 135 | // the largest other floating point type, which is f128 but it doesn't have a |
| 136 | // defined layout so we can't rely on `@bitCast` to construct the smallest |
| 137 | // possible epsilon value like we do in the tests above. In the same vein, we |
| 138 | // also can't represent a max/min, `NaN` or `Inf` values. |
| 139 | const eps_value = 1e-4; |
| 140 | |
| 141 | try testing.expect(approxEqAbs(comptime_float, 0.0, 0.0, eps_value)); |
| 142 | try testing.expect(approxEqAbs(comptime_float, -0.0, -0.0, eps_value)); |
| 143 | try testing.expect(approxEqAbs(comptime_float, 0.0, -0.0, eps_value)); |
| 144 | try testing.expect(!approxEqAbs(comptime_float, 1.0 + 2 * eps_value, 1.0, eps_value)); |
| 145 | try testing.expect(approxEqAbs(comptime_float, 1.0 + 1 * eps_value, 1.0, eps_value)); |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | test approxEqRel { |
| 150 | inline for ([_]type{ f16, f32, f64, f128 }) |T| { |
| 151 | const eps_value = comptime floatEps(T); |
| 152 | const sqrt_eps_value = comptime sqrt(eps_value); |
| 153 | const nan_value = comptime nan(T); |
| 154 | const inf_value = comptime inf(T); |
| 155 | const min_value = comptime floatMin(T); |
| 156 | |
| 157 | try testing.expect(approxEqRel(T, 1.0, 1.0, sqrt_eps_value)); |
| 158 | try testing.expect(!approxEqRel(T, 1.0, 0.0, sqrt_eps_value)); |
| 159 | try testing.expect(!approxEqRel(T, 1.0, nan_value, sqrt_eps_value)); |
| 160 | try testing.expect(!approxEqRel(T, nan_value, nan_value, sqrt_eps_value)); |
| 161 | try testing.expect(approxEqRel(T, inf_value, inf_value, sqrt_eps_value)); |
| 162 | try testing.expect(approxEqRel(T, min_value, min_value, sqrt_eps_value)); |
| 163 | try testing.expect(approxEqRel(T, -min_value, -min_value, sqrt_eps_value)); |
| 164 | } |
| 165 | |
| 166 | comptime { |
| 167 | // `comptime_float` is guaranteed to have the same precision and operations of |
| 168 | // the largest other floating point type, which is f128 but it doesn't have a |
| 169 | // defined layout so we can't rely on `@bitCast` to construct the smallest |
| 170 | // possible epsilon value like we do in the tests above. In the same vein, we |
| 171 | // also can't represent a max/min, `NaN` or `Inf` values. |
| 172 | const eps_value = 1e-4; |
| 173 | const sqrt_eps_value = sqrt(eps_value); |
| 174 | |
| 175 | try testing.expect(approxEqRel(comptime_float, 1.0, 1.0, sqrt_eps_value)); |
| 176 | try testing.expect(!approxEqRel(comptime_float, 1.0, 0.0, sqrt_eps_value)); |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | pub fn raiseInvalid() void { |
| 181 | // Raise INVALID fpu exception |
| 182 | } |
| 183 | |
| 184 | pub fn raiseUnderflow() void { |
| 185 | // Raise UNDERFLOW fpu exception |
| 186 | } |
| 187 | |
| 188 | pub fn raiseOverflow() void { |
| 189 | // Raise OVERFLOW fpu exception |
| 190 | } |
| 191 | |
| 192 | pub fn raiseInexact() void { |
| 193 | // Raise INEXACT fpu exception |
| 194 | } |
| 195 | |
| 196 | pub fn raiseDivByZero() void { |
| 197 | // Raise INEXACT fpu exception |
| 198 | } |
| 199 | |
| 200 | pub const isNan = @import("math/isnan.zig").isNan; |
| 201 | pub const isSignalNan = @import("math/isnan.zig").isSignalNan; |
| 202 | pub const frexp = @import("math/frexp.zig").frexp; |
| 203 | pub const Frexp = @import("math/frexp.zig").Frexp; |
| 204 | pub const modf = @import("math/modf.zig").modf; |
| 205 | pub const Modf = @import("math/modf.zig").Modf; |
| 206 | pub const copysign = @import("math/copysign.zig").copysign; |
| 207 | pub const isFinite = @import("math/isfinite.zig").isFinite; |
| 208 | pub const isInf = @import("math/isinf.zig").isInf; |
| 209 | pub const isPositiveInf = @import("math/isinf.zig").isPositiveInf; |
| 210 | pub const isNegativeInf = @import("math/isinf.zig").isNegativeInf; |
| 211 | pub const isPositiveZero = @import("math/iszero.zig").isPositiveZero; |
| 212 | pub const isNegativeZero = @import("math/iszero.zig").isNegativeZero; |
| 213 | pub const isNormal = @import("math/isnormal.zig").isNormal; |
| 214 | pub const nextAfter = @import("math/nextafter.zig").nextAfter; |
| 215 | pub const signbit = @import("math/signbit.zig").signbit; |
| 216 | pub const scalbn = @import("math/scalbn.zig").scalbn; |
| 217 | pub const ldexp = @import("math/ldexp.zig").ldexp; |
| 218 | pub const pow = @import("math/pow.zig").pow; |
| 219 | pub const powi = @import("math/powi.zig").powi; |
| 220 | pub const sqrt = @import("math/sqrt.zig").sqrt; |
| 221 | pub const cbrt = @import("math/cbrt.zig").cbrt; |
| 222 | pub const acos = @import("math/acos.zig").acos; |
| 223 | pub const asin = @import("math/asin.zig").asin; |
| 224 | pub const atan = @import("math/atan.zig").atan; |
| 225 | pub const atan2 = @import("math/atan2.zig").atan2; |
| 226 | pub const hypot = @import("math/hypot.zig").hypot; |
| 227 | pub const expm1 = @import("math/expm1.zig").expm1; |
| 228 | pub const ilogb = @import("math/ilogb.zig").ilogb; |
| 229 | pub const log = @import("math/log.zig").log; |
| 230 | pub const log2 = @import("math/log2.zig").log2; |
| 231 | pub const log10 = @import("math/log10.zig").log10; |
| 232 | pub const log10_int = @import("math/log10.zig").log10_int; |
| 233 | pub const log_int = @import("math/log_int.zig").log_int; |
| 234 | pub const log1p = @import("math/log1p.zig").log1p; |
| 235 | pub const asinh = @import("math/asinh.zig").asinh; |
| 236 | pub const acosh = @import("math/acosh.zig").acosh; |
| 237 | pub const atanh = @import("math/atanh.zig").atanh; |
| 238 | pub const sinh = @import("math/sinh.zig").sinh; |
| 239 | pub const cosh = @import("math/cosh.zig").cosh; |
| 240 | pub const tanh = @import("math/tanh.zig").tanh; |
| 241 | pub const gcd = @import("math/gcd.zig").gcd; |
| 242 | pub const lcm = @import("math/lcm.zig").lcm; |
| 243 | pub const gamma = @import("math/gamma.zig").gamma; |
| 244 | pub const lgamma = @import("math/gamma.zig").lgamma; |
| 245 | |
| 246 | /// Sine trigonometric function on a floating point number. |
| 247 | /// Uses a dedicated hardware instruction when available. |
| 248 | /// This is the same as calling the builtin @sin |
| 249 | pub inline fn sin(value: anytype) @TypeOf(value) { |
| 250 | return @sin(value); |
| 251 | } |
| 252 | |
| 253 | /// Cosine trigonometric function on a floating point number. |
| 254 | /// Uses a dedicated hardware instruction when available. |
| 255 | /// This is the same as calling the builtin @cos |
| 256 | pub inline fn cos(value: anytype) @TypeOf(value) { |
| 257 | return @cos(value); |
| 258 | } |
| 259 | |
| 260 | /// Tangent trigonometric function on a floating point number. |
| 261 | /// Uses a dedicated hardware instruction when available. |
| 262 | /// This is the same as calling the builtin @tan |
| 263 | pub inline fn tan(value: anytype) @TypeOf(value) { |
| 264 | return @tan(value); |
| 265 | } |
| 266 | |
| 267 | /// Converts an angle in radians to degrees. T must be a float or comptime number or a vector of floats. |
| 268 | pub fn radiansToDegrees(ang: anytype) if (@TypeOf(ang) == comptime_int) comptime_float else @TypeOf(ang) { |
| 269 | const T = @TypeOf(ang); |
| 270 | switch (@typeInfo(T)) { |
| 271 | .float, .comptime_float, .comptime_int => return ang * deg_per_rad, |
| 272 | .vector => |V| if (@typeInfo(V.child) == .float) return ang * @as(T, @splat(deg_per_rad)), |
| 273 | else => {}, |
| 274 | } |
| 275 | @compileError("Input must be float or a comptime number, or a vector of floats."); |
| 276 | } |
| 277 | |
| 278 | test radiansToDegrees { |
| 279 | const zero: f32 = 0; |
| 280 | const half_pi: f32 = pi / 2.0; |
| 281 | const neg_quart_pi: f32 = -pi / 4.0; |
| 282 | const one_pi: f32 = pi; |
| 283 | const two_pi: f32 = 2.0 * pi; |
| 284 | try std.testing.expectApproxEqAbs(@as(f32, 0), radiansToDegrees(zero), 1e-6); |
| 285 | try std.testing.expectApproxEqAbs(@as(f32, 90), radiansToDegrees(half_pi), 1e-6); |
| 286 | try std.testing.expectApproxEqAbs(@as(f32, -45), radiansToDegrees(neg_quart_pi), 1e-6); |
| 287 | try std.testing.expectApproxEqAbs(@as(f32, 180), radiansToDegrees(one_pi), 1e-6); |
| 288 | try std.testing.expectApproxEqAbs(@as(f32, 360), radiansToDegrees(two_pi), 1e-6); |
| 289 | |
| 290 | const result = radiansToDegrees(@Vector(4, f32){ |
| 291 | half_pi, |
| 292 | neg_quart_pi, |
| 293 | one_pi, |
| 294 | two_pi, |
| 295 | }); |
| 296 | try std.testing.expectApproxEqAbs(@as(f32, 90), result[0], 1e-6); |
| 297 | try std.testing.expectApproxEqAbs(@as(f32, -45), result[1], 1e-6); |
| 298 | try std.testing.expectApproxEqAbs(@as(f32, 180), result[2], 1e-6); |
| 299 | try std.testing.expectApproxEqAbs(@as(f32, 360), result[3], 1e-6); |
| 300 | } |
| 301 | |
| 302 | /// Converts an angle in degrees to radians. T must be a float or comptime number or a vector of floats. |
| 303 | pub fn degreesToRadians(ang: anytype) if (@TypeOf(ang) == comptime_int) comptime_float else @TypeOf(ang) { |
| 304 | const T = @TypeOf(ang); |
| 305 | switch (@typeInfo(T)) { |
| 306 | .float, .comptime_float, .comptime_int => return ang * rad_per_deg, |
| 307 | .vector => |V| if (@typeInfo(V.child) == .float) return ang * @as(T, @splat(rad_per_deg)), |
| 308 | else => {}, |
| 309 | } |
| 310 | @compileError("Input must be float or a comptime number, or a vector of floats."); |
| 311 | } |
| 312 | |
| 313 | test degreesToRadians { |
| 314 | const ninety: f32 = 90; |
| 315 | const neg_two_seventy: f32 = -270; |
| 316 | const three_sixty: f32 = 360; |
| 317 | try std.testing.expectApproxEqAbs(@as(f32, pi / 2.0), degreesToRadians(ninety), 1e-6); |
| 318 | try std.testing.expectApproxEqAbs(@as(f32, -3 * pi / 2.0), degreesToRadians(neg_two_seventy), 1e-6); |
| 319 | try std.testing.expectApproxEqAbs(@as(f32, 2 * pi), degreesToRadians(three_sixty), 1e-6); |
| 320 | |
| 321 | const result = degreesToRadians(@Vector(3, f32){ |
| 322 | ninety, |
| 323 | neg_two_seventy, |
| 324 | three_sixty, |
| 325 | }); |
| 326 | try std.testing.expectApproxEqAbs(@as(f32, pi / 2.0), result[0], 1e-6); |
| 327 | try std.testing.expectApproxEqAbs(@as(f32, -3 * pi / 2.0), result[1], 1e-6); |
| 328 | try std.testing.expectApproxEqAbs(@as(f32, 2 * pi), result[2], 1e-6); |
| 329 | } |
| 330 | |
| 331 | /// Base-e exponential function on a floating point number. |
| 332 | /// Uses a dedicated hardware instruction when available. |
| 333 | /// This is the same as calling the builtin @exp |
| 334 | pub inline fn exp(value: anytype) @TypeOf(value) { |
| 335 | return @exp(value); |
| 336 | } |
| 337 | |
| 338 | /// Base-2 exponential function on a floating point number. |
| 339 | /// Uses a dedicated hardware instruction when available. |
| 340 | /// This is the same as calling the builtin @exp2 |
| 341 | pub inline fn exp2(value: anytype) @TypeOf(value) { |
| 342 | return @exp2(value); |
| 343 | } |
| 344 | |
| 345 | pub const complex = @import("math/complex.zig"); |
| 346 | pub const Complex = complex.Complex; |
| 347 | |
| 348 | pub const big = @import("math/big.zig"); |
| 349 | |
| 350 | test { |
| 351 | _ = floatExponentBits; |
| 352 | _ = floatMantissaBits; |
| 353 | _ = floatFractionalBits; |
| 354 | _ = floatExponentMin; |
| 355 | _ = floatExponentMax; |
| 356 | _ = floatTrueMin; |
| 357 | _ = floatMin; |
| 358 | _ = floatMax; |
| 359 | _ = floatEps; |
| 360 | _ = inf; |
| 361 | _ = nan; |
| 362 | _ = snan; |
| 363 | _ = isNan; |
| 364 | _ = isSignalNan; |
| 365 | _ = frexp; |
| 366 | _ = Frexp; |
| 367 | _ = modf; |
| 368 | _ = Modf; |
| 369 | _ = copysign; |
| 370 | _ = isFinite; |
| 371 | _ = isInf; |
| 372 | _ = isPositiveInf; |
| 373 | _ = isNegativeInf; |
| 374 | _ = isNormal; |
| 375 | _ = nextAfter; |
| 376 | _ = signbit; |
| 377 | _ = scalbn; |
| 378 | _ = ldexp; |
| 379 | _ = pow; |
| 380 | _ = powi; |
| 381 | _ = sqrt; |
| 382 | _ = cbrt; |
| 383 | _ = acos; |
| 384 | _ = asin; |
| 385 | _ = atan; |
| 386 | _ = atan2; |
| 387 | _ = hypot; |
| 388 | _ = expm1; |
| 389 | _ = ilogb; |
| 390 | _ = log; |
| 391 | _ = log2; |
| 392 | _ = log10; |
| 393 | _ = log10_int; |
| 394 | _ = log_int; |
| 395 | _ = log1p; |
| 396 | _ = asinh; |
| 397 | _ = acosh; |
| 398 | _ = atanh; |
| 399 | _ = sinh; |
| 400 | _ = cosh; |
| 401 | _ = tanh; |
| 402 | _ = gcd; |
| 403 | _ = lcm; |
| 404 | _ = gamma; |
| 405 | _ = lgamma; |
| 406 | |
| 407 | _ = complex; |
| 408 | _ = Complex; |
| 409 | |
| 410 | _ = big; |
| 411 | } |
| 412 | |
| 413 | /// Given two types, returns the smallest one which is capable of holding the |
| 414 | /// full range of the minimum value. |
| 415 | pub fn Min(comptime A: type, comptime B: type) type { |
| 416 | switch (@typeInfo(A)) { |
| 417 | .int => |a_info| switch (@typeInfo(B)) { |
| 418 | .int => |b_info| if (a_info.signedness == .unsigned and b_info.signedness == .unsigned) { |
| 419 | if (a_info.bits < b_info.bits) { |
| 420 | return A; |
| 421 | } else { |
| 422 | return B; |
| 423 | } |
| 424 | }, |
| 425 | else => {}, |
| 426 | }, |
| 427 | else => {}, |
| 428 | } |
| 429 | return @TypeOf(@as(A, 0) + @as(B, 0)); |
| 430 | } |
| 431 | |
| 432 | /// Odd sawtooth function |
| 433 | /// ``` |
| 434 | /// | |
| 435 | /// / | / / |
| 436 | /// / |/ / |
| 437 | /// --/----/----/-- |
| 438 | /// / /| / |
| 439 | /// / / | / |
| 440 | /// | |
| 441 | /// ``` |
| 442 | /// Limit x to the half-open interval [-r, r). |
| 443 | pub fn wrap(x: anytype, r: anytype) @TypeOf(x) { |
| 444 | const info_x = @typeInfo(@TypeOf(x)); |
| 445 | const info_r = @typeInfo(@TypeOf(r)); |
| 446 | if (info_x == .int and info_x.int.signedness != .signed) { |
| 447 | @compileError("x must be floating point, comptime integer, or signed integer."); |
| 448 | } |
| 449 | switch (info_r) { |
| 450 | .int => { |
| 451 | // in the rare usecase of r not being comptime_int or float, |
| 452 | // take the penalty of having an intermediary type conversion, |
| 453 | // otherwise the alternative is to unwind iteratively to avoid overflow |
| 454 | const R = @Int(.signed, info_r.int.bits + 1); |
| 455 | const radius: if (info_r.int.signedness == .signed) @TypeOf(r) else R = r; |
| 456 | return @intCast(@mod(x - radius, 2 * @as(R, r)) - r); // provably impossible to overflow |
| 457 | }, |
| 458 | else => { |
| 459 | return @mod(x - r, 2 * r) - r; |
| 460 | }, |
| 461 | } |
| 462 | } |
| 463 | test wrap { |
| 464 | if (builtin.os.tag == .windows and builtin.cpu.arch == .x86 and builtin.abi == .msvc) { |
| 465 | // https://codeberg.org/ziglang/zig/issues/35520 |
| 466 | return error.SkipZigTest; |
| 467 | } |
| 468 | |
| 469 | // Within range |
| 470 | try testing.expect(wrap(@as(i32, -75), @as(i32, 180)) == -75); |
| 471 | try testing.expect(wrap(@as(i32, -75), @as(i32, -180)) == -75); |
| 472 | // Below |
| 473 | try testing.expect(wrap(@as(i32, -225), @as(i32, 180)) == 135); |
| 474 | try testing.expect(wrap(@as(i32, -225), @as(i32, -180)) == 135); |
| 475 | // Above |
| 476 | try testing.expect(wrap(@as(i32, 361), @as(i32, 180)) == 1); |
| 477 | try testing.expect(wrap(@as(i32, 361), @as(i32, -180)) == 1); |
| 478 | |
| 479 | // One period, right limit, positive r |
| 480 | try testing.expect(wrap(@as(i32, 180), @as(i32, 180)) == -180); |
| 481 | // One period, left limit, positive r |
| 482 | try testing.expect(wrap(@as(i32, -180), @as(i32, 180)) == -180); |
| 483 | // One period, right limit, negative r |
| 484 | try testing.expect(wrap(@as(i32, 180), @as(i32, -180)) == 180); |
| 485 | // One period, left limit, negative r |
| 486 | try testing.expect(wrap(@as(i32, -180), @as(i32, -180)) == 180); |
| 487 | |
| 488 | // Two periods, right limit, positive r |
| 489 | try testing.expect(wrap(@as(i32, 540), @as(i32, 180)) == -180); |
| 490 | // Two periods, left limit, positive r |
| 491 | try testing.expect(wrap(@as(i32, -540), @as(i32, 180)) == -180); |
| 492 | // Two periods, right limit, negative r |
| 493 | try testing.expect(wrap(@as(i32, 540), @as(i32, -180)) == 180); |
| 494 | // Two periods, left limit, negative r |
| 495 | try testing.expect(wrap(@as(i32, -540), @as(i32, -180)) == 180); |
| 496 | |
| 497 | // Floating point |
| 498 | try testing.expect(wrap(@as(f32, 1.125), @as(f32, 1.0)) == -0.875); |
| 499 | try testing.expect(wrap(@as(f32, -127.5), @as(f32, 180)) == -127.5); |
| 500 | |
| 501 | // Mix of comptime and non-comptime |
| 502 | var i: i32 = 1; |
| 503 | _ = &i; |
| 504 | try testing.expect(wrap(i, 10) == 1); |
| 505 | |
| 506 | const limit: i32 = 180; |
| 507 | // Within range |
| 508 | try testing.expect(wrap(@as(i32, -75), limit) == -75); |
| 509 | // Below |
| 510 | try testing.expect(wrap(@as(i32, -225), limit) == 135); |
| 511 | // Above |
| 512 | try testing.expect(wrap(@as(i32, 361), limit) == 1); |
| 513 | } |
| 514 | |
| 515 | /// Odd ramp function |
| 516 | /// ``` |
| 517 | /// | _____ |
| 518 | /// | / |
| 519 | /// |/ |
| 520 | /// -------/------- |
| 521 | /// /| |
| 522 | /// _____/ | |
| 523 | /// | |
| 524 | /// ``` |
| 525 | /// Limit val to the inclusive range [lower, upper]. |
| 526 | pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper) { |
| 527 | const T = @TypeOf(val, lower, upper); |
| 528 | switch (@typeInfo(T)) { |
| 529 | .int, .float, .comptime_int, .comptime_float => assert(lower <= upper), |
| 530 | .vector => |vinfo| switch (@typeInfo(vinfo.child)) { |
| 531 | .int, .float => assert(@reduce(.And, lower <= upper)), |
| 532 | else => @compileError("Expected vector of ints or floats, found " ++ @typeName(T)), |
| 533 | }, |
| 534 | else => @compileError("Expected an int, float or vector of one, found " ++ @typeName(T)), |
| 535 | } |
| 536 | return @max(lower, @min(val, upper)); |
| 537 | } |
| 538 | test clamp { |
| 539 | // Within range |
| 540 | try testing.expect(std.math.clamp(@as(i32, -1), @as(i32, -4), @as(i32, 7)) == -1); |
| 541 | // Below |
| 542 | try testing.expect(std.math.clamp(@as(i32, -5), @as(i32, -4), @as(i32, 7)) == -4); |
| 543 | // Above |
| 544 | try testing.expect(std.math.clamp(@as(i32, 8), @as(i32, -4), @as(i32, 7)) == 7); |
| 545 | |
| 546 | // Floating point |
| 547 | try testing.expect(std.math.clamp(@as(f32, 1.1), @as(f32, 0.0), @as(f32, 1.0)) == 1.0); |
| 548 | try testing.expect(std.math.clamp(@as(f32, -127.5), @as(f32, -200), @as(f32, -100)) == -127.5); |
| 549 | |
| 550 | // Vector |
| 551 | try testing.expect(@reduce(.And, std.math.clamp(@as(@Vector(3, f32), .{ 1.4, 15.23, 28.3 }), @as(@Vector(3, f32), .{ 9.8, 13.2, 15.6 }), @as(@Vector(3, f32), .{ 15.2, 22.8, 26.3 })) == @as(@Vector(3, f32), .{ 9.8, 15.23, 26.3 }))); |
| 552 | |
| 553 | // Mix of comptime and non-comptime |
| 554 | var i: i32 = 1; |
| 555 | _ = &i; |
| 556 | try testing.expect(std.math.clamp(i, 0, 1) == 1); |
| 557 | } |
| 558 | |
| 559 | /// Returns the product of a and b. Returns an error on overflow. |
| 560 | pub fn mul(comptime T: type, a: T, b: T) (error{Overflow}!T) { |
| 561 | if (T == comptime_int) return a * b; |
| 562 | const ov = @mulWithOverflow(a, b); |
| 563 | if (ov[1] != 0) return error.Overflow; |
| 564 | return ov[0]; |
| 565 | } |
| 566 | |
| 567 | /// Returns the sum of a and b. Returns an error on overflow. |
| 568 | pub fn add(comptime T: type, a: T, b: T) (error{Overflow}!T) { |
| 569 | if (T == comptime_int) return a + b; |
| 570 | const ov = @addWithOverflow(a, b); |
| 571 | if (ov[1] != 0) return error.Overflow; |
| 572 | return ov[0]; |
| 573 | } |
| 574 | |
| 575 | /// Returns a - b, or an error on overflow. |
| 576 | pub fn sub(comptime T: type, a: T, b: T) (error{Overflow}!T) { |
| 577 | if (T == comptime_int) return a - b; |
| 578 | const ov = @subWithOverflow(a, b); |
| 579 | if (ov[1] != 0) return error.Overflow; |
| 580 | return ov[0]; |
| 581 | } |
| 582 | |
| 583 | pub fn negate(x: anytype) !@TypeOf(x) { |
| 584 | return sub(@TypeOf(x), 0, x); |
| 585 | } |
| 586 | |
| 587 | /// Shifts a left by shift_amt. Returns an error on overflow. shift_amt |
| 588 | /// is unsigned. |
| 589 | pub fn shlExact(comptime T: type, a: T, shift_amt: Log2Int(T)) !T { |
| 590 | if (T == comptime_int) return a << shift_amt; |
| 591 | const ov = @shlWithOverflow(a, shift_amt); |
| 592 | if (ov[1] != 0) return error.Overflow; |
| 593 | return ov[0]; |
| 594 | } |
| 595 | |
| 596 | /// Shifts left. Overflowed bits are truncated. |
| 597 | /// A negative shift amount results in a right shift. |
| 598 | pub fn shl(comptime T: type, a: T, shift_amt: anytype) T { |
| 599 | const is_shl = shift_amt >= 0; |
| 600 | const abs_shift_amt = @abs(shift_amt); |
| 601 | const casted_shift_amt = casted_shift_amt: switch (@typeInfo(T)) { |
| 602 | .int => |info| { |
| 603 | if (abs_shift_amt < info.bits) break :casted_shift_amt @as( |
| 604 | Log2Int(T), |
| 605 | @intCast(abs_shift_amt), |
| 606 | ); |
| 607 | if (info.signedness == .unsigned or is_shl) return 0; |
| 608 | return a >> (info.bits - 1); |
| 609 | }, |
| 610 | .vector => |info| { |
| 611 | const Child = info.child; |
| 612 | const child_info = @typeInfo(Child).int; |
| 613 | if (abs_shift_amt < child_info.bits) break :casted_shift_amt @as( |
| 614 | @Vector(info.len, Log2Int(Child)), |
| 615 | @splat(@as(Log2Int(Child), @intCast(abs_shift_amt))), |
| 616 | ); |
| 617 | if (child_info.signedness == .unsigned or is_shl) return @splat(0); |
| 618 | return a >> @splat(child_info.bits - 1); |
| 619 | }, |
| 620 | else => comptime unreachable, |
| 621 | }; |
| 622 | return if (is_shl) a << casted_shift_amt else a >> casted_shift_amt; |
| 623 | } |
| 624 | |
| 625 | test shl { |
| 626 | try testing.expect(shl(u8, 0b11111111, @as(usize, 3)) == 0b11111000); |
| 627 | try testing.expect(shl(u8, 0b11111111, @as(usize, 8)) == 0); |
| 628 | try testing.expect(shl(u8, 0b11111111, @as(usize, 9)) == 0); |
| 629 | try testing.expect(shl(u8, 0b11111111, @as(isize, -2)) == 0b00111111); |
| 630 | try testing.expect(shl(u8, 0b11111111, 3) == 0b11111000); |
| 631 | try testing.expect(shl(u8, 0b11111111, 8) == 0); |
| 632 | try testing.expect(shl(u8, 0b11111111, 9) == 0); |
| 633 | try testing.expect(shl(u8, 0b11111111, -2) == 0b00111111); |
| 634 | try testing.expect(shl(@Vector(1, u32), @Vector(1, u32){42}, @as(usize, 1))[0] == @as(u32, 42) << 1); |
| 635 | try testing.expect(shl(@Vector(1, u32), @Vector(1, u32){42}, @as(isize, -1))[0] == @as(u32, 42) >> 1); |
| 636 | try testing.expect(shl(@Vector(1, u32), @Vector(1, u32){42}, 33)[0] == 0); |
| 637 | |
| 638 | try testing.expect(shl(i8, -1, -100) == -1); |
| 639 | try testing.expect(shl(i8, -1, 100) == 0); |
| 640 | if (builtin.cpu.arch == .hexagon and builtin.zig_backend == .stage2_llvm) return error.SkipZigTest; |
| 641 | try testing.expect(@reduce(.And, shl(@Vector(2, i8), .{ -1, 1 }, -100) == @Vector(2, i8){ -1, 0 })); |
| 642 | try testing.expect(@reduce(.And, shl(@Vector(2, i8), .{ -1, 1 }, 100) == @Vector(2, i8){ 0, 0 })); |
| 643 | } |
| 644 | |
| 645 | /// Shifts right. Overflowed bits are truncated. |
| 646 | /// A negative shift amount results in a left shift. |
| 647 | pub fn shr(comptime T: type, a: T, shift_amt: anytype) T { |
| 648 | const is_shl = shift_amt < 0; |
| 649 | const abs_shift_amt = @abs(shift_amt); |
| 650 | const casted_shift_amt = casted_shift_amt: switch (@typeInfo(T)) { |
| 651 | .int => |info| { |
| 652 | if (abs_shift_amt < info.bits) break :casted_shift_amt @as( |
| 653 | Log2Int(T), |
| 654 | @intCast(abs_shift_amt), |
| 655 | ); |
| 656 | if (info.signedness == .unsigned or is_shl) return 0; |
| 657 | return a >> (info.bits - 1); |
| 658 | }, |
| 659 | .vector => |info| { |
| 660 | const Child = info.child; |
| 661 | const child_info = @typeInfo(Child).int; |
| 662 | if (abs_shift_amt < child_info.bits) break :casted_shift_amt @as( |
| 663 | @Vector(info.len, Log2Int(Child)), |
| 664 | @splat(@as(Log2Int(Child), @intCast(abs_shift_amt))), |
| 665 | ); |
| 666 | if (child_info.signedness == .unsigned or is_shl) return @splat(0); |
| 667 | return a >> @splat(child_info.bits - 1); |
| 668 | }, |
| 669 | else => comptime unreachable, |
| 670 | }; |
| 671 | return if (is_shl) a << casted_shift_amt else a >> casted_shift_amt; |
| 672 | } |
| 673 | |
| 674 | test shr { |
| 675 | try testing.expect(shr(u8, 0b11111111, @as(usize, 3)) == 0b00011111); |
| 676 | try testing.expect(shr(u8, 0b11111111, @as(usize, 8)) == 0); |
| 677 | try testing.expect(shr(u8, 0b11111111, @as(usize, 9)) == 0); |
| 678 | try testing.expect(shr(u8, 0b11111111, @as(isize, -2)) == 0b11111100); |
| 679 | try testing.expect(shr(u8, 0b11111111, 3) == 0b00011111); |
| 680 | try testing.expect(shr(u8, 0b11111111, 8) == 0); |
| 681 | try testing.expect(shr(u8, 0b11111111, 9) == 0); |
| 682 | try testing.expect(shr(u8, 0b11111111, -2) == 0b11111100); |
| 683 | try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, @as(usize, 1))[0] == @as(u32, 42) >> 1); |
| 684 | try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, @as(isize, -1))[0] == @as(u32, 42) << 1); |
| 685 | try testing.expect(shr(@Vector(1, u32), @Vector(1, u32){42}, 33)[0] == 0); |
| 686 | |
| 687 | try testing.expect(shr(i8, -1, -100) == 0); |
| 688 | try testing.expect(shr(i8, -1, 100) == -1); |
| 689 | if (builtin.cpu.arch == .hexagon and builtin.zig_backend == .stage2_llvm) return error.SkipZigTest; |
| 690 | try testing.expect(@reduce(.And, shr(@Vector(2, i8), .{ -1, 1 }, -100) == @Vector(2, i8){ 0, 0 })); |
| 691 | try testing.expect(@reduce(.And, shr(@Vector(2, i8), .{ -1, 1 }, 100) == @Vector(2, i8){ -1, 0 })); |
| 692 | } |
| 693 | |
| 694 | /// Rotates right. Only unsigned values can be rotated. Negative shift |
| 695 | /// values result in shift modulo the bit count. |
| 696 | pub fn rotr(comptime T: type, x: T, r: anytype) T { |
| 697 | if (@typeInfo(T) == .vector) { |
| 698 | const C = @typeInfo(T).vector.child; |
| 699 | if (C == u0) return @splat(0); |
| 700 | |
| 701 | if (@typeInfo(C).int.signedness == .signed) { |
| 702 | @compileError("cannot rotate signed integers"); |
| 703 | } |
| 704 | const ar: Log2Int(C) = @intCast(@mod(r, @typeInfo(C).int.bits)); |
| 705 | return (x >> @splat(ar)) | (x << @splat(1 + ~ar)); |
| 706 | } else if (@typeInfo(T).int.signedness == .signed) { |
| 707 | @compileError("cannot rotate signed integer"); |
| 708 | } else { |
| 709 | if (T == u0) return 0; |
| 710 | |
| 711 | if (comptime isPowerOfTwo(@typeInfo(T).int.bits)) { |
| 712 | const ar: Log2Int(T) = @intCast(@mod(r, @typeInfo(T).int.bits)); |
| 713 | return x >> ar | x << (1 +% ~ar); |
| 714 | } else { |
| 715 | const ar = @mod(r, @typeInfo(T).int.bits); |
| 716 | return shr(T, x, ar) | shl(T, x, @typeInfo(T).int.bits - ar); |
| 717 | } |
| 718 | } |
| 719 | } |
| 720 | |
| 721 | test rotr { |
| 722 | try testing.expect(rotr(u0, 0b0, @as(usize, 3)) == 0b0); |
| 723 | try testing.expect(rotr(u5, 0b00001, @as(usize, 0)) == 0b00001); |
| 724 | try testing.expect(rotr(u6, 0b000001, @as(usize, 7)) == 0b100000); |
| 725 | try testing.expect(rotr(u8, 0b00000001, @as(usize, 0)) == 0b00000001); |
| 726 | try testing.expect(rotr(u8, 0b00000001, @as(usize, 9)) == 0b10000000); |
| 727 | try testing.expect(rotr(u8, 0b00000001, @as(usize, 8)) == 0b00000001); |
| 728 | try testing.expect(rotr(u8, 0b00000001, @as(usize, 4)) == 0b00010000); |
| 729 | try testing.expect(rotr(u8, 0b00000001, @as(isize, -1)) == 0b00000010); |
| 730 | try testing.expect(rotr(u12, 0o7777, 1) == 0o7777); |
| 731 | try testing.expect(rotr(@Vector(1, u32), .{1}, @as(usize, 1))[0] == @as(u32, 1) << 31); |
| 732 | try testing.expect(rotr(@Vector(1, u32), .{1}, @as(isize, -1))[0] == @as(u32, 1) << 1); |
| 733 | try std.testing.expect(@reduce(.And, rotr(@Vector(2, u0), .{ 0, 0 }, @as(usize, 42)) == |
| 734 | @Vector(2, u0){ 0, 0 })); |
| 735 | } |
| 736 | |
| 737 | /// Rotates left. Only unsigned values can be rotated. Negative shift |
| 738 | /// values result in shift modulo the bit count. |
| 739 | pub fn rotl(comptime T: type, x: T, r: anytype) T { |
| 740 | if (@typeInfo(T) == .vector) { |
| 741 | const C = @typeInfo(T).vector.child; |
| 742 | if (C == u0) return @splat(0); |
| 743 | |
| 744 | if (@typeInfo(C).int.signedness == .signed) { |
| 745 | @compileError("cannot rotate signed integers"); |
| 746 | } |
| 747 | const ar: Log2Int(C) = @intCast(@mod(r, @typeInfo(C).int.bits)); |
| 748 | return (x << @splat(ar)) | (x >> @splat(1 +% ~ar)); |
| 749 | } else if (@typeInfo(T).int.signedness == .signed) { |
| 750 | @compileError("cannot rotate signed integer"); |
| 751 | } else { |
| 752 | if (T == u0) return 0; |
| 753 | |
| 754 | if (comptime isPowerOfTwo(@typeInfo(T).int.bits)) { |
| 755 | const ar: Log2Int(T) = @intCast(@mod(r, @typeInfo(T).int.bits)); |
| 756 | return x << ar | x >> 1 +% ~ar; |
| 757 | } else { |
| 758 | const ar = @mod(r, @typeInfo(T).int.bits); |
| 759 | return shl(T, x, ar) | shr(T, x, @typeInfo(T).int.bits - ar); |
| 760 | } |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | test rotl { |
| 765 | try testing.expect(rotl(u0, 0b0, @as(usize, 3)) == 0b0); |
| 766 | try testing.expect(rotl(u5, 0b00001, @as(usize, 0)) == 0b00001); |
| 767 | try testing.expect(rotl(u6, 0b000001, @as(usize, 7)) == 0b000010); |
| 768 | try testing.expect(rotl(u8, 0b00000001, @as(usize, 0)) == 0b00000001); |
| 769 | try testing.expect(rotl(u8, 0b00000001, @as(usize, 9)) == 0b00000010); |
| 770 | try testing.expect(rotl(u8, 0b00000001, @as(usize, 8)) == 0b00000001); |
| 771 | try testing.expect(rotl(u8, 0b00000001, @as(usize, 4)) == 0b00010000); |
| 772 | try testing.expect(rotl(u8, 0b00000001, @as(isize, -1)) == 0b10000000); |
| 773 | try testing.expect(rotl(u12, 0o7777, 1) == 0o7777); |
| 774 | try testing.expect(rotl(@Vector(1, u32), .{1 << 31}, @as(usize, 1))[0] == 1); |
| 775 | try testing.expect(rotl(@Vector(1, u32), .{1 << 31}, @as(isize, -1))[0] == @as(u32, 1) << 30); |
| 776 | try std.testing.expect(@reduce(.And, rotl(@Vector(2, u0), .{ 0, 0 }, @as(usize, 42)) == |
| 777 | @Vector(2, u0){ 0, 0 })); |
| 778 | } |
| 779 | |
| 780 | /// Returns an unsigned int type that can hold the number of bits in T - 1. |
| 781 | /// Suitable for 0-based bit indices of T. |
| 782 | pub fn Log2Int(comptime T: type) type { |
| 783 | // comptime ceil log2 |
| 784 | if (T == comptime_int) return comptime_int; |
| 785 | const bits: u16 = @typeInfo(T).int.bits; |
| 786 | const log2_bits = 16 - @clz(bits - 1); |
| 787 | return @Int(.unsigned, log2_bits); |
| 788 | } |
| 789 | |
| 790 | /// Returns an unsigned int type that can hold the number of bits in T. |
| 791 | pub fn Log2IntCeil(comptime T: type) type { |
| 792 | // comptime ceil log2 |
| 793 | if (T == comptime_int) return comptime_int; |
| 794 | const bits: u16 = @typeInfo(T).int.bits; |
| 795 | const log2_bits = 16 - @clz(bits); |
| 796 | return @Int(.unsigned, log2_bits); |
| 797 | } |
| 798 | |
| 799 | /// Returns the smallest integer type that can hold both from and to. |
| 800 | pub fn IntFittingRange(comptime from: comptime_int, comptime to: comptime_int) type { |
| 801 | assert(from <= to); |
| 802 | const signedness: std.builtin.Signedness = if (from < 0) .signed else .unsigned; |
| 803 | return @Int( |
| 804 | signedness, |
| 805 | @as(u16, @intFromBool(signedness == .signed)) + |
| 806 | switch (if (from < 0) @max(@abs(from) - 1, to) else to) { |
| 807 | 0 => 0, |
| 808 | else => |pos_max| 1 + log2(pos_max), |
| 809 | }, |
| 810 | ); |
| 811 | } |
| 812 | |
| 813 | test IntFittingRange { |
| 814 | try testing.expect(IntFittingRange(0, 0) == u0); |
| 815 | try testing.expect(IntFittingRange(0, 1) == u1); |
| 816 | try testing.expect(IntFittingRange(0, 2) == u2); |
| 817 | try testing.expect(IntFittingRange(0, 3) == u2); |
| 818 | try testing.expect(IntFittingRange(0, 4) == u3); |
| 819 | try testing.expect(IntFittingRange(0, 7) == u3); |
| 820 | try testing.expect(IntFittingRange(0, 8) == u4); |
| 821 | try testing.expect(IntFittingRange(0, 9) == u4); |
| 822 | try testing.expect(IntFittingRange(0, 15) == u4); |
| 823 | try testing.expect(IntFittingRange(0, 16) == u5); |
| 824 | try testing.expect(IntFittingRange(0, 17) == u5); |
| 825 | try testing.expect(IntFittingRange(0, 4095) == u12); |
| 826 | try testing.expect(IntFittingRange(2000, 4095) == u12); |
| 827 | try testing.expect(IntFittingRange(0, 4096) == u13); |
| 828 | try testing.expect(IntFittingRange(2000, 4096) == u13); |
| 829 | try testing.expect(IntFittingRange(0, 4097) == u13); |
| 830 | try testing.expect(IntFittingRange(2000, 4097) == u13); |
| 831 | try testing.expect(IntFittingRange(0, 123456789123456798123456789) == u87); |
| 832 | try testing.expect(IntFittingRange(0, 123456789123456798123456789123456789123456798123456789) == u177); |
| 833 | |
| 834 | try testing.expect(IntFittingRange(-1, -1) == i1); |
| 835 | try testing.expect(IntFittingRange(-1, 0) == i1); |
| 836 | try testing.expect(IntFittingRange(-1, 1) == i2); |
| 837 | try testing.expect(IntFittingRange(-2, -2) == i2); |
| 838 | try testing.expect(IntFittingRange(-2, -1) == i2); |
| 839 | try testing.expect(IntFittingRange(-2, 0) == i2); |
| 840 | try testing.expect(IntFittingRange(-2, 1) == i2); |
| 841 | try testing.expect(IntFittingRange(-2, 2) == i3); |
| 842 | try testing.expect(IntFittingRange(-1, 2) == i3); |
| 843 | try testing.expect(IntFittingRange(-1, 3) == i3); |
| 844 | try testing.expect(IntFittingRange(-1, 4) == i4); |
| 845 | try testing.expect(IntFittingRange(-1, 7) == i4); |
| 846 | try testing.expect(IntFittingRange(-1, 8) == i5); |
| 847 | try testing.expect(IntFittingRange(-1, 9) == i5); |
| 848 | try testing.expect(IntFittingRange(-1, 15) == i5); |
| 849 | try testing.expect(IntFittingRange(-1, 16) == i6); |
| 850 | try testing.expect(IntFittingRange(-1, 17) == i6); |
| 851 | try testing.expect(IntFittingRange(-1, 4095) == i13); |
| 852 | try testing.expect(IntFittingRange(-4096, 4095) == i13); |
| 853 | try testing.expect(IntFittingRange(-1, 4096) == i14); |
| 854 | try testing.expect(IntFittingRange(-4097, 4095) == i14); |
| 855 | try testing.expect(IntFittingRange(-1, 4097) == i14); |
| 856 | try testing.expect(IntFittingRange(-1, 123456789123456798123456789) == i88); |
| 857 | try testing.expect(IntFittingRange(-1, 123456789123456798123456789123456789123456798123456789) == i178); |
| 858 | } |
| 859 | |
| 860 | test "overflow functions" { |
| 861 | try testOverflow(); |
| 862 | try comptime testOverflow(); |
| 863 | } |
| 864 | |
| 865 | fn testOverflow() !void { |
| 866 | try testing.expect((mul(i32, 3, 4) catch unreachable) == 12); |
| 867 | try testing.expect((add(i32, 3, 4) catch unreachable) == 7); |
| 868 | try testing.expect((sub(i32, 3, 4) catch unreachable) == -1); |
| 869 | try testing.expect((shlExact(i32, 0b11, 4) catch unreachable) == 0b110000); |
| 870 | } |
| 871 | |
| 872 | /// Divide numerator by denominator, rounding toward zero. Returns an |
| 873 | /// error on overflow or when denominator is zero. |
| 874 | pub fn divTrunc(comptime T: type, numerator: T, denominator: T) !T { |
| 875 | @setRuntimeSafety(false); |
| 876 | if (denominator == 0) return error.DivisionByZero; |
| 877 | if (@typeInfo(T) == .int and @typeInfo(T).int.signedness == .signed and numerator == minInt(T) and denominator == -1) return error.Overflow; |
| 878 | return @divTrunc(numerator, denominator); |
| 879 | } |
| 880 | |
| 881 | test divTrunc { |
| 882 | try testDivTrunc(); |
| 883 | try comptime testDivTrunc(); |
| 884 | } |
| 885 | fn testDivTrunc() !void { |
| 886 | try testing.expect((divTrunc(i32, 5, 3) catch unreachable) == 1); |
| 887 | try testing.expect((divTrunc(i32, -5, 3) catch unreachable) == -1); |
| 888 | try testing.expectError(error.DivisionByZero, divTrunc(i8, -5, 0)); |
| 889 | try testing.expectError(error.Overflow, divTrunc(i8, -128, -1)); |
| 890 | |
| 891 | try testing.expect((divTrunc(f32, 5.0, 3.0) catch unreachable) == 1.0); |
| 892 | try testing.expect((divTrunc(f32, -5.0, 3.0) catch unreachable) == -1.0); |
| 893 | } |
| 894 | |
| 895 | /// Divide numerator by denominator, rounding toward negative |
| 896 | /// infinity. Returns an error on overflow or when denominator is |
| 897 | /// zero. |
| 898 | pub fn divFloor(comptime T: type, numerator: T, denominator: T) !T { |
| 899 | @setRuntimeSafety(false); |
| 900 | if (denominator == 0) return error.DivisionByZero; |
| 901 | if (@typeInfo(T) == .int and @typeInfo(T).int.signedness == .signed and numerator == minInt(T) and denominator == -1) return error.Overflow; |
| 902 | return @divFloor(numerator, denominator); |
| 903 | } |
| 904 | |
| 905 | test divFloor { |
| 906 | try testDivFloor(); |
| 907 | try comptime testDivFloor(); |
| 908 | } |
| 909 | fn testDivFloor() !void { |
| 910 | try testing.expect((divFloor(i32, 5, 3) catch unreachable) == 1); |
| 911 | try testing.expect((divFloor(i32, -5, 3) catch unreachable) == -2); |
| 912 | try testing.expectError(error.DivisionByZero, divFloor(i8, -5, 0)); |
| 913 | try testing.expectError(error.Overflow, divFloor(i8, -128, -1)); |
| 914 | |
| 915 | try testing.expect((divFloor(f32, 5.0, 3.0) catch unreachable) == 1.0); |
| 916 | try testing.expect((divFloor(f32, -5.0, 3.0) catch unreachable) == -2.0); |
| 917 | } |
| 918 | |
| 919 | /// Divide numerator by denominator, rounding toward positive |
| 920 | /// infinity. Returns an error on overflow or when denominator is |
| 921 | /// zero. |
| 922 | pub fn divCeil(comptime T: type, numerator: T, denominator: T) !T { |
| 923 | @setRuntimeSafety(false); |
| 924 | if (denominator == 0) return error.DivisionByZero; |
| 925 | if (@typeInfo(T) == .int and numerator == minInt(T) and denominator == -1) { |
| 926 | return error.Overflow; |
| 927 | } |
| 928 | return @divCeil(numerator, denominator); |
| 929 | } |
| 930 | |
| 931 | test divCeil { |
| 932 | try testDivCeil(); |
| 933 | try comptime testDivCeil(); |
| 934 | } |
| 935 | fn testDivCeil() !void { |
| 936 | try testing.expectEqual(@as(i32, 2), divCeil(i32, 5, 3) catch unreachable); |
| 937 | try testing.expectEqual(@as(i32, -1), divCeil(i32, -5, 3) catch unreachable); |
| 938 | try testing.expectEqual(@as(i32, -1), divCeil(i32, 5, -3) catch unreachable); |
| 939 | try testing.expectEqual(@as(i32, 2), divCeil(i32, -5, -3) catch unreachable); |
| 940 | try testing.expectEqual(@as(i32, 0), divCeil(i32, 0, 5) catch unreachable); |
| 941 | try testing.expectEqual(@as(u32, 0), divCeil(u32, 0, 5) catch unreachable); |
| 942 | try testing.expectError(error.DivisionByZero, divCeil(i8, -5, 0)); |
| 943 | try testing.expectError(error.Overflow, divCeil(i8, -128, -1)); |
| 944 | |
| 945 | try testing.expectEqual(@as(f32, 0.0), divCeil(f32, 0.0, 5.0) catch unreachable); |
| 946 | try testing.expectEqual(@as(f32, 2.0), divCeil(f32, 5.0, 3.0) catch unreachable); |
| 947 | try testing.expectEqual(@as(f32, -1.0), divCeil(f32, -5.0, 3.0) catch unreachable); |
| 948 | try testing.expectEqual(@as(f32, -1.0), divCeil(f32, 5.0, -3.0) catch unreachable); |
| 949 | try testing.expectEqual(@as(f32, 2.0), divCeil(f32, -5.0, -3.0) catch unreachable); |
| 950 | |
| 951 | try testing.expectEqual(6, divCeil(comptime_int, 23, 4) catch unreachable); |
| 952 | try testing.expectEqual(-5, divCeil(comptime_int, -23, 4) catch unreachable); |
| 953 | try testing.expectEqual(-5, divCeil(comptime_int, 23, -4) catch unreachable); |
| 954 | try testing.expectEqual(6, divCeil(comptime_int, -23, -4) catch unreachable); |
| 955 | try testing.expectError(error.DivisionByZero, divCeil(comptime_int, 23, 0)); |
| 956 | |
| 957 | try testing.expectEqual(6.0, divCeil(comptime_float, 23.0, 4.0) catch unreachable); |
| 958 | try testing.expectEqual(-5.0, divCeil(comptime_float, -23.0, 4.0) catch unreachable); |
| 959 | try testing.expectEqual(-5.0, divCeil(comptime_float, 23.0, -4.0) catch unreachable); |
| 960 | try testing.expectEqual(6.0, divCeil(comptime_float, -23.0, -4.0) catch unreachable); |
| 961 | try testing.expectError(error.DivisionByZero, divCeil(comptime_float, 23.0, 0.0)); |
| 962 | } |
| 963 | |
| 964 | /// Divide numerator by denominator. Return an error if quotient is |
| 965 | /// not an integer, denominator is zero, or on overflow. |
| 966 | pub fn divExact(comptime T: type, numerator: T, denominator: T) !T { |
| 967 | @setRuntimeSafety(false); |
| 968 | if (denominator == 0) return error.DivisionByZero; |
| 969 | if (@typeInfo(T) == .int and @typeInfo(T).int.signedness == .signed and numerator == minInt(T) and denominator == -1) return error.Overflow; |
| 970 | const result = @divTrunc(numerator, denominator); |
| 971 | if (result * denominator != numerator) return error.UnexpectedRemainder; |
| 972 | return result; |
| 973 | } |
| 974 | |
| 975 | test divExact { |
| 976 | try testDivExact(); |
| 977 | try comptime testDivExact(); |
| 978 | } |
| 979 | fn testDivExact() !void { |
| 980 | try testing.expect((divExact(i32, 10, 5) catch unreachable) == 2); |
| 981 | try testing.expect((divExact(i32, -10, 5) catch unreachable) == -2); |
| 982 | try testing.expectError(error.DivisionByZero, divExact(i8, -5, 0)); |
| 983 | try testing.expectError(error.Overflow, divExact(i8, -128, -1)); |
| 984 | try testing.expectError(error.UnexpectedRemainder, divExact(i32, 5, 2)); |
| 985 | |
| 986 | try testing.expect((divExact(f32, 10.0, 5.0) catch unreachable) == 2.0); |
| 987 | try testing.expect((divExact(f32, -10.0, 5.0) catch unreachable) == -2.0); |
| 988 | try testing.expectError(error.UnexpectedRemainder, divExact(f32, 5.0, 2.0)); |
| 989 | } |
| 990 | |
| 991 | /// Returns numerator modulo denominator, or an error if denominator is |
| 992 | /// zero or negative. Negative numerators never result in negative |
| 993 | /// return values. |
| 994 | pub fn mod(comptime T: type, numerator: T, denominator: T) !T { |
| 995 | @setRuntimeSafety(false); |
| 996 | if (denominator == 0) return error.DivisionByZero; |
| 997 | if (denominator < 0) return error.NegativeDenominator; |
| 998 | return @mod(numerator, denominator); |
| 999 | } |
| 1000 | |
| 1001 | test mod { |
| 1002 | try testMod(); |
| 1003 | try comptime testMod(); |
| 1004 | } |
| 1005 | fn testMod() !void { |
| 1006 | try testing.expect((mod(i32, -5, 3) catch unreachable) == 1); |
| 1007 | try testing.expect((mod(i32, 5, 3) catch unreachable) == 2); |
| 1008 | try testing.expectError(error.NegativeDenominator, mod(i32, 10, -1)); |
| 1009 | try testing.expectError(error.DivisionByZero, mod(i32, 10, 0)); |
| 1010 | |
| 1011 | try testing.expect((mod(f32, -5, 3) catch unreachable) == 1); |
| 1012 | try testing.expect((mod(f32, 5, 3) catch unreachable) == 2); |
| 1013 | try testing.expectError(error.NegativeDenominator, mod(f32, 10, -1)); |
| 1014 | try testing.expectError(error.DivisionByZero, mod(f32, 10, 0)); |
| 1015 | } |
| 1016 | |
| 1017 | /// Returns the remainder when numerator is divided by denominator, or |
| 1018 | /// an error if denominator is zero or negative. Negative numerators |
| 1019 | /// can give negative results. |
| 1020 | pub fn rem(comptime T: type, numerator: T, denominator: T) !T { |
| 1021 | @setRuntimeSafety(false); |
| 1022 | if (denominator == 0) return error.DivisionByZero; |
| 1023 | if (denominator < 0) return error.NegativeDenominator; |
| 1024 | return @rem(numerator, denominator); |
| 1025 | } |
| 1026 | |
| 1027 | test rem { |
| 1028 | try testRem(); |
| 1029 | try comptime testRem(); |
| 1030 | } |
| 1031 | fn testRem() !void { |
| 1032 | try testing.expect((rem(i32, -5, 3) catch unreachable) == -2); |
| 1033 | try testing.expect((rem(i32, 5, 3) catch unreachable) == 2); |
| 1034 | try testing.expectError(error.NegativeDenominator, rem(i32, 10, -1)); |
| 1035 | try testing.expectError(error.DivisionByZero, rem(i32, 10, 0)); |
| 1036 | |
| 1037 | try testing.expect((rem(f32, -5, 3) catch unreachable) == -2); |
| 1038 | try testing.expect((rem(f32, 5, 3) catch unreachable) == 2); |
| 1039 | try testing.expectError(error.NegativeDenominator, rem(f32, 10, -1)); |
| 1040 | try testing.expectError(error.DivisionByZero, rem(f32, 10, 0)); |
| 1041 | } |
| 1042 | |
| 1043 | /// Returns the negation of the integer parameter. |
| 1044 | /// Result is a signed integer. |
| 1045 | pub fn negateCast(x: anytype) !@Int(.signed, @bitSizeOf(@TypeOf(x))) { |
| 1046 | if (@typeInfo(@TypeOf(x)).int.signedness == .signed) return negate(x); |
| 1047 | |
| 1048 | const int = @Int(.signed, @bitSizeOf(@TypeOf(x))); |
| 1049 | if (x > -minInt(int)) return error.Overflow; |
| 1050 | |
| 1051 | if (x == -minInt(int)) return minInt(int); |
| 1052 | |
| 1053 | return -@as(int, @intCast(x)); |
| 1054 | } |
| 1055 | |
| 1056 | test negateCast { |
| 1057 | try testing.expect((negateCast(@as(u32, 999)) catch unreachable) == -999); |
| 1058 | try testing.expect(@TypeOf(negateCast(@as(u32, 999)) catch unreachable) == i32); |
| 1059 | |
| 1060 | try testing.expect((negateCast(@as(u32, -minInt(i32))) catch unreachable) == minInt(i32)); |
| 1061 | try testing.expect(@TypeOf(negateCast(@as(u32, -minInt(i32))) catch unreachable) == i32); |
| 1062 | |
| 1063 | try testing.expectError(error.Overflow, negateCast(@as(u32, maxInt(i32) + 10))); |
| 1064 | } |
| 1065 | |
| 1066 | /// Cast an integer to a different integer type. If the value doesn't fit, |
| 1067 | /// return null. |
| 1068 | pub fn cast(comptime T: type, x: anytype) ?T { |
| 1069 | comptime assert(@typeInfo(T) == .int); // must pass an integer |
| 1070 | const is_comptime = @TypeOf(x) == comptime_int; |
| 1071 | comptime assert(is_comptime or @typeInfo(@TypeOf(x)) == .int); // must pass an integer |
| 1072 | if ((is_comptime or maxInt(@TypeOf(x)) > maxInt(T)) and x > maxInt(T)) { |
| 1073 | return null; |
| 1074 | } else if ((is_comptime or minInt(@TypeOf(x)) < minInt(T)) and x < minInt(T)) { |
| 1075 | return null; |
| 1076 | } else { |
| 1077 | return @as(T, @intCast(x)); |
| 1078 | } |
| 1079 | } |
| 1080 | |
| 1081 | test cast { |
| 1082 | try testing.expect(cast(u8, 300) == null); |
| 1083 | try testing.expect(cast(u8, @as(u32, 300)) == null); |
| 1084 | try testing.expect(cast(i8, -200) == null); |
| 1085 | try testing.expect(cast(i8, @as(i32, -200)) == null); |
| 1086 | try testing.expect(cast(u8, -1) == null); |
| 1087 | try testing.expect(cast(u8, @as(i8, -1)) == null); |
| 1088 | try testing.expect(cast(u64, -1) == null); |
| 1089 | try testing.expect(cast(u64, @as(i8, -1)) == null); |
| 1090 | |
| 1091 | try testing.expect(cast(u8, 255).? == @as(u8, 255)); |
| 1092 | try testing.expect(cast(u8, @as(u32, 255)).? == @as(u8, 255)); |
| 1093 | try testing.expect(@TypeOf(cast(u8, 255).?) == u8); |
| 1094 | try testing.expect(@TypeOf(cast(u8, @as(u32, 255)).?) == u8); |
| 1095 | } |
| 1096 | |
| 1097 | pub const AlignCastError = error{UnalignedMemory}; |
| 1098 | |
| 1099 | fn AlignCastResult(comptime alignment: Alignment, comptime Ptr: type) type { |
| 1100 | const orig = @typeInfo(Ptr).pointer; |
| 1101 | return @Pointer(orig.size, .{ |
| 1102 | .@"const" = orig.is_const, |
| 1103 | .@"volatile" = orig.is_volatile, |
| 1104 | .@"allowzero" = orig.is_allowzero, |
| 1105 | .@"align" = alignment.toByteUnits(), |
| 1106 | .@"addrspace" = orig.address_space, |
| 1107 | }, orig.child, orig.sentinel()); |
| 1108 | } |
| 1109 | |
| 1110 | /// Align cast a pointer but return an error if it's the wrong alignment |
| 1111 | pub fn alignCast(comptime alignment: Alignment, ptr: anytype) AlignCastError!AlignCastResult(alignment, @TypeOf(ptr)) { |
| 1112 | if (alignment.check(@intFromPtr(ptr))) return @alignCast(ptr); |
| 1113 | return error.UnalignedMemory; |
| 1114 | } |
| 1115 | |
| 1116 | /// Asserts `int > 0`. |
| 1117 | pub fn isPowerOfTwo(int: anytype) bool { |
| 1118 | assert(int > 0); |
| 1119 | return (int & (int - 1)) == 0; |
| 1120 | } |
| 1121 | |
| 1122 | test isPowerOfTwo { |
| 1123 | try testing.expect(isPowerOfTwo(@as(u8, 1))); |
| 1124 | try testing.expect(isPowerOfTwo(2)); |
| 1125 | try testing.expect(!isPowerOfTwo(@as(i16, 3))); |
| 1126 | try testing.expect(isPowerOfTwo(4)); |
| 1127 | try testing.expect(!isPowerOfTwo(@as(u32, 31))); |
| 1128 | try testing.expect(isPowerOfTwo(32)); |
| 1129 | try testing.expect(!isPowerOfTwo(@as(i64, 63))); |
| 1130 | try testing.expect(isPowerOfTwo(128)); |
| 1131 | try testing.expect(isPowerOfTwo(@as(u128, 256))); |
| 1132 | } |
| 1133 | |
| 1134 | /// Aligns the given integer type bit width to a width divisible by 8. |
| 1135 | pub fn ByteAlignedInt(comptime T: type) type { |
| 1136 | const info = @typeInfo(T).int; |
| 1137 | const bits = (info.bits + 7) / 8 * 8; |
| 1138 | return @Int(info.signedness, bits); |
| 1139 | } |
| 1140 | |
| 1141 | test ByteAlignedInt { |
| 1142 | try testing.expect(ByteAlignedInt(u0) == u0); |
| 1143 | try testing.expect(ByteAlignedInt(u3) == u8); |
| 1144 | try testing.expect(ByteAlignedInt(u8) == u8); |
| 1145 | try testing.expect(ByteAlignedInt(i111) == i112); |
| 1146 | try testing.expect(ByteAlignedInt(u129) == u136); |
| 1147 | } |
| 1148 | |
| 1149 | /// Rounds the given floating point number to the nearest integer. |
| 1150 | /// If two integers are equally close, rounds away from zero. |
| 1151 | /// Uses a dedicated hardware instruction when available. |
| 1152 | /// This is the same as calling the builtin @round |
| 1153 | pub inline fn round(value: anytype) @TypeOf(value) { |
| 1154 | return @round(value); |
| 1155 | } |
| 1156 | |
| 1157 | /// Rounds the given floating point number to an integer, towards zero. |
| 1158 | /// Uses a dedicated hardware instruction when available. |
| 1159 | /// This is the same as calling the builtin @trunc |
| 1160 | pub inline fn trunc(value: anytype) @TypeOf(value) { |
| 1161 | return @trunc(value); |
| 1162 | } |
| 1163 | |
| 1164 | /// Returns the largest integral value not greater than the given floating point number. |
| 1165 | /// Uses a dedicated hardware instruction when available. |
| 1166 | /// This is the same as calling the builtin @floor |
| 1167 | pub inline fn floor(value: anytype) @TypeOf(value) { |
| 1168 | return @floor(value); |
| 1169 | } |
| 1170 | |
| 1171 | /// Returns the nearest power of two less than or equal to value, or |
| 1172 | /// zero if value is less than or equal to zero. |
| 1173 | pub fn floorPowerOfTwo(comptime T: type, value: T) T { |
| 1174 | const uT = @Int(.unsigned, @typeInfo(T).int.bits); |
| 1175 | if (value <= 0) return 0; |
| 1176 | return @as(T, 1) << log2_int(uT, @as(uT, @intCast(value))); |
| 1177 | } |
| 1178 | |
| 1179 | test floorPowerOfTwo { |
| 1180 | try testFloorPowerOfTwo(); |
| 1181 | try comptime testFloorPowerOfTwo(); |
| 1182 | } |
| 1183 | |
| 1184 | fn testFloorPowerOfTwo() !void { |
| 1185 | try testing.expect(floorPowerOfTwo(u32, 63) == 32); |
| 1186 | try testing.expect(floorPowerOfTwo(u32, 64) == 64); |
| 1187 | try testing.expect(floorPowerOfTwo(u32, 65) == 64); |
| 1188 | try testing.expect(floorPowerOfTwo(u32, 0) == 0); |
| 1189 | try testing.expect(floorPowerOfTwo(u4, 7) == 4); |
| 1190 | try testing.expect(floorPowerOfTwo(u4, 8) == 8); |
| 1191 | try testing.expect(floorPowerOfTwo(u4, 9) == 8); |
| 1192 | try testing.expect(floorPowerOfTwo(u4, 0) == 0); |
| 1193 | try testing.expect(floorPowerOfTwo(i4, 7) == 4); |
| 1194 | try testing.expect(floorPowerOfTwo(i4, -8) == 0); |
| 1195 | try testing.expect(floorPowerOfTwo(i4, -1) == 0); |
| 1196 | try testing.expect(floorPowerOfTwo(i4, 0) == 0); |
| 1197 | } |
| 1198 | |
| 1199 | /// Returns the smallest integral value not less than the given floating point number. |
| 1200 | /// Uses a dedicated hardware instruction when available. |
| 1201 | /// This is the same as calling the builtin @ceil |
| 1202 | pub inline fn ceil(value: anytype) @TypeOf(value) { |
| 1203 | return @ceil(value); |
| 1204 | } |
| 1205 | |
| 1206 | /// Returns the next power of two (if the value is not already a power of two). |
| 1207 | /// Only unsigned integers can be used. Zero is not an allowed input. |
| 1208 | /// Result is a type with 1 more bit than the input type. |
| 1209 | pub fn ceilPowerOfTwoPromote(comptime T: type, value: T) @Int(@typeInfo(T).int.signedness, @typeInfo(T).int.bits + 1) { |
| 1210 | comptime assert(@typeInfo(T) == .int); |
| 1211 | comptime assert(@typeInfo(T).int.signedness == .unsigned); |
| 1212 | assert(value != 0); |
| 1213 | const PromotedType = @Int(@typeInfo(T).int.signedness, @typeInfo(T).int.bits + 1); |
| 1214 | const ShiftType = std.math.Log2Int(PromotedType); |
| 1215 | return @as(PromotedType, 1) << @as(ShiftType, @intCast(@typeInfo(T).int.bits - @clz(value - 1))); |
| 1216 | } |
| 1217 | |
| 1218 | /// Returns the next power of two (if the value is not already a power of two). |
| 1219 | /// Only unsigned integers can be used. Zero is not an allowed input. |
| 1220 | /// If the value doesn't fit, returns an error. |
| 1221 | pub fn ceilPowerOfTwo(comptime T: type, value: T) (error{Overflow}!T) { |
| 1222 | comptime assert(@typeInfo(T) == .int); |
| 1223 | const info = @typeInfo(T).int; |
| 1224 | comptime assert(info.signedness == .unsigned); |
| 1225 | const PromotedType = @Int(info.signedness, info.bits + 1); |
| 1226 | const overflowBit = @as(PromotedType, 1) << info.bits; |
| 1227 | const x = ceilPowerOfTwoPromote(T, value); |
| 1228 | if (overflowBit & x != 0) { |
| 1229 | return error.Overflow; |
| 1230 | } |
| 1231 | return @as(T, @intCast(x)); |
| 1232 | } |
| 1233 | |
| 1234 | /// Returns the next power of two (if the value is not already a power |
| 1235 | /// of two). Only unsigned integers can be used. Zero is not an |
| 1236 | /// allowed input. Asserts that the value fits. |
| 1237 | pub fn ceilPowerOfTwoAssert(comptime T: type, value: T) T { |
| 1238 | return ceilPowerOfTwo(T, value) catch unreachable; |
| 1239 | } |
| 1240 | |
| 1241 | test ceilPowerOfTwoPromote { |
| 1242 | try testCeilPowerOfTwoPromote(); |
| 1243 | try comptime testCeilPowerOfTwoPromote(); |
| 1244 | } |
| 1245 | |
| 1246 | fn testCeilPowerOfTwoPromote() !void { |
| 1247 | try testing.expectEqual(@as(u33, 1), ceilPowerOfTwoPromote(u32, 1)); |
| 1248 | try testing.expectEqual(@as(u33, 2), ceilPowerOfTwoPromote(u32, 2)); |
| 1249 | try testing.expectEqual(@as(u33, 64), ceilPowerOfTwoPromote(u32, 63)); |
| 1250 | try testing.expectEqual(@as(u33, 64), ceilPowerOfTwoPromote(u32, 64)); |
| 1251 | try testing.expectEqual(@as(u33, 128), ceilPowerOfTwoPromote(u32, 65)); |
| 1252 | try testing.expectEqual(@as(u6, 8), ceilPowerOfTwoPromote(u5, 7)); |
| 1253 | try testing.expectEqual(@as(u6, 8), ceilPowerOfTwoPromote(u5, 8)); |
| 1254 | try testing.expectEqual(@as(u6, 16), ceilPowerOfTwoPromote(u5, 9)); |
| 1255 | try testing.expectEqual(@as(u5, 16), ceilPowerOfTwoPromote(u4, 9)); |
| 1256 | } |
| 1257 | |
| 1258 | test ceilPowerOfTwo { |
| 1259 | try testCeilPowerOfTwo(); |
| 1260 | try comptime testCeilPowerOfTwo(); |
| 1261 | } |
| 1262 | |
| 1263 | fn testCeilPowerOfTwo() !void { |
| 1264 | try testing.expectEqual(@as(u32, 1), try ceilPowerOfTwo(u32, 1)); |
| 1265 | try testing.expectEqual(@as(u32, 2), try ceilPowerOfTwo(u32, 2)); |
| 1266 | try testing.expectEqual(@as(u32, 64), try ceilPowerOfTwo(u32, 63)); |
| 1267 | try testing.expectEqual(@as(u32, 64), try ceilPowerOfTwo(u32, 64)); |
| 1268 | try testing.expectEqual(@as(u32, 128), try ceilPowerOfTwo(u32, 65)); |
| 1269 | try testing.expectEqual(@as(u5, 8), try ceilPowerOfTwo(u5, 7)); |
| 1270 | try testing.expectEqual(@as(u5, 8), try ceilPowerOfTwo(u5, 8)); |
| 1271 | try testing.expectEqual(@as(u5, 16), try ceilPowerOfTwo(u5, 9)); |
| 1272 | try testing.expectError(error.Overflow, ceilPowerOfTwo(u4, 9)); |
| 1273 | } |
| 1274 | |
| 1275 | /// Return the log base 2 of integer value x, rounding down to the |
| 1276 | /// nearest integer. |
| 1277 | pub fn log2_int(comptime T: type, x: T) Log2Int(T) { |
| 1278 | if (@typeInfo(T) != .int or @typeInfo(T).int.signedness != .unsigned) |
| 1279 | @compileError("log2_int requires an unsigned integer, found " ++ @typeName(T)); |
| 1280 | assert(x != 0); |
| 1281 | return @as(Log2Int(T), @intCast(@typeInfo(T).int.bits - 1 - @clz(x))); |
| 1282 | } |
| 1283 | |
| 1284 | test log2_int { |
| 1285 | try testing.expect(log2_int(u32, 1) == 0); |
| 1286 | try testing.expect(log2_int(u32, 2) == 1); |
| 1287 | try testing.expect(log2_int(u32, 3) == 1); |
| 1288 | try testing.expect(log2_int(u32, 4) == 2); |
| 1289 | try testing.expect(log2_int(u32, 5) == 2); |
| 1290 | try testing.expect(log2_int(u32, 6) == 2); |
| 1291 | try testing.expect(log2_int(u32, 7) == 2); |
| 1292 | try testing.expect(log2_int(u32, 8) == 3); |
| 1293 | try testing.expect(log2_int(u32, 9) == 3); |
| 1294 | try testing.expect(log2_int(u32, 10) == 3); |
| 1295 | } |
| 1296 | |
| 1297 | /// Return the log base 2 of integer value x, rounding up to the |
| 1298 | /// nearest integer. |
| 1299 | pub fn log2_int_ceil(comptime T: type, x: T) Log2IntCeil(T) { |
| 1300 | if (@typeInfo(T) != .int or @typeInfo(T).int.signedness != .unsigned) |
| 1301 | @compileError("log2_int_ceil requires an unsigned integer, found " ++ @typeName(T)); |
| 1302 | assert(x != 0); |
| 1303 | if (x == 1) return 0; |
| 1304 | const log2_val: Log2IntCeil(T) = log2_int(T, x - 1); |
| 1305 | return log2_val + 1; |
| 1306 | } |
| 1307 | |
| 1308 | test log2_int_ceil { |
| 1309 | try testing.expect(log2_int_ceil(u32, 1) == 0); |
| 1310 | try testing.expect(log2_int_ceil(u32, 2) == 1); |
| 1311 | try testing.expect(log2_int_ceil(u32, 3) == 2); |
| 1312 | try testing.expect(log2_int_ceil(u32, 4) == 2); |
| 1313 | try testing.expect(log2_int_ceil(u32, 5) == 3); |
| 1314 | try testing.expect(log2_int_ceil(u32, 6) == 3); |
| 1315 | try testing.expect(log2_int_ceil(u32, 7) == 3); |
| 1316 | try testing.expect(log2_int_ceil(u32, 8) == 3); |
| 1317 | try testing.expect(log2_int_ceil(u32, 9) == 4); |
| 1318 | try testing.expect(log2_int_ceil(u32, 10) == 4); |
| 1319 | } |
| 1320 | |
| 1321 | /// Cast a value to a different type. If the value doesn't fit in, or |
| 1322 | /// can't be perfectly represented by, the new type, it will be |
| 1323 | /// converted to the closest possible representation. |
| 1324 | pub fn lossyCast(comptime T: type, value: anytype) T { |
| 1325 | switch (@typeInfo(T)) { |
| 1326 | .float => { |
| 1327 | switch (@typeInfo(@TypeOf(value))) { |
| 1328 | .int => return @floatFromInt(value), |
| 1329 | .float => return @floatCast(value), |
| 1330 | .comptime_int => return value, |
| 1331 | .comptime_float => return value, |
| 1332 | else => @compileError("bad type"), |
| 1333 | } |
| 1334 | }, |
| 1335 | .int => { |
| 1336 | switch (@typeInfo(@TypeOf(value))) { |
| 1337 | .int, .comptime_int => { |
| 1338 | if (value >= maxInt(T)) { |
| 1339 | return maxInt(T); |
| 1340 | } else if (value <= minInt(T)) { |
| 1341 | return minInt(T); |
| 1342 | } else { |
| 1343 | return @intCast(value); |
| 1344 | } |
| 1345 | }, |
| 1346 | .float, .comptime_float => { |
| 1347 | // In extreme cases, we probably need a language enhancement to be able to |
| 1348 | // specify a rounding mode here to prevent `@intFromFloat` panics. |
| 1349 | const max: @TypeOf(value) = @floatFromInt(maxInt(T)); |
| 1350 | const min: @TypeOf(value) = @floatFromInt(minInt(T)); |
| 1351 | if (isNan(value)) { |
| 1352 | return 0; |
| 1353 | } else if (value >= max) { |
| 1354 | return maxInt(T); |
| 1355 | } else if (value <= min) { |
| 1356 | return minInt(T); |
| 1357 | } else { |
| 1358 | return @intFromFloat(value); |
| 1359 | } |
| 1360 | }, |
| 1361 | else => @compileError("bad type"), |
| 1362 | } |
| 1363 | }, |
| 1364 | else => @compileError("bad result type"), |
| 1365 | } |
| 1366 | } |
| 1367 | |
| 1368 | test lossyCast { |
| 1369 | try testing.expect(lossyCast(i16, 70000.0) == @as(i16, 32767)); |
| 1370 | try testing.expect(lossyCast(u32, @as(i16, -255)) == @as(u32, 0)); |
| 1371 | try testing.expect(lossyCast(i9, @as(u32, 200)) == @as(i9, 200)); |
| 1372 | try testing.expect(lossyCast(u32, @as(f32, @floatFromInt(maxInt(u32)))) == maxInt(u32)); |
| 1373 | try testing.expect(lossyCast(u32, nan(f32)) == 0); |
| 1374 | } |
| 1375 | |
| 1376 | /// Performs linear interpolation between *a* and *b* based on *t*. |
| 1377 | /// *t* ranges from 0.0 to 1.0, but may exceed these bounds. |
| 1378 | /// Supports floats and vectors of floats. |
| 1379 | /// |
| 1380 | /// This does not guarantee returning *b* if *t* is 1 due to floating-point errors. |
| 1381 | /// This is monotonic. |
| 1382 | pub fn lerp(a: anytype, b: anytype, t: anytype) @TypeOf(a, b, t) { |
| 1383 | const Type = @TypeOf(a, b, t); |
| 1384 | return @mulAdd(Type, b - a, t, a); |
| 1385 | } |
| 1386 | |
| 1387 | test lerp { |
| 1388 | if (builtin.zig_backend == .stage2_c and builtin.cpu.arch.isArm()) return error.SkipZigTest; |
| 1389 | if (builtin.zig_backend == .stage2_c and builtin.cpu.arch.isX86()) return error.SkipZigTest; |
| 1390 | if (builtin.zig_backend == .stage2_x86_64 and !comptime builtin.cpu.has(.x86, .fma)) return error.SkipZigTest; // https://github.com/ziglang/zig/issues/17884 |
| 1391 | |
| 1392 | try testing.expectEqual(@as(f64, 75), lerp(50, 100, 0.5)); |
| 1393 | try testing.expectEqual(@as(f32, 43.75), lerp(50, 25, 0.25)); |
| 1394 | try testing.expectEqual(@as(f64, -31.25), lerp(-50, 25, 0.25)); |
| 1395 | |
| 1396 | try testing.expectEqual(@as(f64, 30), lerp(10, 20, 2.0)); |
| 1397 | try testing.expectEqual(@as(f64, 5), lerp(10, 20, -0.5)); |
| 1398 | |
| 1399 | try testing.expectApproxEqRel(@as(f32, -7.16067345e+03), lerp(-10000.12345, -5000.12345, 0.56789), 1e-19); |
| 1400 | try testing.expectApproxEqRel(@as(f64, 7.010987590521e+62), lerp(0.123456789e-64, 0.123456789e64, 0.56789), 1e-33); |
| 1401 | |
| 1402 | try testing.expectEqual(@as(f32, 0.0), lerp(@as(f32, 1.0e8), 1.0, 1.0)); |
| 1403 | try testing.expectEqual(@as(f64, 0.0), lerp(@as(f64, 1.0e16), 1.0, 1.0)); |
| 1404 | try testing.expectEqual(@as(f32, 1.0), lerp(@as(f32, 1.0e7), 1.0, 1.0)); |
| 1405 | try testing.expectEqual(@as(f64, 1.0), lerp(@as(f64, 1.0e15), 1.0, 1.0)); |
| 1406 | |
| 1407 | { |
| 1408 | const a: @Vector(3, f32) = @splat(0); |
| 1409 | const b: @Vector(3, f32) = @splat(50); |
| 1410 | const t: @Vector(3, f32) = @splat(0.5); |
| 1411 | try testing.expectEqual( |
| 1412 | @Vector(3, f32){ 25, 25, 25 }, |
| 1413 | lerp(a, b, t), |
| 1414 | ); |
| 1415 | } |
| 1416 | { |
| 1417 | const a: @Vector(3, f64) = @splat(50); |
| 1418 | const b: @Vector(3, f64) = @splat(100); |
| 1419 | const t: @Vector(3, f64) = @splat(0.5); |
| 1420 | try testing.expectEqual( |
| 1421 | @Vector(3, f64){ 75, 75, 75 }, |
| 1422 | lerp(a, b, t), |
| 1423 | ); |
| 1424 | } |
| 1425 | { |
| 1426 | const a: @Vector(2, f32) = @splat(40); |
| 1427 | const b: @Vector(2, f32) = @splat(80); |
| 1428 | const t: @Vector(2, f32) = @Vector(2, f32){ 0.25, 0.75 }; |
| 1429 | try testing.expectEqual( |
| 1430 | @Vector(2, f32){ 50, 70 }, |
| 1431 | lerp(a, b, t), |
| 1432 | ); |
| 1433 | } |
| 1434 | } |
| 1435 | |
| 1436 | /// Returns the maximum value of integer type T. |
| 1437 | pub fn maxInt(comptime T: type) comptime_int { |
| 1438 | const info = @typeInfo(T).int; |
| 1439 | return (1 << (info.bits - @intFromBool(info.signedness == .signed))) - 1; |
| 1440 | } |
| 1441 | |
| 1442 | /// Returns the minimum value of integer type T. |
| 1443 | pub fn minInt(comptime T: type) comptime_int { |
| 1444 | const info = @typeInfo(T).int; |
| 1445 | return switch (info.signedness) { |
| 1446 | .unsigned => 0, |
| 1447 | .signed => -(1 << (info.bits - 1)), |
| 1448 | }; |
| 1449 | } |
| 1450 | |
| 1451 | test maxInt { |
| 1452 | try testing.expect(maxInt(u0) == 0); |
| 1453 | try testing.expect(maxInt(u1) == 1); |
| 1454 | try testing.expect(maxInt(u8) == 255); |
| 1455 | try testing.expect(maxInt(u16) == 65535); |
| 1456 | try testing.expect(maxInt(u32) == 4294967295); |
| 1457 | try testing.expect(maxInt(u64) == 18446744073709551615); |
| 1458 | try testing.expect(maxInt(u128) == 340282366920938463463374607431768211455); |
| 1459 | |
| 1460 | try testing.expect(maxInt(i1) == 0); |
| 1461 | try testing.expect(maxInt(i8) == 127); |
| 1462 | try testing.expect(maxInt(i16) == 32767); |
| 1463 | try testing.expect(maxInt(i32) == 2147483647); |
| 1464 | try testing.expect(maxInt(i63) == 4611686018427387903); |
| 1465 | try testing.expect(maxInt(i64) == 9223372036854775807); |
| 1466 | try testing.expect(maxInt(i128) == 170141183460469231731687303715884105727); |
| 1467 | } |
| 1468 | |
| 1469 | test minInt { |
| 1470 | try testing.expect(minInt(u0) == 0); |
| 1471 | try testing.expect(minInt(u1) == 0); |
| 1472 | try testing.expect(minInt(u8) == 0); |
| 1473 | try testing.expect(minInt(u16) == 0); |
| 1474 | try testing.expect(minInt(u32) == 0); |
| 1475 | try testing.expect(minInt(u63) == 0); |
| 1476 | try testing.expect(minInt(u64) == 0); |
| 1477 | try testing.expect(minInt(u128) == 0); |
| 1478 | |
| 1479 | try testing.expect(minInt(i1) == -1); |
| 1480 | try testing.expect(minInt(i8) == -128); |
| 1481 | try testing.expect(minInt(i16) == -32768); |
| 1482 | try testing.expect(minInt(i32) == -2147483648); |
| 1483 | try testing.expect(minInt(i63) == -4611686018427387904); |
| 1484 | try testing.expect(minInt(i64) == -9223372036854775808); |
| 1485 | try testing.expect(minInt(i128) == -170141183460469231731687303715884105728); |
| 1486 | } |
| 1487 | |
| 1488 | test "max value type" { |
| 1489 | const x: u32 = maxInt(i32); |
| 1490 | try testing.expect(x == 2147483647); |
| 1491 | } |
| 1492 | |
| 1493 | /// Multiply a and b. Return type is wide enough to guarantee no |
| 1494 | /// overflow. |
| 1495 | pub fn mulWide(comptime T: type, a: T, b: T) @Int( |
| 1496 | @typeInfo(T).int.signedness, |
| 1497 | @typeInfo(T).int.bits * 2, |
| 1498 | ) { |
| 1499 | const ResultInt = @Int( |
| 1500 | @typeInfo(T).int.signedness, |
| 1501 | @typeInfo(T).int.bits * 2, |
| 1502 | ); |
| 1503 | return @as(ResultInt, a) * @as(ResultInt, b); |
| 1504 | } |
| 1505 | |
| 1506 | test mulWide { |
| 1507 | try testing.expect(mulWide(u8, 5, 5) == 25); |
| 1508 | try testing.expect(mulWide(i8, 5, -5) == -25); |
| 1509 | try testing.expect(mulWide(u8, 100, 100) == 10000); |
| 1510 | } |
| 1511 | |
| 1512 | /// See also `CompareOperator`. |
| 1513 | pub const Order = enum { |
| 1514 | /// Greater than (`>`) |
| 1515 | gt, |
| 1516 | |
| 1517 | /// Less than (`<`) |
| 1518 | lt, |
| 1519 | |
| 1520 | /// Equal (`==`) |
| 1521 | eq, |
| 1522 | |
| 1523 | pub fn invert(self: Order) Order { |
| 1524 | return switch (self) { |
| 1525 | .lt => .gt, |
| 1526 | .eq => .eq, |
| 1527 | .gt => .lt, |
| 1528 | }; |
| 1529 | } |
| 1530 | |
| 1531 | test invert { |
| 1532 | try testing.expect(Order.invert(order(0, 0)) == .eq); |
| 1533 | try testing.expect(Order.invert(order(1, 0)) == .lt); |
| 1534 | try testing.expect(Order.invert(order(-1, 0)) == .gt); |
| 1535 | } |
| 1536 | |
| 1537 | pub fn differ(self: Order) ?Order { |
| 1538 | return if (self != .eq) self else null; |
| 1539 | } |
| 1540 | |
| 1541 | test differ { |
| 1542 | const neg: i32 = -1; |
| 1543 | const zero: i32 = 0; |
| 1544 | const pos: i32 = 1; |
| 1545 | try testing.expect(order(zero, neg).differ() orelse |
| 1546 | order(pos, zero) == .gt); |
| 1547 | try testing.expect(order(zero, zero).differ() orelse |
| 1548 | order(zero, zero) == .eq); |
| 1549 | try testing.expect(order(pos, pos).differ() orelse |
| 1550 | order(neg, zero) == .lt); |
| 1551 | try testing.expect(order(zero, zero).differ() orelse |
| 1552 | order(pos, neg).differ() orelse |
| 1553 | order(neg, zero) == .gt); |
| 1554 | try testing.expect(order(pos, pos).differ() orelse |
| 1555 | order(pos, pos).differ() orelse |
| 1556 | order(neg, neg) == .eq); |
| 1557 | try testing.expect(order(zero, pos).differ() orelse |
| 1558 | order(neg, pos).differ() orelse |
| 1559 | order(pos, neg) == .lt); |
| 1560 | } |
| 1561 | |
| 1562 | pub fn compare(self: Order, op: CompareOperator) bool { |
| 1563 | return switch (self) { |
| 1564 | .lt => switch (op) { |
| 1565 | .lt => true, |
| 1566 | .lte => true, |
| 1567 | .eq => false, |
| 1568 | .gte => false, |
| 1569 | .gt => false, |
| 1570 | .neq => true, |
| 1571 | }, |
| 1572 | .eq => switch (op) { |
| 1573 | .lt => false, |
| 1574 | .lte => true, |
| 1575 | .eq => true, |
| 1576 | .gte => true, |
| 1577 | .gt => false, |
| 1578 | .neq => false, |
| 1579 | }, |
| 1580 | .gt => switch (op) { |
| 1581 | .lt => false, |
| 1582 | .lte => false, |
| 1583 | .eq => false, |
| 1584 | .gte => true, |
| 1585 | .gt => true, |
| 1586 | .neq => true, |
| 1587 | }, |
| 1588 | }; |
| 1589 | } |
| 1590 | |
| 1591 | // https://github.com/ziglang/zig/issues/19295 |
| 1592 | test "compare" { |
| 1593 | try testing.expect(order(-1, 0).compare(.lt)); |
| 1594 | try testing.expect(order(-1, 0).compare(.lte)); |
| 1595 | try testing.expect(order(0, 0).compare(.lte)); |
| 1596 | try testing.expect(order(0, 0).compare(.eq)); |
| 1597 | try testing.expect(order(0, 0).compare(.gte)); |
| 1598 | try testing.expect(order(1, 0).compare(.gte)); |
| 1599 | try testing.expect(order(1, 0).compare(.gt)); |
| 1600 | try testing.expect(order(1, 0).compare(.neq)); |
| 1601 | } |
| 1602 | }; |
| 1603 | |
| 1604 | /// Given two numbers, this function returns the order they are with respect to each other. |
| 1605 | pub fn order(a: anytype, b: anytype) Order { |
| 1606 | if (a == b) { |
| 1607 | return .eq; |
| 1608 | } else if (a < b) { |
| 1609 | return .lt; |
| 1610 | } else if (a > b) { |
| 1611 | return .gt; |
| 1612 | } else { |
| 1613 | unreachable; |
| 1614 | } |
| 1615 | } |
| 1616 | |
| 1617 | /// See also `Order`. |
| 1618 | pub const CompareOperator = enum { |
| 1619 | /// Less than (`<`) |
| 1620 | lt, |
| 1621 | /// Less than or equal (`<=`) |
| 1622 | lte, |
| 1623 | /// Equal (`==`) |
| 1624 | eq, |
| 1625 | /// Greater than or equal (`>=`) |
| 1626 | gte, |
| 1627 | /// Greater than (`>`) |
| 1628 | gt, |
| 1629 | /// Not equal (`!=`) |
| 1630 | neq, |
| 1631 | |
| 1632 | /// Reverse the direction of the comparison. |
| 1633 | /// Use when swapping the left and right hand operands. |
| 1634 | pub fn reverse(op: CompareOperator) CompareOperator { |
| 1635 | return switch (op) { |
| 1636 | .lt => .gt, |
| 1637 | .lte => .gte, |
| 1638 | .gt => .lt, |
| 1639 | .gte => .lte, |
| 1640 | .eq => .eq, |
| 1641 | .neq => .neq, |
| 1642 | }; |
| 1643 | } |
| 1644 | |
| 1645 | test reverse { |
| 1646 | inline for (@typeInfo(CompareOperator).@"enum".field_values) |op_field_value| { |
| 1647 | const op = @as(CompareOperator, @fromBackingInt(@intCast(op_field_value))); |
| 1648 | try testing.expect(compare(2, op, 3) == compare(3, op.reverse(), 2)); |
| 1649 | try testing.expect(compare(3, op, 3) == compare(3, op.reverse(), 3)); |
| 1650 | try testing.expect(compare(4, op, 3) == compare(3, op.reverse(), 4)); |
| 1651 | } |
| 1652 | } |
| 1653 | }; |
| 1654 | |
| 1655 | /// This function does the same thing as comparison operators, however the |
| 1656 | /// operator is a runtime-known enum value. Works on any operands that |
| 1657 | /// support comparison operators. |
| 1658 | pub fn compare(a: anytype, op: CompareOperator, b: anytype) bool { |
| 1659 | return switch (op) { |
| 1660 | .lt => a < b, |
| 1661 | .lte => a <= b, |
| 1662 | .eq => a == b, |
| 1663 | .neq => a != b, |
| 1664 | .gt => a > b, |
| 1665 | .gte => a >= b, |
| 1666 | }; |
| 1667 | } |
| 1668 | |
| 1669 | test compare { |
| 1670 | try testing.expect(compare(@as(i8, -1), .lt, @as(u8, 255))); |
| 1671 | try testing.expect(compare(@as(i8, 2), .gt, @as(u8, 1))); |
| 1672 | try testing.expect(!compare(@as(i8, -1), .gte, @as(u8, 255))); |
| 1673 | try testing.expect(compare(@as(u8, 255), .gt, @as(i8, -1))); |
| 1674 | try testing.expect(!compare(@as(u8, 255), .lte, @as(i8, -1))); |
| 1675 | try testing.expect(compare(@as(i8, -1), .lt, @as(u9, 255))); |
| 1676 | try testing.expect(!compare(@as(i8, -1), .gte, @as(u9, 255))); |
| 1677 | try testing.expect(compare(@as(u9, 255), .gt, @as(i8, -1))); |
| 1678 | try testing.expect(!compare(@as(u9, 255), .lte, @as(i8, -1))); |
| 1679 | try testing.expect(compare(@as(i9, -1), .lt, @as(u8, 255))); |
| 1680 | try testing.expect(!compare(@as(i9, -1), .gte, @as(u8, 255))); |
| 1681 | try testing.expect(compare(@as(u8, 255), .gt, @as(i9, -1))); |
| 1682 | try testing.expect(!compare(@as(u8, 255), .lte, @as(i9, -1))); |
| 1683 | try testing.expect(compare(@as(u8, 1), .lt, @as(u8, 2))); |
| 1684 | try testing.expect(@as(u8, @bitCast(@as(i8, -1))) == @as(u8, 255)); |
| 1685 | try testing.expect(!compare(@as(u8, 255), .eq, @as(i8, -1))); |
| 1686 | try testing.expect(compare(@as(u8, 1), .eq, @as(u8, 1))); |
| 1687 | } |
| 1688 | |
| 1689 | test order { |
| 1690 | try testing.expect(order(0, 0) == .eq); |
| 1691 | try testing.expect(order(1, 0) == .gt); |
| 1692 | try testing.expect(order(-1, 0) == .lt); |
| 1693 | } |
| 1694 | |
| 1695 | /// Returns a mask of all ones if value is true, |
| 1696 | /// and a mask of all zeroes if value is false. |
| 1697 | /// Compiles to one instruction for register sized integers. |
| 1698 | pub inline fn boolMask(comptime MaskInt: type, value: bool) MaskInt { |
| 1699 | if (@typeInfo(MaskInt) != .int) |
| 1700 | @compileError("boolMask requires an integer mask type."); |
| 1701 | |
| 1702 | if (MaskInt == u0) |
| 1703 | @compileError("boolMask cannot convert to u0, it is too small."); |
| 1704 | |
| 1705 | // The u1 and i1 cases tend to overflow, |
| 1706 | // so we special case them here. |
| 1707 | if (MaskInt == u1) return @intFromBool(value); |
| 1708 | if (MaskInt == i1) { |
| 1709 | // The @as here is a workaround for #7950 |
| 1710 | return @as(i1, @bitCast(@as(u1, @intFromBool(value)))); |
| 1711 | } |
| 1712 | |
| 1713 | return -%@as(MaskInt, @intCast(@intFromBool(value))); |
| 1714 | } |
| 1715 | |
| 1716 | test boolMask { |
| 1717 | const runTest = struct { |
| 1718 | fn runTest() !void { |
| 1719 | try testing.expectEqual(@as(u1, 0), boolMask(u1, false)); |
| 1720 | try testing.expectEqual(@as(u1, 1), boolMask(u1, true)); |
| 1721 | |
| 1722 | try testing.expectEqual(@as(i1, 0), boolMask(i1, false)); |
| 1723 | try testing.expectEqual(@as(i1, -1), boolMask(i1, true)); |
| 1724 | |
| 1725 | try testing.expectEqual(@as(u13, 0), boolMask(u13, false)); |
| 1726 | try testing.expectEqual(@as(u13, 0x1FFF), boolMask(u13, true)); |
| 1727 | |
| 1728 | try testing.expectEqual(@as(i13, 0), boolMask(i13, false)); |
| 1729 | try testing.expectEqual(@as(i13, -1), boolMask(i13, true)); |
| 1730 | |
| 1731 | try testing.expectEqual(@as(u32, 0), boolMask(u32, false)); |
| 1732 | try testing.expectEqual(@as(u32, 0xFFFF_FFFF), boolMask(u32, true)); |
| 1733 | |
| 1734 | try testing.expectEqual(@as(i32, 0), boolMask(i32, false)); |
| 1735 | try testing.expectEqual(@as(i32, -1), boolMask(i32, true)); |
| 1736 | } |
| 1737 | }.runTest; |
| 1738 | try runTest(); |
| 1739 | try comptime runTest(); |
| 1740 | } |
| 1741 | |
| 1742 | /// Return the mod of `num` with the smallest integer type |
| 1743 | pub fn comptimeMod(num: anytype, comptime denom: comptime_int) IntFittingRange(0, denom - 1) { |
| 1744 | return @as(IntFittingRange(0, denom - 1), @intCast(@mod(num, denom))); |
| 1745 | } |
| 1746 | |
| 1747 | pub const F80 = struct { |
| 1748 | fraction: u64, |
| 1749 | exp: u16, |
| 1750 | |
| 1751 | pub fn toFloat(self: F80) f80 { |
| 1752 | const int = (@as(u80, self.exp) << 64) | self.fraction; |
| 1753 | return @as(f80, @bitCast(int)); |
| 1754 | } |
| 1755 | |
| 1756 | pub fn fromFloat(x: f80) F80 { |
| 1757 | const int = @as(u80, @bitCast(x)); |
| 1758 | return .{ |
| 1759 | .fraction = @as(u64, @truncate(int)), |
| 1760 | .exp = @as(u16, @truncate(int >> 64)), |
| 1761 | }; |
| 1762 | } |
| 1763 | }; |
| 1764 | |
| 1765 | fn SignOf(T: type) type { |
| 1766 | return switch (@typeInfo(T)) { |
| 1767 | .comptime_int, .comptime_float => comptime_int, |
| 1768 | .int => IntFittingRange(@max(minInt(T), -1), @min(maxInt(T), 1)), |
| 1769 | .float => IntFittingRange(-1, 1), |
| 1770 | .vector => |vec| @Vector(vec.len, SignOf(vec.child)), |
| 1771 | else => @compileError("Expected an int, float, or a vector of one, found " ++ @typeName(T)), |
| 1772 | }; |
| 1773 | } |
| 1774 | |
| 1775 | /// Returns -1, 0, or 1. |
| 1776 | /// Supports integer and float types and vectors of integer and float types. |
| 1777 | /// Unsigned integer types will always return 0 or 1. |
| 1778 | /// The returned integer type is the smallest that fits the possible values. |
| 1779 | /// Branchless. |
| 1780 | pub inline fn sign(n: anytype) SignOf(@TypeOf(n)) { |
| 1781 | const T = SignOf(@TypeOf(n)); |
| 1782 | const zero: T = if (@typeInfo(T) == .vector) @splat(0) else 0; |
| 1783 | const pos: T = @intCast(@intFromBool(n > zero)); |
| 1784 | const neg: T = @intCast(@intFromBool(n < zero)); |
| 1785 | return pos - neg; |
| 1786 | } |
| 1787 | |
| 1788 | fn testSign() !void { |
| 1789 | // each of the following blocks checks the inputs |
| 1790 | // 2, -2, 0, { 2, -2, 0 } provide expected output |
| 1791 | // 1, -1, 0, { 1, -1, 0 } for the given T |
| 1792 | // (negative values omitted for unsigned types) |
| 1793 | { |
| 1794 | const T = i8; |
| 1795 | try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2))); |
| 1796 | try std.testing.expectEqual(@as(T, -1), sign(@as(T, -2))); |
| 1797 | try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0))); |
| 1798 | try std.testing.expectEqual(@Vector(3, T){ 1, -1, 0 }, sign(@Vector(3, T){ 2, -2, 0 })); |
| 1799 | } |
| 1800 | { |
| 1801 | const T = i32; |
| 1802 | try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2))); |
| 1803 | try std.testing.expectEqual(@as(T, -1), sign(@as(T, -2))); |
| 1804 | try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0))); |
| 1805 | try std.testing.expectEqual(@Vector(3, T){ 1, -1, 0 }, sign(@Vector(3, T){ 2, -2, 0 })); |
| 1806 | } |
| 1807 | { |
| 1808 | const T = i64; |
| 1809 | try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2))); |
| 1810 | try std.testing.expectEqual(@as(T, -1), sign(@as(T, -2))); |
| 1811 | try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0))); |
| 1812 | try std.testing.expectEqual(@Vector(3, T){ 1, -1, 0 }, sign(@Vector(3, T){ 2, -2, 0 })); |
| 1813 | } |
| 1814 | { |
| 1815 | const T = u8; |
| 1816 | try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2))); |
| 1817 | try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0))); |
| 1818 | try std.testing.expectEqual(@Vector(2, T){ 1, 0 }, sign(@Vector(2, T){ 2, 0 })); |
| 1819 | } |
| 1820 | { |
| 1821 | const T = u32; |
| 1822 | try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2))); |
| 1823 | try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0))); |
| 1824 | try std.testing.expectEqual(@Vector(2, T){ 1, 0 }, sign(@Vector(2, T){ 2, 0 })); |
| 1825 | } |
| 1826 | { |
| 1827 | const T = u64; |
| 1828 | try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2))); |
| 1829 | try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0))); |
| 1830 | try std.testing.expectEqual(@Vector(2, T){ 1, 0 }, sign(@Vector(2, T){ 2, 0 })); |
| 1831 | } |
| 1832 | { |
| 1833 | const T = f16; |
| 1834 | try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2))); |
| 1835 | try std.testing.expectEqual(@as(T, -1), sign(@as(T, -2))); |
| 1836 | try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0))); |
| 1837 | try std.testing.expectEqual(@Vector(3, T){ 1, -1, 0 }, sign(@Vector(3, T){ 2, -2, 0 })); |
| 1838 | } |
| 1839 | { |
| 1840 | const T = f32; |
| 1841 | try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2))); |
| 1842 | try std.testing.expectEqual(@as(T, -1), sign(@as(T, -2))); |
| 1843 | try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0))); |
| 1844 | try std.testing.expectEqual(@Vector(3, T){ 1, -1, 0 }, sign(@Vector(3, T){ 2, -2, 0 })); |
| 1845 | } |
| 1846 | { |
| 1847 | const T = f64; |
| 1848 | try std.testing.expectEqual(@as(T, 1), sign(@as(T, 2))); |
| 1849 | try std.testing.expectEqual(@as(T, -1), sign(@as(T, -2))); |
| 1850 | try std.testing.expectEqual(@as(T, 0), sign(@as(T, 0))); |
| 1851 | try std.testing.expectEqual(@Vector(3, T){ 1, -1, 0 }, sign(@Vector(3, T){ 2, -2, 0 })); |
| 1852 | } |
| 1853 | |
| 1854 | // comptime_int |
| 1855 | try std.testing.expectEqual(-1, sign(-10)); |
| 1856 | try std.testing.expectEqual(1, sign(10)); |
| 1857 | try std.testing.expectEqual(0, sign(0)); |
| 1858 | // comptime_float |
| 1859 | try std.testing.expectEqual(-1.0, sign(-10.0)); |
| 1860 | try std.testing.expectEqual(1.0, sign(10.0)); |
| 1861 | try std.testing.expectEqual(0.0, sign(0.0)); |
| 1862 | } |
| 1863 | |
| 1864 | test sign { |
| 1865 | try testSign(); |
| 1866 | try comptime testSign(); |
| 1867 | } |
| 1868 | |
| 1869 | /// Increases the bit width of an integer by copying the most significant bit. |
| 1870 | /// This results in the input and output having the same arithmetic value, when |
| 1871 | /// interpreted as two's complement integers. |
| 1872 | pub fn signExtend(To: type, n: anytype) To { |
| 1873 | const From = @TypeOf(n); |
| 1874 | if (From == u0) return 0; |
| 1875 | const FromSigned = @Int(.signed, @typeInfo(From).int.bits); |
| 1876 | const ToSigned = @Int(.signed, @typeInfo(To).int.bits); |
| 1877 | |
| 1878 | return @bitCast(@as(ToSigned, @as(FromSigned, @bitCast(n)))); |
| 1879 | } |
| 1880 | |
| 1881 | test signExtend { |
| 1882 | const number: u8 = 0x86; |
| 1883 | try testing.expectEqual(0xff86, signExtend(u16, number)); |
| 1884 | |
| 1885 | try testing.expectEqual(0, signExtend(u1, @as(u0, 0))); |
| 1886 | try testing.expectEqual(0, signExtend(u16, @as(u0, 0))); |
| 1887 | |
| 1888 | try testing.expectEqual(0x0000, signExtend(u16, @as(u1, 0b0))); |
| 1889 | try testing.expectEqual(0xffff, signExtend(u16, @as(u1, 0b1))); |
| 1890 | |
| 1891 | try testing.expectEqual(0b000, signExtend(u3, @as(u2, 0b00))); |
| 1892 | try testing.expectEqual(0b001, signExtend(u3, @as(u2, 0b01))); |
| 1893 | try testing.expectEqual(0b110, signExtend(u3, @as(u2, 0b10))); |
| 1894 | try testing.expectEqual(0b111, signExtend(u3, @as(u2, 0b11))); |
| 1895 | try testing.expectEqual(0b0000_0001, signExtend(u8, @as(u2, 0b01))); |
| 1896 | try testing.expectEqual(0b1111_1110, signExtend(u8, @as(u2, 0b10))); |
| 1897 | |
| 1898 | try testing.expectEqual(0x0039, signExtend(u16, @as(u8, 0x39))); |
| 1899 | try testing.expectEqual(0xff93, signExtend(u16, @as(u8, 0x93))); |
| 1900 | |
| 1901 | try testing.expectEqual(5, signExtend(i32, @as(i8, 5))); |
| 1902 | try testing.expectEqual(-123, signExtend(i16, @as(i8, -123))); |
| 1903 | } |