#Sorting struct fields at comptime

1 messages · Page 1 of 1 (latest)

proud parrot
#
const std = @import("std");

pub fn main() !void {
    const T = @TypeOf(.{.third = 3, .first = 1, .second = 2});
    const s = @typeInfo(T).@"struct";

    var field_names: [s.fields.len][]const u8 = undefined;
    inline for (s.fields, 0..) |f, i| {
        field_names[i] = f.name;
    }
    comptime sort(&field_names);
    std.debug.print("{any}\n", .{field_names});
}

fn sort(values: [][]const u8) void {
    std.mem.sort([]const u8, values, {}, struct {
        fn sort(_: void, lhs: []const u8, rhs: []const u8) bool {
             return std.mem.order(u8, lhs, rhs) == .lt;
        }
    }.sort);
}

Doesn't compile:

error: unable to evaluate comptime expression
    comptime sort(&field_names);

If I take out the comptime from the call to sort, it works. But I need the fields sorted at comptime.

wind wasp
#

maybe do it like

const field_names = comptime blk: {
  var field_names: [s.fields.len][]const u8 = undefined;
  inline for (s.fields, 0..) |f, i| {
    field_names[i] = f.name;
  }
  sort(&field_names);
  break :blk field_names;
};
zealous remnant
zealous remnant
proud parrot
#

Thanks, should have been able to figure this out..appreciate it.

wind wasp
zealous remnant
#

oh, yeah. should have read the sample more carefully

minor coral
#

the compiler is free to re-order them and insert padding at random if it wants

proud parrot
#

Which is a good reason to sort by name 😉

minor coral
#

the compiler is free to mangle the order anyway, the order does not matter for auto layout structs

#

it makes more sense to group fields logically by function/data contained

#

eg. if you have multiple fields relating to a timer, then multiple relating to a position vector
it does not make sense to sort that by name

#

and for extern/packed structs
the order should be done based on what reduces the space taken

#

alignment should be a consideration aswell

#

especially for packed structs

#

eg. its smarter to have a packed struct with layout u8, u8, u8, u2, u1, than it is to have a packed struct with layout u8, u2, u8, u1, u8