From 35f902c6a2b2051e13ac4028d2351f9a54eee303 Mon Sep 17 00:00:00 2001 From: DcruBro Date: Tue, 1 Dec 2026 15:35:56 +0100 Subject: [PATCH] defined varint functions --- src/wire/packet.h | 2 ++ src/wire/varint.c | 56 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 src/wire/varint.c diff --git a/src/wire/packet.h b/src/wire/packet.h index 42cd2c1..d9ec33b 100644 --- a/src/wire/packet.h +++ b/src/wire/packet.h @@ -45,7 +45,9 @@ typedef struct { bool bravais_packet_type_is_handshake(bravais_packet_type_t type); // true for INIT and RESPONSE size_t bravais_packet_header_length_raw(bravais_packet_type_t type); // 0 is an invalid type +// Parse one raw-mode datagram bravais_result_t bravais_packet_parse_raw(const uint8_t* data, size_t dataLen, bravais_packet_t* outPacket); // zeroes on failure +// Write a raw-mode header for the packet's type (caller must write payload) bravais_result_t bravais_packet_write_header_raw(const bravais_packet_t* packet, uint8_t* out, size_t outCap, size_t* outLen); #endif // BRAVAIS_PACKET_H diff --git a/src/wire/varint.c b/src/wire/varint.c new file mode 100644 index 0000000..3c785d5 --- /dev/null +++ b/src/wire/varint.c @@ -0,0 +1,56 @@ +// varint.c +// Implement QUIC variable-length integers, according to RFC 9000 Section 16 + +#include "wire/varint.h" + +size_t bravais_varint_len(uint64_t val) { + if (val <= 0x3F) { + return 1; + } else if (val <= 0x3FFF) { + return 2; + } else if (val <= 0x3FFFFFFF) { + return 4; + } else if (val <= BRAVAIS_VARINT_MAX) { + return 8; + } else { + return 0; // too large to encode + } +} + +uint64_t bravais_rcur_varint(bravais_rcur_t* buf) { + uint8_t firstByte = bravais_rcur_u8(buf); + if (!bravais_rcur_ok(buf)) { return 0; } + + // the top two bits of the first byte indicate the length of the integer in bytes (cue cursed bitwise operations) + size_t len = (size_t)1 << (firstByte >> 6); + uint64_t val = firstByte & 0x3F; // the remaining bits + + for (size_t i = 1; i < len; i++) { + val = (val << 8) | bravais_rcur_u8(buf); + } + + if (!bravais_rcur_ok(buf)) { return 0; } // ran out mid-varint + + return val; +} + +// Always uses the shortest encoding. Fails the cursor if value is too large. +void bravais_wcur_varint(bravais_wcur_t* cur, uint64_t val) { + switch (bravais_varint_len(val)) { + case 1: + bravais_wcur_u8(cur, (uint8_t)val); + break; + case 2: + bravais_wcur_u16(cur, (uint16_t)(val | UINT64_C(0x4000))); + break; + case 4: + bravais_wcur_u32(cur, (uint32_t)(val | UINT64_C(0x80000000))); + break; + case 8: + bravais_wcur_u64(cur, val | UINT64_C(0xC000000000000000)); + break; + default: + cur->failed = true; // too large to encode + break; + } +}