font/sfnt: simpler and more efficient FixedType conversions

This commit is contained in:
Qwerasd
2025-07-04 09:28:13 -06:00
parent 5553f7bf68
commit 1a8a048136

View File

@ -76,24 +76,22 @@ fn FixedPoint(comptime T: type, int_bits: u64, frac_bits: u64) type {
)); ));
const half = @as(T, 1) << @intCast(frac_bits - 1); const half = @as(T, 1) << @intCast(frac_bits - 1);
frac: std.meta.Int(.unsigned, frac_bits), const Frac = std.meta.Int(.unsigned, frac_bits);
int: std.meta.Int(type_info.signedness, int_bits), const Int = std.meta.Int(type_info.signedness, int_bits);
frac: Frac,
int: Int,
pub fn to(self: Self, comptime FloatType: type) FloatType { pub fn to(self: Self, comptime FloatType: type) FloatType {
const i: FloatType = @floatFromInt(self.int); return @as(FloatType, @floatFromInt(
const f: FloatType = @floatFromInt(self.frac); @as(T, @bitCast(self)),
)) / frac_factor;
return i + f / frac_factor;
} }
pub fn from(float: anytype) Self { pub fn from(float: anytype) Self {
const int = @floor(float); return @bitCast(
const frac = @abs(float - int); @as(T, @intFromFloat(@round(float * frac_factor))),
);
return .{
.int = @intFromFloat(int),
.frac = @intFromFloat(@round(frac * frac_factor)),
};
} }
/// Round to the nearest integer, .5 rounds away from 0. /// Round to the nearest integer, .5 rounds away from 0.