From 836481ff18f1f53f58af79e98cdfeb14f1b8b0a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Tue, 16 Apr 2024 21:27:01 +0900 Subject: [PATCH] Add meta.zig --- src/image.zig | 2 +- src/meta.zig | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 src/meta.zig diff --git a/src/image.zig b/src/image.zig index 9742826..bbc1e6f 100644 --- a/src/image.zig +++ b/src/image.zig @@ -1,7 +1,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const Rgba = @import("color.zig").Rgba; -const as = @import("utils.zig").as; +const as = @import("meta.zig").as; /// A simple image struct that encapsulates the size and the data. pub fn Image(comptime T: type) type { diff --git a/src/meta.zig b/src/meta.zig new file mode 100644 index 0000000..ac0ae23 --- /dev/null +++ b/src/meta.zig @@ -0,0 +1,27 @@ +/// Converts between numeric types: .Enum, .Int and .Float. +pub inline fn as(comptime T: type, from: anytype) T { + switch (@typeInfo(@TypeOf(from))) { + .Enum => { + switch (@typeInfo(T)) { + .Int => return @intFromEnum(from), + else => @compileError(@typeName(@TypeOf(from)) ++ " can't be converted to " ++ @typeName(T)), + } + }, + .Int => { + switch (@typeInfo(T)) { + .Enum => return @enumFromInt(from), + .Int => return @intCast(from), + .Float => return @floatFromInt(from), + else => @compileError(@typeName(@TypeOf(from)) ++ " can't be converted to " ++ @typeName(T)), + } + }, + .Float => { + switch (@typeInfo(T)) { + .Float => return @floatCast(from), + .Int => return @intFromFloat(from), + else => @compileError(@typeName(@TypeOf(from)) ++ " can't be converted to " ++ @typeName(T)), + } + }, + else => @compileError(@typeName(@TypeOf(from) ++ " is not supported.")), + } +}