zig icon indicating copy to clipboard operation
zig copied to clipboard

`diff` algorithm in the std

Open Arnau478 opened this issue 1 year ago • 0 comments

This proposal is about implementing a diff algorithm (probably Myers') in the standard library.

Considerations

  • It would probably be under std.mem, being something like std.mem.diff
  • The prototype would be fn diff(allocator: Allocator, comptime T: type, a: []const T, b: []const T) []DiffChange(T)
  • It could prove to be really useful in parts of the std itself (e.g. with testing tools like expectEqualSlices)

[]DiffChange(T)

Probably the most critical thing is the return type. So, if someone knows a better way of doing this, please comment it. What I thought of was to return a slice of DiffChange(T). DiffChange(T) would be defined to be something like:

pub fn DiffChange(comptime T: type) type {
    return union(enum){
        add: []const T,
        del: []const T,
    };
}

Using a tagged union (instead of a data-tag approach) makes it suitable for switch statements. Note that add would be a sub-slice of b and del would be a sub-slice of a.

I think I will start implementing this on a fork, but I obviously won't open a PR until this issue is accepted.

Arnau478 avatar Dec 23 '23 21:12 Arnau478