writeVarInt function
Implementation
Uint8List writeVarInt(int value) {
if (value < 0x40) {
// 1 byte (00 prefix)
return Uint8List.fromList([value]);
}
if (value < 0x4000) {
// 2 bytes (01 prefix)
return Uint8List.fromList([0x40 | (value >> 8) & 0x3F, value & 0xFF]);
}
if (value < 0x40000000) {
// 4 bytes (10 prefix)
// Dart integers are 64-bit, so this is safe.
return Uint8List.fromList([
0x80 | (value >> 24) & 0x3F,
(value >> 16) & 0xFF,
(value >> 8) & 0xFF,
value & 0xFF,
]);
}
// For 8-byte (11 prefix), you must handle the full 62 bits:
if (value < 0x4000000000000000) {
// Use ByteData to ensure correct 64-bit little-endian writing.
final buffer = ByteData(8);
buffer.setUint64(0, value, Endian.big); // Write 64-bit value
// Dart integers up to 2^63 - 1 are safe.
return Uint8List.fromList([
0xC0 | (buffer.getUint8(0) & 0x3F),
buffer.getUint8(1),
buffer.getUint8(2),
buffer.getUint8(3),
buffer.getUint8(4),
buffer.getUint8(5),
buffer.getUint8(6),
buffer.getUint8(7),
]);
}
throw Exception("Value too large for QUIC VarInt");
}