// SPDX-FileCopyrightText: © 2022 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The TFTP packet opcode, the big endian `u16` that begins every packet. const std = @import("std"); const testing = std.testing; /// The type of a TFTP packet. Opcodes 1 through 5 are defined by RFC 1350 and /// opcode 6 by RFC 2347. pub const Opcode = enum(u16) { /// The errors `decode` can return. pub const DecodeErrors = error{ InvalidOpcode, PacketTooLong, } || std.Io.Reader.Error || std.Io.Reader.TakeEnumError; /// Read request. rrq = 1, /// Write request. wrq = 2, /// A block of file data. data = 3, /// Acknowledgment of a data block, or of a write request. ack = 4, /// An error, which terminates the transfer. err = 5, /// Option acknowledgment (RFC 2347). oack = 6, /// Reads a big endian opcode from `input`. An unrecognized value is /// `error.InvalidOpcode`, and its two bytes are consumed all the same. pub fn decode(input: *std.Io.Reader) Opcode.DecodeErrors!Opcode { return input.takeEnum(Opcode, .big) catch |err| switch (err) { error.InvalidEnumTag => return error.InvalidOpcode, else => |e| return e, }; } /// Writes the opcode to `output` as a big endian `u16`. pub fn encode(self: Opcode, output: *std.Io.Writer) !void { try output.writeInt(u16, @intFromEnum(self), .big); } test "opcode" { { var input: std.Io.Reader = .fixed(&[_]u8{ 0x00, 0x00 }); try testing.expectError(error.InvalidOpcode, Opcode.decode(&input)); try testing.expectEqual(0, input.bufferedLen()); } { var input: std.Io.Reader = .fixed(&[_]u8{ 0x00, 0x01 }); try testing.expectEqual(.rrq, try Opcode.decode(&input)); try testing.expectEqual(0, input.bufferedLen()); } { var input: std.Io.Reader = .fixed(&[_]u8{ 0x00, 0x02 }); try testing.expectEqual(.wrq, try Opcode.decode(&input)); try testing.expectEqual(0, input.bufferedLen()); } { var input: std.Io.Reader = .fixed(&[_]u8{ 0x00, 0x03 }); try testing.expectEqual(.data, try Opcode.decode(&input)); try testing.expectEqual(0, input.bufferedLen()); } { var input: std.Io.Reader = .fixed(&[_]u8{ 0x00, 0x04 }); try testing.expectEqual(.ack, try Opcode.decode(&input)); try testing.expectEqual(0, input.bufferedLen()); } { var input: std.Io.Reader = .fixed(&[_]u8{ 0x00, 0x05 }); try testing.expectEqual(.err, try Opcode.decode(&input)); try testing.expectEqual(0, input.bufferedLen()); } { var input: std.Io.Reader = .fixed(&[_]u8{ 0x00, 0x06 }); try testing.expectEqual(.oack, try Opcode.decode(&input)); try testing.expectEqual(0, input.bufferedLen()); } { var input: std.Io.Reader = .fixed(&[_]u8{ 0x01, 0x01 }); try testing.expectError(error.InvalidOpcode, Opcode.decode(&input)); try testing.expectEqual(0, input.bufferedLen()); } } };