GenericWriter
Deprecated in favor of Writer.
Fields of this type
Fields
- context:Context
Type definitions in this namespace
Types
Functions in this namespace
Functions
- adaptToNewApi
- Helper for bridging to the new `Writer` API while upgrading.
= WriteError
Values
- Error
- = WriteError
Source
Implementation
pub fn GenericWriter(
comptime Context: type,
comptime WriteError: type,
comptime writeFn: fn (context: Context, bytes: []const u8) WriteError!usize,
) type {
return struct {
context: Context,
const Self = @This();
pub const Error = WriteError;
pub inline fn write(self: Self, bytes: []const u8) Error!usize {
return writeFn(self.context, bytes);
}
pub inline fn writeAll(self: Self, bytes: []const u8) Error!void {
return @errorCast(self.any().writeAll(bytes));
}
pub inline fn print(self: Self, comptime format: []const u8, args: anytype) Error!void {
return @errorCast(self.any().print(format, args));
}
pub inline fn writeByte(self: Self, byte: u8) Error!void {
return @errorCast(self.any().writeByte(byte));
}
pub inline fn writeByteNTimes(self: Self, byte: u8, n: usize) Error!void {
return @errorCast(self.any().writeByteNTimes(byte, n));
}
pub inline fn writeBytesNTimes(self: Self, bytes: []const u8, n: usize) Error!void {
return @errorCast(self.any().writeBytesNTimes(bytes, n));
}
pub inline fn writeInt(self: Self, comptime T: type, value: T, endian: std.builtin.Endian) Error!void {
return @errorCast(self.any().writeInt(T, value, endian));
}
pub inline fn writeStruct(self: Self, value: anytype) Error!void {
return @errorCast(self.any().writeStruct(value));
}
pub inline fn writeStructEndian(self: Self, value: anytype, endian: std.builtin.Endian) Error!void {
return @errorCast(self.any().writeStructEndian(value, endian));
}
pub inline fn any(self: *const Self) AnyWriter {
return .{
.context = @ptrCast(&self.context),
.writeFn = typeErasedWriteFn,
};
}
fn typeErasedWriteFn(context: *const anyopaque, bytes: []const u8) anyerror!usize {
const ptr: *const Context = @ptrCast(@alignCast(context));
return writeFn(ptr.*, bytes);
}
/// Helper for bridging to the new `Writer` API while upgrading.
pub fn adaptToNewApi(self: *const Self, buffer: []u8) Adapter {
return .{
.derp_writer = self.*,
.new_interface = .{
.buffer = buffer,
.vtable = &.{ .drain = Adapter.drain },
},
};
}
pub const Adapter = struct {
derp_writer: Self,
new_interface: Writer,
err: ?Error = null,
fn drain(w: *std.io.Writer, data: []const []const u8, splat: usize) std.io.Writer.Error!usize {
_ = splat;
const a: *@This() = @alignCast(@fieldParentPtr("new_interface", w));
const buffered = w.buffered();
if (buffered.len != 0) return w.consume(a.derp_writer.write(buffered) catch |err| {
a.err = err;
return error.WriteFailed;
});
return a.derp_writer.write(data[0]) catch |err| {
a.err = err;
return error.WriteFailed;
};
}
};
};
}