// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! RFC 9000 §16: the variable-length integer nearly every field in QUIC is //! written in. //! //! The two most significant bits of the first octet are the base-2 logarithm //! of the length, and the value occupies what is left: //! //! | 2MSB | Length | Usable bits | Range | //! | ---- | ------ | ----------- | --------------------- | //! | `00` | 1 | 6 | 0-63 | //! | `01` | 2 | 14 | 0-16383 | //! | `10` | 4 | 30 | 0-1073741823 | //! | `11` | 8 | 62 | 0-4611686018427387903 | //! //! ## The non-minimal encoding is legal, and that is the thing to know //! //! §16: "Values do not need to be encoded on the minimum number of bytes //! necessary, with the sole exception of the Frame Type field". So 1 may //! arrive as `01`, as `0x4001`, as `0x80000001` or as `0xc000000000000001`, //! and all four are correct. //! //! That is the opposite of the rule this project's sibling libraries enforce //! — HTTP/2's frame lengths and WebSocket's payload lengths both refuse a //! non-minimal encoding, because there two spellings of one length is how two //! implementations come to disagree about where a frame ends. QUIC can afford //! to be lax because every field it matters for is inside an AEAD: an attacker //! who could rewrite a length has already broken the packet protection, and //! at that point the encoding is the least of it. //! //! The consequence for anything written against this file: **a value and its //! encoded length are independent**. Code that re-encodes a parsed varint and //! expects the same octets back is wrong, and `encodedLen` is how a parser //! that must know where the next field starts finds out. const std = @import("std"); const assert = std.debug.assert; /// §16: "0-4611686018427387903", which is 2^62 - 1. pub const max = (@as(u64, 1) << 62) - 1; pub const Error = error{ /// The buffer ended before the encoded integer did. Truncated, }; pub const Parsed = struct { value: u64, /// How many octets it occupied, which is not determined by the value — /// see the note about non-minimal encodings above. len: usize, }; /// Reads a variable-length integer from the front of `bytes`. /// /// Octets past the end of the encoding are left alone, so `bytes` can be the /// rest of a packet and `Parsed.len` says where the next field starts. Every /// length is accepted, the non-minimal ones included; the only failure is /// `Truncated`, when `bytes` stops before the encoding its first octet /// announces. pub fn parse(bytes: []const u8) Error!Parsed { if (bytes.len == 0) return error.Truncated; const len = lengthOf(bytes[0]); if (bytes.len < len) return error.Truncated; // The two length bits are not part of the value. var value: u64 = bytes[0] & 0x3f; for (bytes[1..len]) |b| value = (value << 8) | b; return .{ .value = value, .len = len }; } test parse { // §A.1's two-octet example, followed by whatever the next field is. const got = try parse(&.{ 0x7b, 0xbd, 0xff }); try testing.expectEqual(@as(u64, 15293), got.value); try testing.expectEqual(@as(usize, 2), got.len); // The first octet promises four, and only two have arrived. try testing.expectError(error.Truncated, parse(&.{ 0x9d, 0x7f })); } /// How many octets an encoding beginning with this one occupies. /// /// Total, and deliberately so: every one of the 256 first octets names a /// length, so there is no such thing as a first octet a reader may refuse. pub fn lengthOf(first: u8) usize { return @as(usize, 1) << @intCast(first >> 6); } test lengthOf { // The two high bits alone decide it, whatever the rest of the octet says. try testing.expectEqual(@as(usize, 1), lengthOf(0x25)); try testing.expectEqual(@as(usize, 2), lengthOf(0x40)); try testing.expectEqual(@as(usize, 4), lengthOf(0x9d)); try testing.expectEqual(@as(usize, 8), lengthOf(0xff)); } /// The fewest octets `value` can be written in, which is the length `write` /// uses. /// /// `value` must be at most `max`, which is asserted: anything larger has no /// encoding at all. pub fn encodedLen(value: u64) usize { assert(value <= max); if (value <= 63) return 1; if (value <= 16383) return 2; if (value <= 1073741823) return 4; return 8; } test encodedLen { try testing.expectEqual(@as(usize, 1), encodedLen(63)); try testing.expectEqual(@as(usize, 2), encodedLen(64)); try testing.expectEqual(@as(usize, 4), encodedLen(16384)); try testing.expectEqual(@as(usize, 8), encodedLen(max)); } /// Writes `value` in the fewest octets it fits in, and returns them. /// /// `value` must be at most `max` and `out` must hold `encodedLen(value)` /// octets; both are asserted rather than reported. The slice returned is the /// front of `out`. Writing the shortest form is a choice /// rather than a rule — §16 permits any of them — and it is the one worth /// making: the longer forms exist so that a value whose size is not yet known /// can have space reserved for it, which is a thing a writer does on purpose /// and not a default. pub fn write(out: []u8, value: u64) []u8 { assert(value <= max); const len = encodedLen(value); assert(out.len >= len); switch (len) { 1 => out[0] = @intCast(value), 2 => { std.mem.writeInt(u16, out[0..2], @intCast(value), .big); out[0] |= 0x40; }, 4 => { std.mem.writeInt(u32, out[0..4], @intCast(value), .big); out[0] |= 0x80; }, 8 => { std.mem.writeInt(u64, out[0..8], value, .big); out[0] |= 0xc0; }, else => unreachable, } return out[0..len]; } test write { var buf: [8]u8 = undefined; // §A.1's 15293, in the two octets it needs and no more. try testing.expectEqualSlices(u8, &.{ 0x7b, 0xbd }, write(&buf, 15293)); try testing.expectEqualSlices(u8, &.{0x25}, write(&buf, 37)); } /// Writes `value` in exactly `len` octets, which must be one of 1, 2, 4 or 8 /// and large enough to hold it, and returns those octets at the front of /// `out`. All three conditions are asserted. /// /// The use for this is a length field written before the thing it measures: /// reserve two octets, fill the rest of the packet, then come back and write /// the real length into the space already left. §16 permitting non-minimal /// encodings is exactly what makes that possible. pub fn writeFixed(out: []u8, value: u64, len: usize) []u8 { assert(len == 1 or len == 2 or len == 4 or len == 8); assert(encodedLen(value) <= len); assert(out.len >= len); switch (len) { 1 => out[0] = @intCast(value), 2 => { std.mem.writeInt(u16, out[0..2], @intCast(value), .big); out[0] |= 0x40; }, 4 => { std.mem.writeInt(u32, out[0..4], @intCast(value), .big); out[0] |= 0x80; }, 8 => { std.mem.writeInt(u64, out[0..8], value, .big); out[0] |= 0xc0; }, else => unreachable, } return out[0..len]; } test writeFixed { // Reserve a two-octet Length ahead of a payload nobody has measured yet... var buf: [16]u8 = undefined; const payload = "hello"; @memcpy(buf[2..][0..payload.len], payload); // ...and fill it in afterwards. 5 fits in one octet, but it goes in the // two that were set aside, just as §A.1 writes 37 as `40 25`. _ = writeFixed(buf[0..2], payload.len, 2); try testing.expectEqualSlices(u8, &.{ 0x40, 0x05 }, buf[0..2]); try testing.expectEqual(@as(u64, 5), (try parse(&buf)).value); } const testing = std.testing; test "RFC 9000 A.1: the sample decodings" { // The appendix prints four encodings and what they mean, including the // same value twice at two different lengths -- which is the whole point // of the example. const cases = [_]struct { bytes: []const u8, value: u64, len: usize }{ .{ .bytes = &.{ 0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c }, .value = 151288809941952652, .len = 8 }, .{ .bytes = &.{ 0x9d, 0x7f, 0x3e, 0x7d }, .value = 494878333, .len = 4 }, .{ .bytes = &.{ 0x7b, 0xbd }, .value = 15293, .len = 2 }, .{ .bytes = &.{0x25}, .value = 37, .len = 1 }, // "(as the two-byte sequence 40 25)" — the same 37, said longer. .{ .bytes = &.{ 0x40, 0x25 }, .value = 37, .len = 2 }, }; for (cases) |c| { const got = try parse(c.bytes); try testing.expectEqual(c.value, got.value); try testing.expectEqual(c.len, got.len); } } test "the four lengths, at each of their boundaries" { const cases = [_]struct { value: u64, len: usize }{ .{ .value = 0, .len = 1 }, .{ .value = 63, .len = 1 }, .{ .value = 64, .len = 2 }, .{ .value = 16383, .len = 2 }, .{ .value = 16384, .len = 4 }, .{ .value = 1073741823, .len = 4 }, .{ .value = 1073741824, .len = 8 }, .{ .value = max, .len = 8 }, }; for (cases) |c| { try testing.expectEqual(c.len, encodedLen(c.value)); var buf: [8]u8 = undefined; const written = write(&buf, c.value); try testing.expectEqual(c.len, written.len); const got = try parse(written); try testing.expectEqual(c.value, got.value); try testing.expectEqual(c.len, got.len); } } test "every first octet names a length, so none can be refused" { var first: u16 = 0; while (first <= 255) : (first += 1) { const len = lengthOf(@intCast(first)); try testing.expect(len == 1 or len == 2 or len == 4 or len == 8); // And a buffer of exactly that length always parses. var buf: [8]u8 = @splat(0); buf[0] = @intCast(first); const got = try parse(buf[0..len]); try testing.expectEqual(len, got.len); try testing.expect(got.value <= max); } } test "a non-minimal encoding is legal and means what the short one means" { // §16 allows it, so a parser that refused would be refusing conformant // packets. All four spellings of 1: for ([_][]const u8{ &.{0x01}, &.{ 0x40, 0x01 }, &.{ 0x80, 0x00, 0x00, 0x01 }, &.{ 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }, }) |bytes| { const got = try parse(bytes); try testing.expectEqual(@as(u64, 1), got.value); try testing.expectEqual(bytes.len, got.len); } } test "a reserved length field can be filled in afterwards" { // The pattern a packet writer uses: leave two octets for a length nobody // knows yet, write the payload, then come back. var buf: [2]u8 = undefined; const written = writeFixed(&buf, 37, 2); try testing.expectEqualSlices(u8, &.{ 0x40, 0x25 }, written); const got = try parse(written); try testing.expectEqual(@as(u64, 37), got.value); try testing.expectEqual(@as(usize, 2), got.len); } test "an encoding that has not all arrived is truncated, not wrong" { try testing.expectError(error.Truncated, parse(&.{})); try testing.expectError(error.Truncated, parse(&.{0x40})); try testing.expectError(error.Truncated, parse(&.{ 0x80, 0x00 })); try testing.expectError(error.Truncated, parse(&.{ 0xc0, 0, 0, 0, 0, 0, 0 })); }