From e380af70568677ded64bc50005cd224b1bb784da Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Tue, 21 Feb 2023 23:18:37 -0600 Subject: [PATCH] chore: use a more efficient decimal->bcd algorithm This will not improve perf in any way because this code only gets run one time a second orz --- src/core/bus/gpio.zig | 30 +++++++++++------------------- src/main.zig | 2 +- 2 files changed, 12 insertions(+), 20 deletions(-) diff --git a/src/core/bus/gpio.zig b/src/core/bus/gpio.zig index 9b2b2d2..93716b5 100644 --- a/src/core/bus/gpio.zig +++ b/src/core/bus/gpio.zig @@ -293,13 +293,13 @@ pub const Clock = struct { self.cpu.sched.push(.RealTimeClock, (1 << 24) -| late); // Reschedule const now = DateTime.now(); - self.year = bcd(u8, @intCast(u8, now.date.year - 2000)); - self.month = bcd(u5, now.date.month); - self.day = bcd(u6, now.date.day); - self.weekday = bcd(u3, (now.date.weekday() + 1) % 7); // API is Monday = 0, Sunday = 6. We want Sunday = 0, Saturday = 6 - self.hour = bcd(u6, now.time.hour); - self.minute = bcd(u7, now.time.minute); - self.second = bcd(u7, now.time.second); + self.year = bcd(@intCast(u8, now.date.year - 2000)); + self.month = @truncate(u5, bcd(now.date.month)); + self.day = @truncate(u6, bcd(now.date.day)); + self.weekday = @truncate(u3, bcd((now.date.weekday() + 1) % 7)); // API is Monday = 0, Sunday = 6. We want Sunday = 0, Saturday = 6 + self.hour = @truncate(u6, bcd(now.time.hour)); + self.minute = @truncate(u7, bcd(now.time.minute)); + self.second = @truncate(u7, bcd(now.time.second)); } fn step(self: *Self, value: Data) u4 { @@ -449,16 +449,8 @@ pub const Clock = struct { } }; -fn bcd(comptime T: type, value: u8) T { - var input = value; - var ret: u8 = 0; - var shift: u3 = 0; - - while (input > 0) { - ret |= (input % 10) << (shift << 2); - shift += 1; - input /= 10; - } - - return @truncate(T, ret); +/// Converts an 8-bit unsigned integer to its BCD representation. +/// Note: Algorithm only works for values between 0 and 99 inclusive. +fn bcd(value: u8) u8 { + return ((value / 10) << 4) + (value % 10); } diff --git a/src/main.zig b/src/main.zig index 0397e41..463f388 100644 --- a/src/main.zig +++ b/src/main.zig @@ -93,7 +93,7 @@ pub fn main() void { gui.run(&cpu, &scheduler) catch |e| exitln("failed to run gui thread: {}", .{e}); } -pub fn handleArguments(allocator: Allocator, data_path: []const u8, result: *const clap.Result(clap.Help, ¶ms, clap.parsers.default)) !FilePaths { +fn handleArguments(allocator: Allocator, data_path: []const u8, result: *const clap.Result(clap.Help, ¶ms, clap.parsers.default)) !FilePaths { const rom_path = romPath(result); log.info("ROM path: {s}", .{rom_path});