Skip to content

Commit

Permalink
Add meta.zig
Browse files Browse the repository at this point in the history
  • Loading branch information
arrufat committed Apr 16, 2024
1 parent 8e054eb commit 836481f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/image.zig
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down
27 changes: 27 additions & 0 deletions src/meta.zig
Original file line number Diff line number Diff line change
@@ -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.")),
}
}

0 comments on commit 836481f

Please sign in to comment.