defined varint functions

This commit is contained in:
2026-12-01 15:35:56 +01:00
parent 1a165752c9
commit 35f902c6a2
2 changed files with 58 additions and 0 deletions
+2
View File
@@ -45,7 +45,9 @@ typedef struct {
bool bravais_packet_type_is_handshake(bravais_packet_type_t type); // true for INIT and RESPONSE 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 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 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); 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 #endif // BRAVAIS_PACKET_H
+56
View File
@@ -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;
}
}