zig/lib/c/stdlib.zig
David 55848363fd
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>
2025-05-21 00:57:38 +02:00

40 lines
1.0 KiB
Zig

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));
}