Skip to content

Double-check C bitfield translation #16

@ianprime0509

Description

@ianprime0509

I'm no longer sure I trust the prior understanding of bitfields that caused me to write this:

fn translateLinearFields(allocator: Allocator, fields: []const gir.Field, ctx: TranslationContext, out: anytype) !void {
// The handling of bit fields aligns with what a "normal" C compiler should
// do: pack adjacent bit fields next to each other, padding out to the next
// byte after the last bit field in a sequence. This is not guaranteed by
// the standard, but GObject stuff seems to assume it.
var in_bit_fields = false;
var bit_fields_bits: u16 = 0;
var n_bit_fields: usize = 0;
for (fields) |field| {
if (field.bits) |bits| {
if (!in_bit_fields) {
try out.print("bitfields$L: packed struct ${\n", .{n_bit_fields});
in_bit_fields = true;
}
try out.print("$I: u$L,\n", .{ field.name, bits });
bit_fields_bits += bits;
} else {
if (in_bit_fields) {
const total_bits = @max(math.ceilPowerOfTwoPromote(u16, bit_fields_bits), 8);
const padding_bits = total_bits - bit_fields_bits;
if (padding_bits > 0) {
try out.print("padding: u$L,\n", .{padding_bits});
}
try out.print("$},\n", .{});
in_bit_fields = false;
bit_fields_bits = 0;
n_bit_fields += 1;
}
try out.print("$I: ", .{field.name});
try translateFieldType(allocator, field.type, ctx, out);
try out.print(",\n", .{});
}
}
// Handle trailing bit fields
if (in_bit_fields) {
const total_bits = @max(math.ceilPowerOfTwoPromote(u16, bit_fields_bits), 8);
const padding_bits = total_bits - bit_fields_bits;
if (padding_bits > 0) {
try out.print("padding: u$L,\n", .{padding_bits});
}
try out.print("$},\n", .{});
}
}
It seems to be more complicated than I previously understood.

Related: ziglang/zig#1499 There is a project in the comments of that issue that might help solidify the translation in this library.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions