// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Parsing of the port half of an endpoint, shared by `Ipv4Endpoint` and //! `Ipv6Endpoint`. Internal to the library. const std = @import("std"); pub const ParseError = error{ /// Nothing followed the `:`, as in `192.0.2.1:`. EmptyPort, /// The port held a character other than a decimal digit. InvalidPort, /// The port had a redundant leading zero, as in `:0443`. LeadingZero, /// The port was greater than 65535. PortOutOfRange, }; /// Parses a decimal port. Port 0 is accepted: it is how a caller asks the /// operating system to choose one. pub fn parse(text: []const u8) ParseError!u16 { if (text.len == 0) return error.EmptyPort; // One pass: the value accumulates while the characters are checked, and a // bad character only wins over the checks below because they are deferred // until the whole text has been seen. The accumulator stops after five // digits, by which point the port is out of range anyway. var value: u32 = 0; var invalid = false; for (text, 0..) |c, i| { const digit = c -% '0'; if (digit > 9) { invalid = true; } else if (i < 5) { value = value * 10 + digit; } } if (invalid) return error.InvalidPort; if (text.len > 1 and text[0] == '0') return error.LeadingZero; if (text.len > 5 or value > std.math.maxInt(u16)) return error.PortOutOfRange; return @intCast(value); } /// The longest text a port can format to, `65535`. pub const max_text_len = "65535".len; const testing = std.testing; test parse { try testing.expectEqual(@as(u16, 443), try parse("443")); try testing.expectEqual(@as(u16, 0), try parse("0")); try testing.expectEqual(@as(u16, 65535), try parse("65535")); try testing.expectError(error.EmptyPort, parse("")); try testing.expectError(error.InvalidPort, parse("80x")); try testing.expectError(error.InvalidPort, parse("-1")); try testing.expectError(error.InvalidPort, parse(" 80")); try testing.expectError(error.LeadingZero, parse("0443")); try testing.expectError(error.LeadingZero, parse("00")); try testing.expectError(error.PortOutOfRange, parse("65536")); try testing.expectError(error.PortOutOfRange, parse("123456")); }