Correct writer to use with std.zig.stringEscape

Which writer can I use as the second argument to std.zig.stringEscape? The code

var buf = std.ArrayListUnmanaged(u8){};
var w = buf.writer(alloc);
try std.zig.stringEscape(bytes, &w);

results in the error

 error: expected type '*Io.Writer', found '*Io.GenericWriter(array_list.Aligned(u8,null).WriterContext,error{OutOfMemory},(function 'appendWrite'))'
    try std.zig.stringEscape(bytes, &w);
                                    ^~

There have been some changes to the Writer interface in 0.15. GenericWriter is deprecated, the new interface is the non-generic std.Io.Writer which is what you need here. ArrayList.writer() (which uses GenericWriter) is also effectively deprecated (has already been removed on master branch). The suggested alternative is std.Io.Writer.Allocating which writes to an ArrayList:

var w: std.Io.Writer.Allocating = .init(alloc);
errdefer w.deinit();
try std.zig.stringEscape(bytes, &w.writer);

std.Io.Writer.Allocating also provides written(), fromArrayList() and toArrayList() which might help.

(also ArrayListUnmanaged is now a deprecated alias for ArrayList since the unmanaged variant has become the default)

2 Likes

Thank you so much. The code worked!

1 Like