// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `DISPLAY-HINT`, the little format language of RFC 2579 §3.1. //! //! A textual convention may say how values of its type are meant to be read //! by people, and a manager that ignores it prints hex where the MIB author //! intended a MAC address: //! //! ``` //! PhysAddress ::= TEXTUAL-CONVENTION DISPLAY-HINT "1x:" SYNTAX OCTET STRING //! 18 C0 4D 95 93 86 without the hint //! 18:c0:4d:95:93:86 with it //! //! DateAndTime ::= TEXTUAL-CONVENTION DISPLAY-HINT "2d-1d-1d,1d:1d:1d.1d" //! 00 00 01 01 00 00 00 00 without //! 0-1-1,0:0:0.0 with //! ``` //! //! This lives here rather than in a manager because the language is SMI's and //! knows nothing about SNMP: it turns a string of octets, or an integer, into //! text. What decides *which* hint applies to a value is the textual //! convention its syntax names, which `Registry.resolveSyntax` answers. //! //! ## The grammar, and where it is looser than it looks //! //! For an OCTET STRING a hint is a sequence of //! `[[]]`, where the repeat is a //! number or `*` --- `*` meaning "take the count from the next octet", which //! is how a variable-length field inside a fixed structure is written. For an //! INTEGER it is a single `d`, `x`, `o` or `b`, and `d` may carry `-N` to say //! the value has N implied decimal places: `d-2` renders 1234 as `12.34`. //! //! Two rules are easy to get wrong and both show up in the first real value //! anybody tries: //! //! - **The separator goes between repeats, not after them.** `1x:` on six //! octets is five colons, not six. //! - **When the octets outlast the hint, the last piece repeats.** That is //! the whole of how `1x:` --- one piece --- formats an address of any //! length. //! //! A hint that cannot be parsed is not an error worth raising. Vendor MIBs //! contain plenty of nonsense hints, and the right answer for one is to print //! the value the ordinary way rather than to refuse the value. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const testing = std.testing; const DisplayHint = @This(); /// How one piece of the value is written. pub const Format = enum { /// `x` --- hexadecimal, lower case, no leading zeroes. hex, /// `d` --- decimal. decimal, /// `o` --- octal. octal, /// `b` --- binary. binary, /// `a` --- the octets as ASCII text. ascii, /// `t` --- the octets as UTF-8 text. Treated as `a`, because both mean /// "these octets are already the characters". utf8, fn base(f: Format) u8 { return switch (f) { .hex => 16, .decimal => 10, .octal => 8, .binary => 2, .ascii, .utf8 => 0, }; } fn isText(f: Format) bool { return f == .ascii or f == .utf8; } }; /// One `[*][[]]` of a hint. pub const Piece = struct { /// How many octets one repeat of this piece consumes. `2d` is two. count: u32, /// `*`: how many *repeats* to do is the value of the next octet, which is /// consumed. `*1x:` reads a length and then that many octets as hex. /// Without it, one repeat. repeat_from_octet: bool = false, format: Format, /// Written between repeats, never after the last. separator: ?u8 = null, /// Written after a `*` group, which is what ends a variable-length group /// so the next piece can begin. Only `*1x:/1x:` in the corpus uses one. terminator: ?u8 = null, }; /// What an INTEGER hint says. pub const Integer = struct { format: Format, /// `d-2` means two implied decimal places: 1234 is rendered `12.34`. decimals: u8 = 0, }; pieces: []const Piece, integer: ?Integer, /// The hint as written, for anything that wants to show it back. text: []const u8, pub const ParseError = error{NotAHint} || Allocator.Error; /// Reads a hint. `gpa` owns the pieces; call `deinit` to give them back. /// /// Fails only when the text is not a hint at all. A caller should treat that /// as "render this value the ordinary way", not as a fault: a MIB with a /// malformed hint still has values worth printing. pub fn parse(gpa: Allocator, text: []const u8) ParseError!DisplayHint { if (text.len == 0) return error.NotAHint; // An integer hint is the whole string and has no repeat count: `d`, `x`, // `o`, `b`, or `d-2`. Anything beginning with a digit or `*` is an octet // hint, which is what makes the two distinguishable at the first // character. if (!std.ascii.isDigit(text[0]) and text[0] != '*') { const format = formatOf(text[0]) orelse return error.NotAHint; var decimals: u8 = 0; if (text.len > 1) { if (text[1] != '-') return error.NotAHint; decimals = std.fmt.parseInt(u8, text[2..], 10) catch return error.NotAHint; } return .{ .pieces = &.{}, .integer = .{ .format = format, .decimals = decimals }, .text = text }; } var pieces: std.ArrayList(Piece) = .empty; errdefer pieces.deinit(gpa); var i: usize = 0; while (i < text.len) { var piece: Piece = .{ .count = 1, .format = .hex }; if (text[i] == '*') { piece.repeat_from_octet = true; i += 1; } // The count follows the star rather than replacing it: `*1x:` is a // repeat count read from an octet, of pieces that are one octet wide. { const start = i; while (i < text.len and std.ascii.isDigit(text[i])) i += 1; if (i == start) return error.NotAHint; piece.count = std.fmt.parseInt(u32, text[start..i], 10) catch return error.NotAHint; if (piece.count == 0) return error.NotAHint; } if (i >= text.len) return error.NotAHint; piece.format = formatOf(text[i]) orelse return error.NotAHint; i += 1; // A separator is any character that does not begin the next piece. if (i < text.len and text[i] != '*' and !std.ascii.isDigit(text[i])) { piece.separator = text[i]; i += 1; if (piece.repeat_from_octet and i < text.len and text[i] != '*' and !std.ascii.isDigit(text[i])) { piece.terminator = text[i]; i += 1; } } try pieces.append(gpa, piece); } if (pieces.items.len == 0) return error.NotAHint; return .{ .pieces = try pieces.toOwnedSlice(gpa), .integer = null, .text = text }; } pub fn deinit(h: *DisplayHint, gpa: Allocator) void { gpa.free(h.pieces); h.* = undefined; } /// Whether this hint describes an integer rather than a string of octets. pub fn isInteger(h: DisplayHint) bool { return h.integer != null; } /// Writes an integer through the hint. pub fn renderInteger(h: DisplayHint, value: i64, w: *Io.Writer) Io.Writer.Error!void { const spec = h.integer orelse return w.print("{d}", .{value}); // Sign and magnitude, kept apart from the start. A hint may pair `x`, // `o` or `b` with an `Integer32`, which is signed, and the standard // formatters overflow on a negative value in those bases -- found by the // fuzzer on the first run, at `-1`. `@abs` also handles the one value // that cannot be negated, `minInt(i64)`, which a `-%value` would leave // negative and silently wrong. const negative = value < 0; const magnitude: u64 = @abs(value); if (negative) try w.writeByte('-'); if (spec.decimals == 0) { switch (spec.format) { .hex => try w.print("{x}", .{magnitude}), .octal => try w.print("{o}", .{magnitude}), .binary => try w.print("{b}", .{magnitude}), .decimal, .ascii, .utf8 => try w.print("{d}", .{magnitude}), } return; } // `d-2` on 1234 is `12.34`, and on 5 is `0.05`: the digits after the // point are padded, the ones before are not. var divisor: u64 = 1; for (0..@min(spec.decimals, 19)) |_| divisor *= 10; try w.print("{d}.", .{magnitude / divisor}); const fraction = magnitude % divisor; // Leading zeroes of the fractional part, which `{d}` would drop. var scale = divisor / 10; while (scale > 1 and fraction < scale) : (scale /= 10) try w.writeByte('0'); try w.print("{d}", .{fraction}); } /// Writes a string of octets through the hint. pub fn renderOctets(h: DisplayHint, octets: []const u8, w: *Io.Writer) Io.Writer.Error!void { if (h.pieces.len == 0) return w.writeAll(octets); var at: usize = 0; var index: usize = 0; while (at < octets.len) { // When the octets outlast the hint the last piece repeats, which is // the whole of how a one-piece hint like `1x:` formats an address of // any length. const piece = h.pieces[@min(index, h.pieces.len - 1)]; index += 1; var repeats: usize = 1; if (piece.repeat_from_octet) { repeats = octets[at]; at += 1; } for (0..repeats) |n| { if (at >= octets.len) break; if (n != 0) { if (piece.separator) |separator| try w.writeByte(separator); } const take = @min(@as(usize, piece.count), octets.len - at); try writeChunk(piece.format, octets[at..][0..take], w); at += take; } if (piece.repeat_from_octet) { if (piece.terminator) |t| try w.writeByte(t); continue; } // Between repeats of a plain piece, never after the last. if (at < octets.len) { if (piece.separator) |separator| try w.writeByte(separator); } } } fn writeChunk(format: Format, chunk: []const u8, w: *Io.Writer) Io.Writer.Error!void { if (format.isText()) return w.writeAll(chunk); // The octets of one piece are one big-endian number: `2d` on `00 0a` is // ten, not zero and then ten. var n: u64 = 0; for (chunk) |byte| n = (n << 8) | byte; switch (format) { .hex => try w.print("{x}", .{n}), .decimal => try w.print("{d}", .{n}), .octal => try w.print("{o}", .{n}), .binary => try w.print("{b}", .{n}), .ascii, .utf8 => unreachable, } } fn formatOf(c: u8) ?Format { return switch (c) { 'x', 'X' => .hex, 'd', 'D' => .decimal, 'o', 'O' => .octal, 'b', 'B' => .binary, 'a', 'A' => .ascii, 't', 'T' => .utf8, else => null, }; } // -- tests ------------------------------------------------------------------ fn expectOctets(hint: []const u8, octets: []const u8, expected: []const u8) !void { var h = try parse(testing.allocator, hint); defer h.deinit(testing.allocator); var buffer: [256]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try h.renderOctets(octets, &w); try testing.expectEqualStrings(expected, w.buffered()); } fn expectInteger(hint: []const u8, value: i64, expected: []const u8) !void { var h = try parse(testing.allocator, hint); defer h.deinit(testing.allocator); // Room for a 64-bit value in binary, which is the widest a hint asks for. var buffer: [128]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try h.renderInteger(value, &w); try testing.expectEqualStrings(expected, w.buffered()); } test "1x:, which is PhysAddress and the reason anybody wants this" { try expectOctets("1x:", &.{ 0x18, 0xc0, 0x4d, 0x95, 0x93, 0x86 }, "18:c0:4d:95:93:86"); // No leading zeroes: net-snmp prints `0`, not `00`, for a zero octet. try expectOctets("1x:", &.{ 0x52, 0x54, 0x00, 0x84, 0xe2, 0xd3 }, "52:54:0:84:e2:d3"); // One octet is no separators at all, not a trailing one. try expectOctets("1x:", &.{0xab}, "ab"); try expectOctets("1x:", &.{}, ""); } test "2d-1d-1d,1d:1d:1d.1d, which is DateAndTime" { // Seven pieces consuming exactly eight octets, and the last has no // separator to write. try expectOctets( "2d-1d-1d,1d:1d:1d.1d", &.{ 0, 0, 1, 1, 0, 0, 0, 0 }, "0-1-1,0:0:0.0", ); try expectOctets( "2d-1d-1d,1d:1d:1d.1d", &.{ 0x07, 0xe6, 9, 12, 15, 4, 30, 50 }, "2022-9-12,15:4:30.50", ); } test "the octets of one piece are one number, not several" { // `2d` on `00 0a` is ten. A reader that took each octet separately would // say `0` then `10`, and a year would come out as two numbers. try expectOctets("2d", &.{ 0x00, 0x0a }, "10"); try expectOctets("2d", &.{ 0x07, 0xe6 }, "2022"); try expectOctets("4d", &.{ 0, 1, 0, 0 }, "65536"); } test "255a, which is DisplayString" { try expectOctets("255a", "hello", "hello"); // A count larger than what is there takes what is there. try expectOctets("255a", "", ""); // And text with a separator still writes the separator between repeats. try expectOctets("1a:", "abc", "a:b:c"); } test "the hints the corpus actually contains" { // Every one of these appears in net-snmp's or Cisco's MIBs. Inventing a // hint to test against would be testing a reading of RFC 2579 rather than // anything a MIB says. try expectOctets("1d.1d.1d.1d", &.{ 192, 168, 4, 64 }, "192.168.4.64"); try expectOctets("1d.1d.1d.1d:2d", &.{ 192, 168, 4, 64, 0x00, 0xa1 }, "192.168.4.64:161"); try expectOctets( "2x:2x:2x:2x:2x:2x:2x:2x", &.{ 0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, "2001:db8:0:0:0:0:0:1", ); try expectOctets("2x:", &.{ 0x12, 0x34, 0xab, 0xcd }, "1234:abcd"); try expectOctets("4d", &.{ 0, 0, 0x01, 0x00 }, "256"); } test "a starred repeat count, read from the octet in front of the group" { // `*1x:/1x:` is the only starred hint in the corpus: a length, then that // many octets as colon-separated hex, then `/`, then the rest the same // way. The star governs how many *repeats* there are, not how wide one // is, which is the part that is easy to read backwards. try expectOctets("*1x:/1x:", &.{ 3, 0xaa, 0xbb, 0xcc, 0x11, 0x22 }, "aa:bb:cc/11:22"); try expectOctets("*1x:/1x:", &.{ 0, 0x11 }, "/11"); } test "the last piece repeats when the octets outlast the hint" { // RFC 2579's rule, and the whole of how `1x:` -- a single piece -- writes // an address of any length. The piece that repeats is the last one, not // the hint as a whole, which is why `1d.1d.1d.1d` on five octets runs the // final `1d` again with the separator it does not have. try expectOctets("1x:", &.{ 1, 2, 3, 4, 5, 6, 7, 8 }, "1:2:3:4:5:6:7:8"); try expectOctets("1d.1d.1d.1d", &.{ 1, 2, 3, 4, 5 }, "1.2.3.45"); } test "integer hints, including implied decimal places" { try expectInteger("d", 1234, "1234"); try expectInteger("x", 255, "ff"); try expectInteger("o", 8, "10"); try expectInteger("b", 5, "101"); // `d-2` is two implied decimal places, and the fractional digits are // padded where the whole ones are not. try expectInteger("d-2", 1234, "12.34"); try expectInteger("d-2", 5, "0.05"); try expectInteger("d-2", 100, "1.00"); try expectInteger("d-3", 1, "0.001"); try expectInteger("d-2", -1234, "-12.34"); // A signed value in a base that is not ten. The standard formatters // overflow here rather than printing anything, which the fuzzer found at // `-1` within a second of the target being written. try expectInteger("x", -1, "-1"); try expectInteger("x", -255, "-ff"); try expectInteger("b", std.math.minInt(i64), "-1" ++ @as([63]u8, @splat('0'))); try expectInteger("d-2", std.math.minInt(i64), "-92233720368547758.08"); } test "a hint that is not one is refused, not guessed at" { // Vendor MIBs contain plenty of these, and the right answer for a caller // is to print the value the ordinary way rather than refuse the value. for ([_][]const u8{ "", "q", "1", "0x", "1z", "d-", "d-x", "1x-and then some" }) |text| { try testing.expectError(error.NotAHint, parse(testing.allocator, text)); } } test "an integer hint and an octet hint are told apart at the first character" { { var h = try parse(testing.allocator, "d-2"); defer h.deinit(testing.allocator); try testing.expect(h.isInteger()); } { var h = try parse(testing.allocator, "1x:"); defer h.deinit(testing.allocator); try testing.expect(!h.isInteger()); } }