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>
This commit is contained in:
20
lib/c/inttypes.zig
Normal file
20
lib/c/inttypes.zig
Normal file
@@ -0,0 +1,20 @@
|
||||
const std = @import("std");
|
||||
const common = @import("common.zig");
|
||||
const builtin = @import("builtin");
|
||||
const intmax_t = std.c.intmax_t;
|
||||
|
||||
comptime {
|
||||
if (builtin.target.isMuslLibC() or builtin.target.isWasiLibC()) {
|
||||
// Functions specific to musl and wasi-libc.
|
||||
@export(&imaxabs, .{ .name = "imaxabs", .linkage = common.linkage, .visibility = common.visibility });
|
||||
}
|
||||
}
|
||||
|
||||
fn imaxabs(a: intmax_t) callconv(.c) intmax_t {
|
||||
return @intCast(@abs(a));
|
||||
}
|
||||
|
||||
test imaxabs {
|
||||
const val: intmax_t = -10;
|
||||
try std.testing.expectEqual(10, imaxabs(val));
|
||||
}
|
||||
39
lib/c/stdlib.zig
Normal file
39
lib/c/stdlib.zig
Normal file
@@ -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));
|
||||
}
|
||||
Reference in New Issue
Block a user