authorgravatar for thatlemon@gmail.comLemonBoy <thatlemon@gmail.com> 2021-04-14 17:52:24+02:00
committergravatar for thatlemon@gmail.comLemonBoy <thatlemon@gmail.com> 2021-04-14 17:53:27+02:00
log2ebd6bd7060dab3347a736ffd8a0ca5914624dc4
tree39a13abd6ec1832572010d46db05f2bc38ba4f45
parentebf97627fd4e1ee46c1b446108e4b4e3bf4b5769

std: Fix sqrt for u0/u1 input types


1 files changed, 17 insertions(+), 3 deletions(-)

lib/std/math/sqrt.zig+17-3
......@@ -39,7 +39,13 @@ pub fn sqrt(x: anytype) Sqrt(@TypeOf(x)) {
3939 }
4040}
4141
42fn sqrt_int(comptime T: type, value: T) std.meta.Int(.unsigned, @typeInfo(T).Int.bits / 2) {
42fn sqrt_int(comptime T: type, value: T) Sqrt(T) {
43 switch (T) {
44 u0 => return 0,
45 u1 => return value,
46 else => {},
47 }
48
4349 var op = value;
4450 var res: T = 0;
4551 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
5864 one >>= 2;
5965 }
6066
61 const ResultType = std.meta.Int(.unsigned, @typeInfo(T).Int.bits / 2);
67 const ResultType = Sqrt(T);
6268 return @intCast(ResultType, res);
6369}
6470
6571test "math.sqrt_int" {
72 expect(sqrt_int(u0, 0) == 0);
73 expect(sqrt_int(u1, 1) == 1);
6674 expect(sqrt_int(u32, 3) == 1);
6775 expect(sqrt_int(u32, 4) == 2);
6876 expect(sqrt_int(u32, 5) == 2);
......@@ -74,7 +82,13 @@ test "math.sqrt_int" {
7482/// Returns the return type `sqrt` will return given an operand of type `T`.
7583pub fn Sqrt(comptime T: type) type {
7684 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 },
7892 else => T,
7993 };
8094}