// SPDX-FileCopyrightText: © 2022 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The transfer mode named in a read or write request. const std = @import("std"); const testing = std.testing; const Allocator = std.mem.Allocator; const netascii = @import("netascii.zig"); /// The transfer mode of a request, which says how the data is to be /// represented on the wire. Mode names are matched without regard to case, as /// RFC 1350 requires. pub const Mode = enum { /// The errors `decodeZ` can return. A mode string longer than the sixteen /// bytes any valid mode needs fails with `error.WriteFailed`. pub const DecodeErrors = error{ InvalidMode, } || netascii.DecodeSentinelErrors; /// Netascii sent to a user rather than a file. RFC 1350 declares it /// obsolete; it is handled as `netascii` is. mail, /// Text, sent as netascii and translated to and from the local line /// ending convention. netascii, /// Raw eight bit bytes, transferred unchanged. octet, /// Reads a NUL terminated mode name from `input` and returns the mode it /// names, or `error.InvalidMode` if it names none of them. pub fn decodeZ(input: *std.Io.Reader) Mode.DecodeErrors!Mode { var buf: [16]u8 = undefined; var output: std.Io.Writer = .fixed(&buf); _ = try netascii.decodeZ(input, &output); inline for (@typeInfo(Mode).@"enum".field_names) |name| if (std.ascii.eqlIgnoreCase(name, output.buffered())) return @field(Mode, name); return error.InvalidMode; } /// Writes the mode's name to `output`, NUL terminated. pub fn encodeZ(self: Mode, output: *std.Io.Writer) !void { var input: std.Io.Reader = .fixed(@tagName(self)); try netascii.encodeZ(&input, output); } test "mode 1" { { var input: std.Io.Reader = .fixed("mail\x00"); try testing.expectEqual(.mail, Mode.decodeZ(&input)); } { var input: std.Io.Reader = .fixed("MAIL\x00"); try testing.expectEqual(.mail, Mode.decodeZ(&input)); } { var input: std.Io.Reader = .fixed("Mail\x00"); try testing.expectEqual(.mail, Mode.decodeZ(&input)); } { var input: std.Io.Reader = .fixed("MaIl\x00"); try testing.expectEqual(.mail, Mode.decodeZ(&input)); } } test "mode 2" { { var input: std.Io.Reader = .fixed("netascii\x00"); try testing.expectEqual(.netascii, Mode.decodeZ(&input)); } } test "mode 3" { { var input: std.Io.Reader = .fixed("octet\x00"); try testing.expectEqual(.octet, Mode.decodeZ(&input)); } } test "mode 4" { { var input: std.Io.Reader = .fixed("apple\x00"); try testing.expectError(error.InvalidMode, Mode.decodeZ(&input)); } } };