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