From 4e0916d397d67a7dfe1ebac635825591d9858f06 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Wed, 13 Dec 2023 18:54:41 -0800 Subject: [PATCH] config: C API read allows any packed struct that fits in c int --- src/config/c_get.zig | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/config/c_get.zig b/src/config/c_get.zig index 0305100a6..2a1ca95ab 100644 --- a/src/config/c_get.zig +++ b/src/config/c_get.zig @@ -39,17 +39,24 @@ pub fn get(config: *const Config, k: Key, ptr_raw: *anyopaque) bool { ptr.* = @floatCast(value); }, - Color => { - const ptr: *c_uint = @ptrCast(@alignCast(ptr_raw)); - ptr.* = @as(c_uint, @as(u24, @bitCast(value))); - }, - else => |T| switch (@typeInfo(T)) { .Enum => { const ptr: *[*:0]const u8 = @ptrCast(@alignCast(ptr_raw)); ptr.* = @tagName(value); }, + .Struct => |info| { + // Packed structs that are less than or equal to the + // size of a C int can be passed directly as their + // bit representation. + if (info.layout != .Packed) return false; + const Backing = info.backing_integer orelse return false; + if (@bitSizeOf(Backing) > @bitSizeOf(c_uint)) return false; + + const ptr: *c_uint = @ptrCast(@alignCast(ptr_raw)); + ptr.* = @intCast(@as(Backing, @bitCast(value))); + }, + else => return false, }, }