aboutsummaryrefslogtreecommitdiff
path: root/lib/c/stdlib.zig
diff options
context:
space:
mode:
authorDavid <seda18@rolmail.net>2025-05-21 00:57:38 +0200
committerGitHub <noreply@github.com>2025-05-21 00:57:38 +0200
commit55848363fd5c88bd6313880e770515a9c548c0df (patch)
tree1c2cb9fe2d20f6273d41e238aa366f775611f413 /lib/c/stdlib.zig
parenta63f7875f451bda975ddabcc0c1feed10a216516 (diff)
downloadzig-55848363fd5c88bd6313880e770515a9c548c0df.tar.gz
zig-55848363fd5c88bd6313880e770515a9c548c0df.zip
libc: implement common `abs` for various integer sizes (#23893)
* libc: implement common `abs` for various integer sizes * libc: move imaxabs to inttypes.zig and don't use cInclude * libc: delete `fabs` c implementations because already implemented in compiler_rt * libc: export functions depending on the target libc Previously all the functions that were exported were handled equally, though some may exist and some not inside the same file. Moving the checks inside the file allows handling different functions differently * remove empty ifs in inttypes Co-authored-by: Alex Rønne Petersen <alex@alexrp.com> * remove empty ifs in stdlib Co-authored-by: Alex Rønne Petersen <alex@alexrp.com> * libc: use `@abs` for the absolute value calculation --------- Co-authored-by: Alex Rønne Petersen <alex@alexrp.com>
Diffstat (limited to 'lib/c/stdlib.zig')
-rw-r--r--lib/c/stdlib.zig39
1 files changed, 39 insertions, 0 deletions
diff --git a/lib/c/stdlib.zig b/lib/c/stdlib.zig
new file mode 100644
index 0000000000..e427771640
--- /dev/null
+++ b/lib/c/stdlib.zig
@@ -0,0 +1,39 @@
+const std = @import("std");
+const common = @import("common.zig");
+const builtin = @import("builtin");
+
+comptime {
+ if (builtin.target.isMuslLibC() or builtin.target.isWasiLibC()) {
+ // Functions specific to musl and wasi-libc.
+ @export(&abs, .{ .name = "abs", .linkage = common.linkage, .visibility = common.visibility });
+ @export(&labs, .{ .name = "labs", .linkage = common.linkage, .visibility = common.visibility });
+ @export(&llabs, .{ .name = "llabs", .linkage = common.linkage, .visibility = common.visibility });
+ }
+}
+
+fn abs(a: c_int) callconv(.c) c_int {
+ return @intCast(@abs(a));
+}
+
+fn labs(a: c_long) callconv(.c) c_long {
+ return @intCast(@abs(a));
+}
+
+fn llabs(a: c_longlong) callconv(.c) c_longlong {
+ return @intCast(@abs(a));
+}
+
+test abs {
+ const val: c_int = -10;
+ try std.testing.expectEqual(10, abs(val));
+}
+
+test labs {
+ const val: c_long = -10;
+ try std.testing.expectEqual(10, labs(val));
+}
+
+test llabs {
+ const val: c_longlong = -10;
+ try std.testing.expectEqual(10, llabs(val));
+}