Is there a nicer way of writing this?
inline fn isComptimeKnown(value: usize) bool {
return @TypeOfT@aspeOf(@as([*]u8, @ptrFromInt(1))[0..value]) != []u8;
}
I use it to encode a comptime-known value as an immediate in inline assembly (an optimization LLVM intentionally cannot do):
pub inline fn write(comptime name: []const u8, value: usize) void {
if (isComptimeKnown(value) and value >> 12 == 0) {
asm volatile (std.fmt.comptimePrint("csrwi {s}, {d}", .{ name, value }));
return;
}
asm volatile (std.fmt.comptimePrint("csrw {s}, %[value]", .{name})
:
: [value] "r" (value),
);
}
vulpesx
2
do you think this is nicer?
inline fn isComptimeKnown(value: anytype) bool {
const tuple = .{ value };
return @typeInfo(@TypeOf(tuple)).@"struct".field_attrs[0].@"comptime";
}
However, comptime fields are going to be removed (they are super buggy anyway)
to work around that you can do this, which might be nicer anyway
inline fn isComptimeKnown(value: anytype) bool {
// explicit type needed while `comptime` fields still exist
const tuple: struct { @TypeOf(value), u8 } = .{ value, 1 };
return @TypeOf(""[0..tuple[1]]) != []const u8;
}
Both of these work for any type, unlike yours which only works for integers
which could be reduced by using "" instead of @ptrFromInt