Appendix A. Pseudocode
Appendix A. Pseudocode
This appendix provides pseudocode for selected functions referenced throughout this document.
A.1 Sample Variable-Length Integer Decoding
uint64_t DecodeVariableLengthInteger(const uint8_t *data) {
uint64_t v = data[0];
uint8_t prefix = v >> 6;
uint8_t length = 1 << prefix;
v = v & 0x3f;
while (--length > 0) {
v = (v << 8) | *++data;
}
return v;
}
A.2 Sample Packet Number Encoding Algorithm
EncodePacketNumber(uint64_t full_pn, uint64_t largest_acked) {
// The number of bits must be at least one more
// than the base-2 logarithm of the number of contiguous
// unacknowledged packet numbers, including the new packet.
uint64_t num_unacked = full_pn - largest_acked;
uint8_t min_bits = log2(num_unacked) + 1;
uint8_t num_bytes = (min_bits + 7) / 8;
return TruncatePacketNumber(full_pn, num_bytes);
}
A.3 Sample Packet Number Decoding Algorithm
DecodePacketNumber(uint64_t largest_pn, uint64_t truncated_pn,
uint8_t pn_nbits) {
uint64_t expected_pn = largest_pn + 1;
uint64_t pn_win = 1ULL << pn_nbits;
uint64_t pn_hwin = pn_win / 2;
uint64_t pn_mask = pn_win - 1;
// The incoming packet number should be greater than
// expected_pn - pn_hwin and less than or equal to
// expected_pn + pn_hwin
uint64_t candidate_pn = (expected_pn & ~pn_mask) | truncated_pn;
if (candidate_pn <= expected_pn - pn_hwin &&
candidate_pn < (1ULL << 62) - pn_win) {
return candidate_pn + pn_win;
}
if (candidate_pn > expected_pn + pn_hwin &&
candidate_pn >= pn_win) {
return candidate_pn - pn_win;
}
return candidate_pn;
}
A.4 Sample ECN Validation Algorithm
ValidateECNCounts(newest_acked, ECT0_increase,
ECT1_increase, CE_increase) {
if (ECT0_increase + ECT1_increase + CE_increase <
newly_acked_bytes) {
// ECN validation failed
DisableECN();
}
}