#How to generate format args in recursive function?

1 messages · Page 1 of 1 (latest)

grizzled trench
#

I have this function:

fn diffAny(comptime T: type, comptime Path: []const u8, pathArgs: anytype, a: T, b: T, depth: u8, differences:*Diffs, gpa: std.mem.Allocator) void {
    switch (@typeInfo(T)) {
       // other cases deleted, to have a short message
        .array => |ar| {
            if (a.len != b.len) {
                var newD = differences.differences.addOne(gpa) catch unreachable;
                newD.path = std.fmt.allocPrint(gpa, Path ++ ".len", pathArgs) catch unreachable;
                newD.depth = depth;
                newD.diff = std.fmt.allocPrint(gpa, "{} != {}", .{ a.len, b.len }) catch unreachable;
            }

            // TODO update pathArgs with index
            for (a, b) |aI, bI|diffAny(ar.child, Path ++ "[]", pathArgs, aI, bI, depth + 1, differences, gpa);
        },
        else => @compileError("Unreachable. " ++ @typeName(T) ++ " is unexpected"),
    }
}

And I would like for Path ++ "[]" to be Path ++ "[{}]", and somehow add index to the pathArgs.
I believe such thing is possible, because I can generate types at compile time, but the index will be a runtime value, but that is only assignment, but I can not even figure out the correct question, for search engines to understand.

crystal whale
#

you could, but it will be far easier to just write the logic to print things individually instead of mashing them into a single print call.

grizzled trench
#

I do not want to do something like 6000*8000*12000 allocations, and then somehow free them, because none of them will be in the final output...

#

🤔 actually I can not even imagine freeing these allocation

crystal whale
#

you need to share more code, because I have no idea what you are talking about

grizzled trench
#

I call it for a huge hierarchical structure, and in most cases differences:*Diffs should not be touched, but for the few paths where it will find a difference I would like to have the path contain actual indices (or map keys)

crystal whale
#

hm, perhaps i misunderstood what you were trying to do.
you can pathArgs ++ .{i} concatinate tuples at comptime

grizzled trench
#

😮 oh that compiles 🤩
Wasn't ++ for arrays, not structs?

crystal whale
#

tuples are weird

grizzled trench
#

😮 🤩 it works

#

debug: .game_data.data.Card.entities.a[101].u0.tokens.tokens[]: .Neutral != .White (depth: 10)

#

Thank you very much