| ... | ... | @@ -39,7 +39,13 @@ pub fn sqrt(x: anytype) Sqrt(@TypeOf(x)) { |
| 39 | 39 | } |
| 40 | 40 | } |
| 41 | 41 | |
| 42 | | fn sqrt_int(comptime T: type, value: T) std.meta.Int(.unsigned, @typeInfo(T).Int.bits / 2) { |
| 42 | fn sqrt_int(comptime T: type, value: T) Sqrt(T) { |
| 43 | switch (T) { |
| 44 | u0 => return 0, |
| 45 | u1 => return value, |
| 46 | else => {}, |
| 47 | } |
| 48 | |
| 43 | 49 | var op = value; |
| 44 | 50 | var res: T = 0; |
| 45 | 51 | var one: T = 1 << (@typeInfo(T).Int.bits - 2); |
| ... | ... | @@ -58,11 +64,13 @@ fn sqrt_int(comptime T: type, value: T) std.meta.Int(.unsigned, @typeInfo(T).Int |
| 58 | 64 | one >>= 2; |
| 59 | 65 | } |
| 60 | 66 | |
| 61 | | const ResultType = std.meta.Int(.unsigned, @typeInfo(T).Int.bits / 2); |
| 67 | const ResultType = Sqrt(T); |
| 62 | 68 | return @intCast(ResultType, res); |
| 63 | 69 | } |
| 64 | 70 | |
| 65 | 71 | test "math.sqrt_int" { |
| 72 | expect(sqrt_int(u0, 0) == 0); |
| 73 | expect(sqrt_int(u1, 1) == 1); |
| 66 | 74 | expect(sqrt_int(u32, 3) == 1); |
| 67 | 75 | expect(sqrt_int(u32, 4) == 2); |
| 68 | 76 | expect(sqrt_int(u32, 5) == 2); |
| ... | ... | @@ -74,7 +82,13 @@ test "math.sqrt_int" { |
| 74 | 82 | /// Returns the return type `sqrt` will return given an operand of type `T`. |
| 75 | 83 | pub fn Sqrt(comptime T: type) type { |
| 76 | 84 | return switch (@typeInfo(T)) { |
| 77 | | .Int => |int| std.meta.Int(.unsigned, int.bits / 2), |
| 85 | .Int => |int| { |
| 86 | return switch (int.bits) { |
| 87 | 0 => u0, |
| 88 | 1 => u1, |
| 89 | else => std.meta.Int(.unsigned, int.bits / 2), |
| 90 | }; |
| 91 | }, |
| 78 | 92 | else => T, |
| 79 | 93 | }; |
| 80 | 94 | } |