From 0be3a8ae25e8d032f4af59e675dce66452ba9211 Mon Sep 17 00:00:00 2001 From: Inga Date: Sat, 2 Dec 2023 18:29:49 +0000 Subject: [PATCH] extract setMaxValue --- day02-hard/src/main.zig | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/day02-hard/src/main.zig b/day02-hard/src/main.zig index 7e4eca3..a0bfa56 100644 --- a/day02-hard/src/main.zig +++ b/day02-hard/src/main.zig @@ -1,5 +1,14 @@ const std = @import("std"); +fn setMaxValue(field: anytype, new_value: anytype) void { + comptime { + if (!std.meta.trait.isPtrTo(@typeInfo(@TypeOf(new_value)))(@TypeOf(field))) { + @compileError("Expects field to be pointer type to new_value."); + } + } + field.* = @max(field.*, new_value); +} + const Cubes = struct { red: u32 = 0, green: u32 = 0, @@ -10,21 +19,15 @@ const Cubes = struct { } fn setRed(self: *Cubes, value: u32) void { - if (self.red < value) { - self.red = value; - } + setMaxValue(&self.red, value); } fn setGreen(self: *Cubes, value: u32) void { - if (self.green < value) { - self.green = value; - } + setMaxValue(&self.green, value); } fn setBlue(self: *Cubes, value: u32) void { - if (self.blue < value) { - self.blue = value; - } + setMaxValue(&self.blue, value); } };