// SPDX-FileCopyrightText: © 2022 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Netascii, the text representation TFTP borrows from Telnet's NVT ASCII //! (RFC 854): lines end in CR LF, and a CR that is data rather than part of a //! line ending is sent as CR NUL. A CR followed by anything else is not //! netascii at all. //! //! Decoding turns netascii into local text, whose line ending depends on the //! operating system: CR LF on Windows, LF everywhere else. Encoding goes the //! other way. Each codec is a function over a whole stream, and the stream //! adapters `Decoder`, `DecodeReader` and `EncodeReader` do the same work a //! buffer at a time. The public names choose the host's convention; the //! underscored ones take it as a parameter, which is how the tests cover every //! convention on any host. const std = @import("std"); const builtin = @import("builtin"); const testing = std.testing; const Allocator = std.mem.Allocator; /// The errors `decode` can return. `error.UnescapedCR` means the input held a /// CR followed by neither LF nor NUL, or ended in a CR. pub const DecodeErrors = error{ UnescapedCR, } || std.Io.Reader.Error || std.Io.Writer.Error; /// The errors `decodeZ` can return. `error.MissingSentinel` means the input /// ended before the terminating NUL. pub const DecodeSentinelErrors = error{ UnescapedCR, MissingSentinel, } || std.Io.Reader.Error || std.Io.Writer.Error; /// The errors `encode` and `encodeZ` can return. Encoding cannot fail on its /// input, only in reading or writing it. pub const EncodeErrors = error{} || std.Io.Reader.Error || std.Io.Writer.Error; /// A local line ending convention. pub const LineSeparator = enum { /// A lone CR, as in the classic Mac OS. cr, /// A lone LF, as on Unix. lf, /// CR LF, as on Windows. crlf, }; const log = std.log.scoped(.netascii); /// A `std.Io.Writer` that decodes the netascii written to it and writes local /// text to another `std.Io.Writer`, using the line ending convention of the /// host operating system. /// /// This is the write side counterpart of `DecodeReader`. pub const Decoder = switch (builtin.os.tag) { .windows => _Decoder(.crlf), else => _Decoder(.lf), // macOS before OS X would be .cr, but that is not supported by Zig }; /// `Decoder` for the line ending convention `linesep`. /// /// Decoded bytes reach the child as the buffer fills, or when the decoder is /// flushed. A CR at the end of the buffer is held back until the byte after it /// arrives, which is why the buffer must hold at least two bytes. Input that is /// not netascii fails the write with `error.WriteFailed`, as does a CR still /// held back when the decoder is flushed, since there is then nothing left to /// escape it. Either records the reason in `err`, which tells it apart from a /// failure of the child. pub fn _Decoder(comptime linesep: LineSeparator) type { return struct { const Self = @This(); /// The writer netascii is written to. interface: std.Io.Writer, /// Where the decoded text goes. child: *std.Io.Writer, /// Diagnostics for `error.WriteFailed` originating from this decoder /// rather than from `child`. Once set, the interface fails every /// subsequent write. err: ?WriteError, /// The reasons the decoder itself can fail a write, recorded in `err`. pub const WriteError = error{ /// The input held a CR followed by neither LF nor NUL, or ended /// in a CR. UnescapedCR, }; /// A decoder writing to `child`, buffering in `buffer`, which must /// hold at least two bytes. pub fn init(child: *std.Io.Writer, buffer: []u8) Self { std.debug.assert(buffer.len >= 2); return .{ .interface = .{ .buffer = buffer, .vtable = &.{ .drain = VTable.drain, .flush = VTable.flush, }, }, .child = child, .err = null, }; } /// The `std.Io.Writer` implementation, which forwards to the methods /// below. const VTable = struct { /// Buffers every chunk of `data`, the last one `splat` times, /// decoding each time the buffer fills. fn drain(interface: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { const self: *Self = @alignCast(@fieldParentPtr("interface", interface)); var count: usize = 0; for (data[0 .. data.len - 1]) |chunk| { try self.write(chunk, &count); } for (0..splat) |_| { try self.write(data[data.len - 1], &count); } return count; } /// Decodes all that is buffered and flushes the child. fn flush(interface: *std.Io.Writer) std.Io.Writer.Error!void { const self: *Self = @alignCast(@fieldParentPtr("interface", interface)); try self.flush(); } }; /// Copies `chunk` into the buffer, decoding whenever it fills, and /// adds the number of bytes accepted to `count`. fn write(self: *Self, chunk: []const u8, count: *usize) std.Io.Writer.Error!void { var index: usize = 0; while (index < chunk.len) { const size = @min( self.interface.buffer.len - self.interface.end, chunk.len - index, ); @memcpy( self.interface.buffer[self.interface.end .. self.interface.end + size], chunk[index .. index + size], ); self.interface.end += size; index += size; count.* += size; if (self.interface.buffer.len == self.interface.end) { try self._write(false); } } } /// Decodes everything buffered, allowing no CR to be held back, and /// flushes the child. fn flush(self: *Self) std.Io.Writer.Error!void { try self._write(true); try self.child.flush(); } /// Decodes the buffer into the child and empties it, except that a CR /// in its last byte is kept for the next call unless `finish` says /// there will be no next call. fn _write(self: *Self, finish: bool) std.Io.Writer.Error!void { const linesep_bytes = switch (linesep) { .lf => [_]u8{std.ascii.control_code.lf}, .cr => [_]u8{std.ascii.control_code.cr}, .crlf => [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.lf }, }; const replacements = .{ .{ [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.nul }, [_]u8{std.ascii.control_code.cr}, }, .{ [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.lf }, linesep_bytes, }, // A bare LF is a line terminator in NVT ASCII, so it decodes // to the local convention just as CR LF does. .{ [_]u8{std.ascii.control_code.lf}, linesep_bytes, }, }; if (self.err != null) return error.WriteFailed; // If there's nothing in the buffer, do nothing. if (self.interface.end == 0) return; var index: usize = 0; outer: while (true) { inline for (replacements) |item| replacement: { const needle, const replacement = item; // If there's not enough data left in the buffer, skip this needle. if (index + needle.len > self.interface.end) break :replacement; const haystack = self.interface.buffer[index .. index + needle.len]; if (std.mem.eql(u8, haystack, &needle)) { index += needle.len; try self.child.writeAll(&replacement); continue :outer; } } if (index >= self.interface.end) { self.interface.end = 0; return; } switch (self.interface.buffer[index]) { std.ascii.control_code.cr => { // The bare CR occurred before the end of the buffer. // The subtraction is safe because we guaranteed that // `self.interface.end` is not zero above. if (index < self.interface.end - 1) { self.err = error.UnescapedCR; return error.WriteFailed; } // The bare CR occurred at end of the buffer and there // will be no more data. The subtraction is safe because // we guaranteed that `self.interface.end` is not zero // above. if (index == self.interface.end - 1 and finish) { self.err = error.UnescapedCR; return error.WriteFailed; } // The bare CR occurred at the end of the buffer and // there will be more data. self.interface.buffer[0] = std.ascii.control_code.cr; self.interface.end = 1; return; }, else => |byte| { index += 1; try self.child.writeByte(byte); }, } } } }; } test "decoder netascii cr 4" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); var decode_buf: [2]u8 = undefined; var decoder: _Decoder(.cr) = .init(&buf.writer, &decode_buf); try decoder.interface.writeAll("foo\x0d\x00\x0abar"); try decoder.interface.flush(); try testing.expectEqualStrings("foo\x0d\x0dbar", buf.written()); } test "decoder netascii cr 5" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); var decode_buf: [2]u8 = undefined; var decoder: _Decoder(.cr) = .init(&buf.writer, &decode_buf); try testing.expectError(error.WriteFailed, decoder.interface.writeAll("foo\x0d\x0a\x0dbar")); try testing.expectEqual(error.UnescapedCR, decoder.err.?); // The failure is sticky. try testing.expectError(error.WriteFailed, decoder.interface.writeAll("baz")); } test "decoder trailing cr" { var buf: std.Io.Writer.Allocating = .init(testing.allocator); defer buf.deinit(); var decode_buf: [8]u8 = undefined; var decoder: _Decoder(.lf) = .init(&buf.writer, &decode_buf); try decoder.interface.writeAll("foo\x0d"); try testing.expectError(error.WriteFailed, decoder.interface.flush()); try testing.expectEqual(error.UnescapedCR, decoder.err.?); } test "decoder child failure" { var out: [2]u8 = undefined; var child: std.Io.Writer = .fixed(&out); var decode_buf: [8]u8 = undefined; var decoder: _Decoder(.lf) = .init(&child, &decode_buf); try decoder.interface.writeAll("foo"); try testing.expectError(error.WriteFailed, decoder.interface.flush()); try testing.expectEqual(null, decoder.err); } test "decoder netascii crlf 2" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); var decode_buf: [2]u8 = undefined; var decoder: _Decoder(.crlf) = .init(&buf.writer, &decode_buf); try decoder.interface.writeAll("\x0d\x0a"); try decoder.interface.flush(); try testing.expectEqualStrings("\x0d\x0a", buf.written()); } /// A `std.Io.Reader` that decodes netascii read from another `std.Io.Reader`, /// translating line endings to the convention of the host operating system. /// /// This is the read side counterpart of `Decoder`. pub const DecodeReader = switch (builtin.os.tag) { .windows => _DecodeReader(.crlf), else => _DecodeReader(.lf), // macOS before OS X would be .cr, but that is not supported by Zig }; /// `DecodeReader` for the line ending convention `linesep`. /// /// The netascii escapes that have to be recognized are two bytes long, so the /// decoder needs to look ahead two bytes in `child`. That look ahead is done /// with `std.Io.Reader.peek`, which means `child` must have been initialized /// with a buffer capacity of at least two bytes, unless fewer than two bytes /// remain in the stream. /// /// The `buffer` passed to `init` has no minimum size; the decoder writes into /// the destination it is handed rather than into its own buffer. An empty /// buffer is fine for `readSliceAll` style usage, but the `std.Io.Reader` API /// asserts a capacity of at least `n` for `peek(n)` and friends, so give it a /// buffer if callers will peek. pub fn _DecodeReader(comptime linesep: LineSeparator) type { return struct { const Self = @This(); const cr = std.ascii.control_code.cr; const lf = std.ascii.control_code.lf; const nul = std.ascii.control_code.nul; /// The local line terminator, which is what both CR LF and a bare LF /// decode to. A bare LF is a line terminator in NVT ASCII, so it /// follows the local convention rather than passing through. const linesep_bytes = switch (linesep) { .cr => [_]u8{cr}, .lf => [_]u8{lf}, .crlf => [_]u8{ cr, lf }, }; /// Bytes that cannot be copied through verbatim. Under `.lf` a bare LF /// decodes to itself, so only a CR interrupts the copy. const specials: []const u8 = if (linesep == .lf) &.{cr} else &.{ cr, lf }; /// The reader decoded text is read from. interface: std.Io.Reader, /// Where the netascii comes from. child: *std.Io.Reader, /// Diagnostics for `error.ReadFailed` originating from this decoder /// rather than from `child`. Once set, the interface fails every /// subsequent read. err: ?ReadError, /// Set when a line terminator decoded to two bytes but only one byte of /// room was left in the destination. The held over byte is always an /// LF, because CR LF is the only two byte local line terminator. pending_lf: bool, /// The reasons the decoder itself can fail a read, recorded in `err`. pub const ReadError = error{ /// The input held a CR followed by neither LF nor NUL, or ended /// in a CR. UnescapedCR, }; /// A decoder reading from `child`, buffering in `buffer`. pub fn init(child: *std.Io.Reader, buffer: []u8) Self { return .{ .interface = .{ .buffer = buffer, .seek = 0, .end = 0, .vtable = &.{ .stream = VTable.stream, .discard = VTable.discard, }, }, .child = child, .err = null, .pending_lf = false, }; } /// The `std.Io.Reader` implementation, which forwards to `stream`. const VTable = struct { /// Decodes into `w`, at most `limit` bytes. fn stream(interface: *std.Io.Reader, w: *std.Io.Writer, limit: std.Io.Limit) std.Io.Reader.StreamError!usize { const self: *Self = @alignCast(@fieldParentPtr("interface", interface)); return self.stream(w, limit); } /// Decodes at most `limit` bytes and throws them away. fn discard(interface: *std.Io.Reader, limit: std.Io.Limit) std.Io.Reader.Error!usize { const self: *Self = @alignCast(@fieldParentPtr("interface", interface)); // Decoding never expands the data, so a small scratch buffer is // enough; returning fewer bytes than `limit` is a short read, // which the interface allows. var scratch: [64]u8 = undefined; var discarding: std.Io.Writer.Discarding = .init(&scratch); return self.stream(&discarding.writer, limit) catch |err| switch (err) { error.WriteFailed => unreachable, else => |e| return e, }; } }; /// Copies as much of `bytes` into `dest` as fits, holding the rest over /// for the next read. Asserts nothing is already held over, which is /// guaranteed because holding anything over fills `dest`. fn emit(self: *Self, dest: []u8, count: *usize, bytes: []const u8) void { std.debug.assert(!self.pending_lf); const size = @min(bytes.len, dest.len - count.*); @memcpy(dest[count.*..][0..size], bytes[0..size]); count.* += size; if (size < bytes.len) { std.debug.assert(bytes.len - size == 1 and bytes[size] == lf); self.pending_lf = true; } } /// Decodes from `child` into the writable space of `w`, at most /// `limit` bytes, and returns how many were written. A failure after /// some bytes have been decoded ends the read early, and is reported by /// the next one. fn stream(self: *Self, w: *std.Io.Writer, limit: std.Io.Limit) std.Io.Reader.StreamError!usize { if (self.err != null) return error.ReadFailed; const dest = limit.slice(try w.writableSliceGreedy(1)); if (dest.len == 0) return 0; var count: usize = 0; if (self.pending_lf) { dest[0] = lf; count = 1; self.pending_lf = false; } outer: while (count < dest.len) { const src = self.child.peekGreedy(2) catch |err| switch (err) { error.ReadFailed => { if (count > 0) break :outer; return error.ReadFailed; }, error.EndOfStream => { // Fewer than two bytes remain in the stream. const byte = self.child.peekByte() catch |e| switch (e) { error.EndOfStream => break :outer, error.ReadFailed => { if (count > 0) break :outer; return error.ReadFailed; }, }; // A CR at the very end of the stream cannot be escaped. if (byte == cr) { if (count > 0) break :outer; self.err = error.UnescapedCR; return error.ReadFailed; } self.child.toss(1); if (byte == lf) { self.emit(dest, &count, &linesep_bytes); } else { dest[count] = byte; count += 1; } continue :outer; }, }; // Copy everything up to the next byte needing translation. const special_index = std.mem.indexOfAny(u8, src, specials) orelse src.len; if (special_index > 0) { const size = @min(special_index, dest.len - count); @memcpy(dest[count..][0..size], src[0..size]); count += size; self.child.toss(size); continue :outer; } // `src` starts with a CR, or with a bare LF that translates, // and holds at least two bytes. if (src[0] == lf) { self.child.toss(1); self.emit(dest, &count, &linesep_bytes); continue :outer; } switch (src[1]) { nul => { self.child.toss(2); self.emit(dest, &count, &.{cr}); }, lf => { self.child.toss(2); self.emit(dest, &count, &linesep_bytes); }, else => { if (count > 0) break :outer; self.err = error.UnescapedCR; return error.ReadFailed; }, } } if (count == 0) return error.EndOfStream; w.advance(count); return count; } }; } /// Decodes `input` with `_DecodeReader`, asserting that the result is /// `expected` and that all of `input` was consumed. fn testDecodeReader( comptime linesep: LineSeparator, comptime buffer_len: usize, input: []const u8, expected: []const u8, ) !void { var child: std.Io.Reader = .fixed(input); var decode_buf: [buffer_len]u8 = undefined; var decoder: _DecodeReader(linesep) = .init(&child, &decode_buf); var buf: std.Io.Writer.Allocating = .init(testing.allocator); defer buf.deinit(); _ = try decoder.interface.streamRemaining(&buf.writer); try testing.expectEqualStrings(expected, buf.written()); try testing.expectEqual(0, child.bufferedLen()); } /// Decodes `input` with `_DecodeReader`, asserting that it fails with /// `error.UnescapedCR` and goes on failing. fn testDecodeReaderError(comptime linesep: LineSeparator, input: []const u8) !void { var child: std.Io.Reader = .fixed(input); var decode_buf: [4]u8 = undefined; var decoder: _DecodeReader(linesep) = .init(&child, &decode_buf); var buf: std.Io.Writer.Allocating = .init(testing.allocator); defer buf.deinit(); try testing.expectError(error.ReadFailed, decoder.interface.streamRemaining(&buf.writer)); try testing.expectEqual(error.UnescapedCR, decoder.err.?); // The failure is sticky. try testing.expectError(error.ReadFailed, decoder.interface.streamRemaining(&buf.writer)); } test "decode reader cr 1" { try testDecodeReader(.cr, 8, "\x0d\x00", "\x0d"); } test "decode reader cr 2" { try testDecodeReader(.cr, 8, "\x0d\x0a", "\x0d"); } test "decode reader cr 3" { try testDecodeReader(.cr, 8, "foo\x0d\x0a\x0abar", "foo\x0d\x0dbar"); } test "decode reader cr 4" { try testDecodeReader(.cr, 8, "foo\x0d\x00\x0abar", "foo\x0d\x0dbar"); } test "decode reader cr 5" { try testDecodeReaderError(.cr, "foo\x0d\x0a\x0dbar"); } test "decode reader lf 1" { try testDecodeReader(.lf, 8, "\x0d\x00", "\x0d"); } test "decode reader lf 2" { try testDecodeReader(.lf, 8, "\x0d\x0a", "\x0a"); } test "decode reader lf 3" { try testDecodeReader(.lf, 8, "foo\x0d\x0a\x0abar", "foo\x0a\x0abar"); } test "decode reader lf 4" { try testDecodeReader(.lf, 8, "foo\x0d\x00\x0abar", "foo\x0d\x0abar"); } test "decode reader lf 5" { try testDecodeReaderError(.lf, "foo\x0d\x0a\x0dbar"); } test "decode reader crlf 1" { try testDecodeReader(.crlf, 8, "\x0d\x00", "\x0d"); } test "decode reader crlf 2" { try testDecodeReader(.crlf, 8, "\x0d\x0a", "\x0d\x0a"); } test "decode reader crlf 3" { try testDecodeReader(.crlf, 8, "foo\x0d\x0a\x0abar", "foo\x0d\x0a\x0d\x0abar"); } test "decode reader crlf 4" { try testDecodeReader(.crlf, 8, "foo\x0d\x00\x0abar", "foo\x0d\x0d\x0abar"); } test "decode reader crlf 5" { try testDecodeReaderError(.crlf, "foo\x0d\x0a\x0dbar"); } test "decode reader trailing cr" { try testDecodeReaderError(.lf, "foo\x0d"); } test "decode reader empty" { try testDecodeReader(.lf, 8, "", ""); } test "decode reader zero length buffer" { var child: std.Io.Reader = .fixed("foo\x0d\x0a\x0d\x00bar"); var decoder: _DecodeReader(.lf) = .init(&child, &.{}); var out: [10]u8 = undefined; const n = try decoder.interface.readSliceShort(&out); try testing.expectEqualStrings("foo\x0a\x0dbar", out[0..n]); } test "decode reader byte at a time" { // Forces the `.crlf` decoder to split a CR LF pair across two reads. var child: std.Io.Reader = .fixed("a\x0d\x0ab\x0d\x0a"); var decode_buf: [1]u8 = undefined; var decoder: _DecodeReader(.crlf) = .init(&child, &decode_buf); var buf: std.Io.Writer.Allocating = .init(testing.allocator); defer buf.deinit(); while (decoder.interface.streamExact(&buf.writer, 1)) {} else |err| { try testing.expectEqual(error.EndOfStream, err); } try testing.expectEqualStrings("a\x0d\x0ab\x0d\x0a", buf.written()); } test "decode reader discard" { var child: std.Io.Reader = .fixed("foo\x0d\x0abar\x0d\x00baz"); var decode_buf: [4]u8 = undefined; var decoder: _DecodeReader(.lf) = .init(&child, &decode_buf); try testing.expectEqual(11, try decoder.interface.discardRemaining()); } // test "decoder netascii cr 5" { // const alloc = std.testing.allocator; // var buf: std.Io.Writer.Allocating = .init(alloc); // defer buf.deinit(); // const output = &buf.writer; // var input: std.Io.Reader = .fixed("foo\x0d\x0a\x0dbar"); // try testing.expectError(error.UnescapedCR, _decode(&input, output, null, .cr)); // } /// Decodes all of `input` into `output`, using the line ending convention of /// the host operating system, and returns the number of netascii bytes read. pub fn decode(input: *std.Io.Reader, output: *std.Io.Writer) DecodeErrors!usize { switch (builtin.os.tag) { .windows => return _decode(input, output, null, .crlf) catch |err| { switch (err) { error.MissingSentinel => unreachable, else => |e| return e, } }, else => return _decode(input, output, null, .lf) catch |err| { switch (err) { error.MissingSentinel => unreachable, else => |e| return e, } }, // macOS before OS X would be .cr, but that is not supported by Zig } } /// Decodes a NUL terminated string from `input` into `output`, using the line /// ending convention of the host operating system, and returns the number of /// netascii bytes read, the NUL included. The NUL is consumed but not written. /// A NUL escaping a CR does not end the string. pub fn decodeZ(input: *std.Io.Reader, output: *std.Io.Writer) DecodeSentinelErrors!usize { switch (builtin.os.tag) { .windows => return try _decode(input, output, std.ascii.control_code.nul, .crlf), else => return try _decode(input, output, std.ascii.control_code.nul, .lf), // macOS before OS X would be .cr, but that is not supported by Zig } } /// `decode`, or `decodeZ` if `sentinel_` is given, for the line ending /// convention `linesep`. fn _decode(input: *std.Io.Reader, output: *std.Io.Writer, comptime sentinel_: ?u8, comptime linesep: LineSeparator) DecodeSentinelErrors!usize { const linesep_bytes = switch (linesep) { .lf => [_]u8{std.ascii.control_code.lf}, .cr => [_]u8{std.ascii.control_code.cr}, .crlf => [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.lf }, }; const replacements = .{ .{ [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.nul }, [_]u8{std.ascii.control_code.cr}, }, .{ [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.lf }, linesep_bytes, }, // A bare LF is a line terminator in NVT ASCII, so it decodes to the // local convention just as CR LF does. .{ [_]u8{std.ascii.control_code.lf}, linesep_bytes, }, }; var count: usize = 0; outer: while (true) { inline for (replacements) |item| replacement: { const needle, const replacement = item; const data = input.peek(needle.len) catch |err| switch (err) { error.EndOfStream => break :replacement, error.ReadFailed => |e| return e, }; if (std.mem.eql(u8, data, &needle)) { input.toss(needle.len); count += needle.len; try output.writeAll(&replacement); continue :outer; } } const byte = input.takeByte() catch |err| switch (err) { error.EndOfStream => { if (sentinel_) |_| return error.MissingSentinel; return count; }, error.ReadFailed => |e| return e, }; count += 1; switch (byte) { std.ascii.control_code.cr => { // std.log.warn("unescaped cr at {d}", .{count}); return error.UnescapedCR; }, else => { if (sentinel_) |sentinel| if (byte == sentinel) return count; try output.writeByte(byte); }, } } return count; } /// Encodes all of `input` into `writer` as netascii, taking its line endings /// to be those of the host operating system. pub fn encode(input: *std.Io.Reader, writer: *std.Io.Writer) EncodeErrors!void { switch (builtin.os.tag) { .windows => try _encode(input, writer, .crlf), else => try _encode(input, writer, .lf), // macOS before OS X would be .cr, but that is not supported by Zig } } /// `encode`, followed by a NUL, which is how TFTP terminates the strings in a /// request or error. pub fn encodeZ(input: *std.Io.Reader, writer: *std.Io.Writer) EncodeErrors!void { switch (builtin.os.tag) { .windows => try _encode(input, writer, .crlf), else => try _encode(input, writer, .lf), // macOS before OS X would be .cr, but that is not supported by Zig } try writer.writeByte(std.ascii.control_code.nul); } /// `encode` for the line ending convention `linesep`. fn _encode(input: *std.Io.Reader, output: *std.Io.Writer, comptime linesep: LineSeparator) EncodeErrors!void { const replacements = .{ .{ [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.lf }, switch (linesep) { .cr => [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.lf, std.ascii.control_code.cr, std.ascii.control_code.lf }, .lf => [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.nul, std.ascii.control_code.cr, std.ascii.control_code.lf }, .crlf => [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.lf }, }, }, .{ [_]u8{std.ascii.control_code.cr}, switch (linesep) { .cr => [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.lf }, .lf => [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.nul }, .crlf => [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.nul }, }, }, .{ [_]u8{std.ascii.control_code.lf}, // Netascii has no escape for a data LF, so every LF is encoded as // a line terminator regardless of the local convention. [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.lf }, }, }; outer: while (true) { inline for (replacements) |item| replacement: { const needle, const replacement = item; const data = input.peek(needle.len) catch |err| switch (err) { error.EndOfStream => break :replacement, error.ReadFailed => |e| return e, }; if (std.mem.eql(u8, data, &needle)) { input.toss(needle.len); try output.writeAll(&replacement); continue :outer; } } const byte = input.takeByte() catch |err| switch (err) { error.EndOfStream => return, error.ReadFailed => |e| return e, }; switch (byte) { std.ascii.control_code.cr => unreachable, else => try output.writeByte(byte), } } } /// A `std.Io.Reader` that encodes data read from another `std.Io.Reader` into /// netascii, translating the line endings of the host operating system. /// /// This is the read side counterpart of `encode`. pub const EncodeReader = switch (builtin.os.tag) { .windows => _EncodeReader(.crlf), else => _EncodeReader(.lf), // macOS before OS X would be .cr, but that is not supported by Zig }; /// `EncodeReader` for the line ending convention `linesep`. /// /// The longest sequence that has to be recognized is two bytes long, so the /// encoder needs to look ahead two bytes in `child`. That look ahead is done /// with `std.Io.Reader.peek`, which means `child` must have been initialized /// with a buffer capacity of at least two bytes, unless fewer than two bytes /// remain in the stream. /// /// The `buffer` passed to `init` has no minimum size; the encoder writes into /// the destination it is handed rather than into its own buffer. An empty /// buffer is fine for `readSliceAll` style usage, but the `std.Io.Reader` API /// asserts a capacity of at least `n` for `peek(n)` and friends, so give it a /// buffer if callers will peek. /// /// The encoding is the one `_encode` performs, so the two produce identical /// output for the same input. pub fn _EncodeReader(comptime linesep: LineSeparator) type { return struct { const Self = @This(); const cr = std.ascii.control_code.cr; const lf = std.ascii.control_code.lf; const nul = std.ascii.control_code.nul; /// A CR immediately followed by an LF. Under `.crlf` that pair is one /// line terminator; under the others it is a data CR followed by a line /// terminator, so both halves are encoded. const crlf_replacement = switch (linesep) { .cr => [_]u8{ cr, lf, cr, lf }, .lf => [_]u8{ cr, nul, cr, lf }, .crlf => [_]u8{ cr, lf }, }; /// A CR that is not followed by an LF. Under `.cr` it is a line /// terminator; under the others it is data and has to be escaped. const cr_replacement = switch (linesep) { .cr => [_]u8{ cr, lf }, .lf => [_]u8{ cr, nul }, .crlf => [_]u8{ cr, nul }, }; /// An LF that is not preceded by a CR. Netascii has no escape for a /// data LF, so every LF is encoded as a line terminator regardless of /// the local convention, which is what a bare LF means in NVT ASCII. const lf_replacement = [_]u8{ cr, lf }; /// Bytes that cannot be copied through verbatim. const specials: []const u8 = &.{ cr, lf }; /// The reader netascii is read from. interface: std.Io.Reader, /// Where the local text comes from. child: *std.Io.Reader, /// Encoding expands, so a replacement may not fit in the destination /// all at once. What did not fit is emitted by the next read. pending: [3]u8, /// How many bytes of `pending` are held over. pending_len: usize, /// An encoder reading from `child`, buffering in `buffer`. pub fn init(child: *std.Io.Reader, buffer: []u8) Self { return .{ .interface = .{ .buffer = buffer, .seek = 0, .end = 0, .vtable = &.{ .stream = VTable.stream, .discard = VTable.discard, }, }, .child = child, .pending = undefined, .pending_len = 0, }; } /// The `std.Io.Reader` implementation, which forwards to `stream`. const VTable = struct { /// Decodes into `w`, at most `limit` bytes. fn stream(interface: *std.Io.Reader, w: *std.Io.Writer, limit: std.Io.Limit) std.Io.Reader.StreamError!usize { const self: *Self = @alignCast(@fieldParentPtr("interface", interface)); return self.stream(w, limit); } /// Decodes at most `limit` bytes and throws them away. fn discard(interface: *std.Io.Reader, limit: std.Io.Limit) std.Io.Reader.Error!usize { const self: *Self = @alignCast(@fieldParentPtr("interface", interface)); var scratch: [64]u8 = undefined; var discarding: std.Io.Writer.Discarding = .init(&scratch); return self.stream(&discarding.writer, limit) catch |err| switch (err) { error.WriteFailed => unreachable, else => |e| return e, }; } }; /// Copies as much of `bytes` into `dest` as fits, holding the rest over /// for the next read. Asserts nothing is already held over, which is /// guaranteed because holding anything over fills `dest`. fn emit(self: *Self, dest: []u8, count: *usize, bytes: []const u8) void { std.debug.assert(self.pending_len == 0); const size = @min(bytes.len, dest.len - count.*); @memcpy(dest[count.*..][0..size], bytes[0..size]); count.* += size; const rest = bytes[size..]; @memcpy(self.pending[0..rest.len], rest); self.pending_len = rest.len; } /// Encodes from `child` into the writable space of `w`, at most /// `limit` bytes, and returns how many were written. A failure after /// some bytes have been encoded ends the read early, and is reported by /// the next one. fn stream(self: *Self, w: *std.Io.Writer, limit: std.Io.Limit) std.Io.Reader.StreamError!usize { const dest = limit.slice(try w.writableSliceGreedy(1)); if (dest.len == 0) return 0; var count: usize = 0; if (self.pending_len > 0) { const size = @min(self.pending_len, dest.len); @memcpy(dest[0..size], self.pending[0..size]); count = size; self.pending_len -= size; for (0..self.pending_len) |index| self.pending[index] = self.pending[size + index]; } outer: while (count < dest.len) { const src = self.child.peekGreedy(2) catch |err| switch (err) { error.ReadFailed => { if (count > 0) break :outer; return error.ReadFailed; }, error.EndOfStream => { // Fewer than two bytes remain in the stream. const byte = self.child.peekByte() catch |e| switch (e) { error.EndOfStream => break :outer, error.ReadFailed => { if (count > 0) break :outer; return error.ReadFailed; }, }; self.child.toss(1); switch (byte) { cr => self.emit(dest, &count, &cr_replacement), lf => self.emit(dest, &count, &lf_replacement), else => { dest[count] = byte; count += 1; }, } continue :outer; }, }; // Copy everything up to the next byte needing an escape verbatim. const special_index = std.mem.indexOfAny(u8, src, specials) orelse src.len; if (special_index > 0) { const size = @min(special_index, dest.len - count); @memcpy(dest[count..][0..size], src[0..size]); count += size; self.child.toss(size); continue :outer; } // `src` starts with a CR, or with an LF that needs an escape, // and holds at least two bytes. if (src[0] == cr) { if (src[1] == lf) { self.child.toss(2); self.emit(dest, &count, &crlf_replacement); } else { self.child.toss(1); self.emit(dest, &count, &cr_replacement); } } else { self.child.toss(1); self.emit(dest, &count, &lf_replacement); } } if (count == 0) return error.EndOfStream; w.advance(count); return count; } }; } /// Encodes `input` with both `_encode` and `_EncodeReader`, asserting that they /// agree with each other and with `expected`. fn testEncodeReader( comptime linesep: LineSeparator, comptime buffer_len: usize, input: []const u8, expected: []const u8, ) !void { { var child: std.Io.Reader = .fixed(input); var buf: std.Io.Writer.Allocating = .init(testing.allocator); defer buf.deinit(); try _encode(&child, &buf.writer, linesep); try testing.expectEqualStrings(expected, buf.written()); } var child: std.Io.Reader = .fixed(input); var encode_buf: [buffer_len]u8 = undefined; var encoder: _EncodeReader(linesep) = .init(&child, &encode_buf); var buf: std.Io.Writer.Allocating = .init(testing.allocator); defer buf.deinit(); _ = try encoder.interface.streamRemaining(&buf.writer); try testing.expectEqualStrings(expected, buf.written()); try testing.expectEqual(0, child.bufferedLen()); } test "encode reader cr 1" { try testEncodeReader(.cr, 8, "foo\x0dbar", "foo\x0d\x0abar"); } test "encode reader cr 2" { try testEncodeReader(.cr, 8, "foo\x0d\x0abar", "foo\x0d\x0a\x0d\x0abar"); } test "encode reader cr 3" { try testEncodeReader(.cr, 8, "foo\x0abar", "foo\x0d\x0abar"); } test "encode reader lf 1" { try testEncodeReader(.lf, 8, "foo\x0dbar", "foo\x0d\x00bar"); } test "encode reader lf 2" { try testEncodeReader(.lf, 8, "foo\x0d\x0abar", "foo\x0d\x00\x0d\x0abar"); } test "encode reader lf 3" { try testEncodeReader(.lf, 8, "foo\x0abar", "foo\x0d\x0abar"); } test "encode reader crlf 1" { try testEncodeReader(.crlf, 8, "foo\x0dbar", "foo\x0d\x00bar"); } test "encode reader crlf 2" { try testEncodeReader(.crlf, 8, "foo\x0d\x0abar", "foo\x0d\x0abar"); } test "encode reader crlf 3" { try testEncodeReader(.crlf, 8, "foo\x0abar", "foo\x0d\x0abar"); } test "encode reader empty" { try testEncodeReader(.lf, 8, "", ""); } test "encode reader trailing cr" { try testEncodeReader(.lf, 8, "foo\x0d", "foo\x0d\x00"); } test "encode reader trailing lf" { try testEncodeReader(.lf, 8, "foo\x0a", "foo\x0d\x0a"); } test "encode reader zero length buffer" { var child: std.Io.Reader = .fixed("foo\x0abar\x0d"); var encoder: _EncodeReader(.lf) = .init(&child, &.{}); var out: [16]u8 = undefined; const n = try encoder.interface.readSliceShort(&out); try testing.expectEqualStrings("foo\x0d\x0abar\x0d\x00", out[0..n]); } test "encode reader byte at a time" { // Forces every multi byte replacement to be split across reads. var child: std.Io.Reader = .fixed("\x0d\x0a\x0d\x0a"); var encode_buf: [1]u8 = undefined; var encoder: _EncodeReader(.cr) = .init(&child, &encode_buf); var buf: std.Io.Writer.Allocating = .init(testing.allocator); defer buf.deinit(); while (encoder.interface.streamExact(&buf.writer, 1)) {} else |err| { try testing.expectEqual(error.EndOfStream, err); } try testing.expectEqualStrings("\x0d\x0a\x0d\x0a\x0d\x0a\x0d\x0a", buf.written()); } test "encode reader byte at a time, four byte replacement" { var child: std.Io.Reader = .fixed("\x0d\x0a\x0d\x0a"); var encode_buf: [1]u8 = undefined; var encoder: _EncodeReader(.lf) = .init(&child, &encode_buf); var buf: std.Io.Writer.Allocating = .init(testing.allocator); defer buf.deinit(); while (encoder.interface.streamExact(&buf.writer, 1)) {} else |err| { try testing.expectEqual(error.EndOfStream, err); } try testing.expectEqualStrings("\x0d\x00\x0d\x0a\x0d\x00\x0d\x0a", buf.written()); } test "encode reader discard" { var child: std.Io.Reader = .fixed("foo\x0abar\x0dbaz"); var encode_buf: [4]u8 = undefined; var encoder: _EncodeReader(.lf) = .init(&child, &encode_buf); try testing.expectEqual(13, try encoder.interface.discardRemaining()); } /// Encodes `input` and decodes it again, appending the result to `output`. fn roundTrip( comptime linesep: LineSeparator, input: []const u8, output: *std.Io.Writer.Allocating, ) !void { var child: std.Io.Reader = .fixed(input); var encode_buf: [3]u8 = undefined; var encoder: _EncodeReader(linesep) = .init(&child, &encode_buf); var encoded: std.Io.Writer.Allocating = .init(testing.allocator); defer encoded.deinit(); _ = try encoder.interface.streamRemaining(&encoded.writer); var encoded_reader: std.Io.Reader = .fixed(encoded.written()); var decode_buf: [3]u8 = undefined; var decoder: _DecodeReader(linesep) = .init(&encoded_reader, &decode_buf); _ = try decoder.interface.streamRemaining(&output.writer); } test "encode reader round trip" { const inputs = [_][]const u8{ "", "hello", "foo\x0abar", "foo\x0dbar", "foo\x0d\x0abar", "\x0a\x0a\x0d\x0d\x0a\x0d\x00", }; inline for (.{ .cr, .lf, .crlf }) |linesep| { for (inputs) |input| { // A round trip normalizes line endings to the local convention. // Under `.lf` that is lossless, because every local line terminator // and every data byte survives. Under `.cr` and `.crlf` it is not: // netascii has no escape for a data LF, so a lone LF in the input // comes back as a line terminator. The property that holds for // every separator is therefore idempotence rather than identity. var once: std.Io.Writer.Allocating = .init(testing.allocator); defer once.deinit(); try roundTrip(linesep, input, &once); var twice: std.Io.Writer.Allocating = .init(testing.allocator); defer twice.deinit(); try roundTrip(linesep, once.written(), &twice); try testing.expectEqualStrings(once.written(), twice.written()); if (linesep == .lf) try testing.expectEqualStrings(input, once.written()); } } } // The tests below check this implementation against tftp-hpa, the de facto // reference TFTP implementation on Linux, over an exhaustive corpus. tftp-hpa // ships no test suite of its own, so the reference is its source: the netascii // conversions in `common/tftpsubs.c`, transcribed here. // // tftp-hpa has no per platform tables. It opens files with `O_TEXT` and lets // the C runtime translate line endings, then always applies the conversions // below, which are the `.lf` case. The other separators are therefore compared // against that same composition: `textRead` and `textWrite` model what a C // runtime does in text mode, and every separator must equal the reference // sandwiched between them. /// Output buffer for the reference implementations. The corpus inputs are /// short and encoding at most doubles the length, so a fixed buffer is enough. const HpaBuffer = struct { bytes: [16]u8 = undefined, len: usize = 0, /// Appends `byte`, which must fit. fn append(self: *HpaBuffer, byte: u8) void { self.bytes[self.len] = byte; self.len += 1; } /// Everything appended so far. fn written(self: *const HpaBuffer) []const u8 { return self.bytes[0..self.len]; } }; /// Transcription of `read_ahead` from tftp-hpa `common/tftpsubs.c`, which /// converts local text to netascii: "conversions are lf -> cr,lf and cr -> /// cr,nul". It works one character at a time with no lookahead, so a CR LF pair /// encodes as CR NUL CR LF rather than CR NUL LF. fn hpaEncode(input: []const u8) HpaBuffer { var output: HpaBuffer = .{}; var newline = false; var prevchar: i32 = -1; var index: usize = 0; while (true) { var byte: u8 = undefined; if (newline) { byte = if (prevchar == std.ascii.control_code.lf) std.ascii.control_code.lf else std.ascii.control_code.nul; newline = false; } else { // `getc` returning EOF. if (index >= input.len) break; byte = input[index]; index += 1; if (byte == std.ascii.control_code.lf or byte == std.ascii.control_code.cr) { prevchar = byte; byte = std.ascii.control_code.cr; newline = true; } } output.append(byte); } return output; } /// Transcription of `write_behind` from tftp-hpa `common/tftpsubs.c`, which /// converts netascii to local text: "CR,NUL -> CR and CR,LF => LF". Its /// `fseek(file, -1, 1)` smashes the LF on top of the CR already written, which /// is the length decrement here. /// /// A CR followed by anything else is passed through unchanged. tftp-hpa notes /// that "spec is undefined if we get CR as last byte of file or a CR followed /// by anything else. In this case we leave it alone." This implementation /// rejects those inputs instead, so they are compared only for that rejection. fn hpaDecode(input: []const u8) HpaBuffer { var output: HpaBuffer = .{}; var prevchar: i32 = -1; for (input) |byte| { if (prevchar == std.ascii.control_code.cr) { if (byte == std.ascii.control_code.lf) { // Seek back over the CR that was already emitted. output.len -= 1; } else if (byte == std.ascii.control_code.nul) { prevchar = byte; continue; } } output.append(byte); prevchar = byte; } return output; } /// Local text to LF only text: what a C runtime does when reading a file opened /// in text mode. tftp-hpa relies on this and then always applies `read_ahead`. fn textRead(comptime linesep: LineSeparator, input: []const u8) HpaBuffer { var output: HpaBuffer = .{}; var index: usize = 0; while (index < input.len) : (index += 1) { switch (linesep) { // A CR is dropped only when it is immediately followed by an LF. .crlf => if (input[index] == std.ascii.control_code.cr and index + 1 < input.len and input[index + 1] == std.ascii.control_code.lf) continue, .cr => if (input[index] == std.ascii.control_code.cr) { output.append(std.ascii.control_code.lf); continue; }, .lf => {}, } output.append(input[index]); } return output; } /// LF only text back to local text: what a C runtime does when writing a file /// opened in text mode, and the reverse of `textRead`. fn textWrite(comptime linesep: LineSeparator, input: []const u8) HpaBuffer { var output: HpaBuffer = .{}; for (input) |byte| { if (byte == std.ascii.control_code.lf) { switch (linesep) { .crlf => { output.append(std.ascii.control_code.cr); output.append(std.ascii.control_code.lf); continue; }, .cr => { output.append(std.ascii.control_code.cr); continue; }, .lf => {}, } } output.append(byte); } return output; } /// Whether `input` is well formed netascii, which RFC 854 defines by requiring /// that a CR be followed by either an LF or a NUL. fn isNetascii(input: []const u8) bool { var index: usize = 0; while (index < input.len) { if (input[index] != std.ascii.control_code.cr) { index += 1; continue; } if (index + 1 >= input.len) return false; switch (input[index + 1]) { std.ascii.control_code.lf, std.ascii.control_code.nul => index += 2, else => return false, } } return true; } test "netascii differential corpus against tftp-hpa" { const alloc = std.testing.allocator; const alphabet = [_]u8{ std.ascii.control_code.cr, std.ascii.control_code.lf, std.ascii.control_code.nul, 'a', }; const max_len = 4; var case_count: usize = 0; for (0..max_len + 1) |len| { var total: usize = 1; for (0..len) |_| total *= alphabet.len; for (0..total) |counter| { var input_buf: [max_len]u8 = undefined; var remaining = counter; for (0..len) |position| { input_buf[len - 1 - position] = alphabet[remaining % alphabet.len]; remaining /= alphabet.len; } const input = input_buf[0..len]; case_count += 1; inline for (.{ .cr, .lf, .crlf }) |linesep| { // Encoding must equal the reference applied to text mode input. const local = textRead(linesep, input); const expected_encoded = hpaEncode(local.written()); { var child: std.Io.Reader = .fixed(input); var encode_buf: [3]u8 = undefined; var encoder: _EncodeReader(linesep) = .init(&child, &encode_buf); var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); _ = try encoder.interface.streamRemaining(&buf.writer); try testing.expectEqualStrings(expected_encoded.written(), buf.written()); } { var child: std.Io.Reader = .fixed(input); var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); try _encode(&child, &buf.writer, linesep); try testing.expectEqualStrings(expected_encoded.written(), buf.written()); } // Decoding must equal the reference written back out in text // mode, and must reject exactly the inputs RFC 854 disallows. var child: std.Io.Reader = .fixed(input); var decode_buf: [3]u8 = undefined; var decoder: _DecodeReader(linesep) = .init(&child, &decode_buf); var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); var function_input: std.Io.Reader = .fixed(input); var function_buf: std.Io.Writer.Allocating = .init(alloc); defer function_buf.deinit(); if (isNetascii(input)) { const reference = hpaDecode(input); const expected_decoded = textWrite(linesep, reference.written()); _ = try decoder.interface.streamRemaining(&buf.writer); try testing.expectEqualStrings(expected_decoded.written(), buf.written()); _ = try _decode(&function_input, &function_buf.writer, null, linesep); try testing.expectEqualStrings(expected_decoded.written(), function_buf.written()); } else { try testing.expectError( error.ReadFailed, decoder.interface.streamRemaining(&buf.writer), ); try testing.expectEqual(error.UnescapedCR, decoder.err.?); try testing.expectError( error.UnescapedCR, _decode(&function_input, &function_buf.writer, null, linesep), ); } } } } // Guards against the corpus silently shrinking. 4^0 + ... + 4^4. try testing.expectEqual(341, case_count); } test "netascii cr 1" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("\x0d\x00"); _ = try _decode(&input, output, null, .cr); try testing.expectEqualStrings("\x0d", buf.written()); } test "netascii cr 2" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("\x0d\x0a"); _ = try _decode(&input, output, null, .cr); try testing.expectEqualStrings("\x0d", buf.written()); try testing.expectEqual(0, input.bufferedLen()); } test "netascii cr 3" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("foo\x0d\x0a\x0abar"); _ = try _decode(&input, output, null, .cr); try testing.expectEqualStrings("foo\x0d\x0dbar", buf.written()); try testing.expectEqual(0, input.bufferedLen()); } test "netascii cr 4" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("foo\x0d\x00\x0abar"); _ = try _decode(&input, output, null, .cr); try testing.expectEqualStrings("foo\x0d\x0dbar", buf.written()); try testing.expectEqual(0, input.bufferedLen()); } test "netascii cr 5" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("foo\x0d\x0a\x0dbar"); try testing.expectError(error.UnescapedCR, _decode(&input, output, null, .cr)); } test "netascii lf 1" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("\x0d\x00"); _ = try _decode(&input, output, null, .lf); try testing.expectEqualStrings("\x0d", buf.written()); try testing.expectEqual(0, input.bufferedLen()); } test "netascii lf 2" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("\x0d\x0a"); _ = try _decode(&input, output, null, .lf); try testing.expectEqualStrings("\x0a", buf.written()); try testing.expectEqual(0, input.bufferedLen()); } test "netascii lf 3" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("foo\x0d\x0a\x0abar"); _ = try _decode(&input, output, null, .lf); try testing.expectEqualStrings("foo\x0a\x0abar", buf.written()); try testing.expectEqual(0, input.bufferedLen()); } test "netascii lf 4" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("foo\x0d\x00\x0abar"); _ = try _decode(&input, output, null, .lf); try testing.expectEqualStrings("foo\x0d\x0abar", buf.written()); try testing.expectEqual(0, input.bufferedLen()); } test "netascii lf 5" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("foo\x0d\x0a\x0dbar"); try testing.expectError(error.UnescapedCR, _decode(&input, output, null, .lf)); } test "netascii crlf 1" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("\x0d\x00"); _ = try _decode(&input, output, null, .crlf); try testing.expectEqualStrings("\x0d", buf.written()); try testing.expectEqual(0, input.bufferedLen()); } test "netascii crlf 2" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("\x0d\x0a"); _ = try _decode(&input, output, null, .crlf); try testing.expectEqualStrings("\x0d\x0a", buf.written()); try testing.expectEqual(0, input.bufferedLen()); } test "netascii crlf 3" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("foo\x0d\x0a\x0abar"); _ = try _decode(&input, output, null, .crlf); try testing.expectEqualStrings("foo\x0d\x0a\x0d\x0abar", buf.written()); try testing.expectEqual(0, input.bufferedLen()); } test "netascii crlf 4" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("foo\x0d\x00\x0abar"); _ = try _decode(&input, output, null, .crlf); try testing.expectEqualStrings("foo\x0d\x0d\x0abar", buf.written()); try testing.expectEqual(0, input.bufferedLen()); } test "netascii crlf 5" { const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; var input: std.Io.Reader = .fixed("foo\x0d\x0a\x0dbar"); try testing.expectError(error.UnescapedCR, _decode(&input, output, null, .crlf)); } test "netascii decodeZ lf 1" { var input: std.Io.Reader = .fixed("test.txt\x00netascii\x00"); const alloc = std.testing.allocator; { var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; _ = try _decode(&input, output, std.ascii.control_code.nul, .lf); try testing.expectEqualStrings("test.txt", buf.written()); try testing.expectEqual(9, input.bufferedLen()); } { var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; _ = try _decode(&input, output, std.ascii.control_code.nul, .lf); try testing.expectEqualStrings("netascii", buf.written()); try testing.expectEqual(0, input.bufferedLen()); } } test "netascii decodeZ lf 2" { var input: std.Io.Reader = .fixed("test.txt"); const alloc = std.testing.allocator; var buf: std.Io.Writer.Allocating = .init(alloc); defer buf.deinit(); const output = &buf.writer; try testing.expectError(error.MissingSentinel, _decode(&input, output, std.ascii.control_code.nul, .lf)); }