golang.org/x/net@v0.25.1-0.20240516223405-c87a5b62e243/quic/packet_number.go (about) 1 // Copyright 2023 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build go1.21 6 7 package quic 8 9 // A packetNumber is a QUIC packet number. 10 // Packet numbers are integers in the range [0, 2^62-1]. 11 // 12 // https://www.rfc-editor.org/rfc/rfc9000.html#section-12.3 13 type packetNumber int64 14 15 const maxPacketNumber = 1<<62 - 1 // https://www.rfc-editor.org/rfc/rfc9000.html#section-17.1-1 16 17 // decodePacketNumber decodes a truncated packet number, given 18 // the largest acknowledged packet number in this number space, 19 // the truncated number received in a packet, and the size of the 20 // number received in bytes. 21 // 22 // https://www.rfc-editor.org/rfc/rfc9000.html#section-17.1 23 // https://www.rfc-editor.org/rfc/rfc9000.html#section-a.3 24 func decodePacketNumber(largest, truncated packetNumber, numLenInBytes int) packetNumber { 25 expected := largest + 1 26 win := packetNumber(1) << (uint(numLenInBytes) * 8) 27 hwin := win / 2 28 mask := win - 1 29 candidate := (expected &^ mask) | truncated 30 if candidate <= expected-hwin && candidate < (1<<62)-win { 31 return candidate + win 32 } 33 if candidate > expected+hwin && candidate >= win { 34 return candidate - win 35 } 36 return candidate 37 } 38 39 // appendPacketNumber appends an encoded packet number to b. 40 // The packet number must be larger than the largest acknowledged packet number. 41 // When no packets have been acknowledged yet, largestAck is -1. 42 // 43 // https://www.rfc-editor.org/rfc/rfc9000.html#section-17.1-5 44 func appendPacketNumber(b []byte, pnum, largestAck packetNumber) []byte { 45 switch packetNumberLength(pnum, largestAck) { 46 case 1: 47 return append(b, byte(pnum)) 48 case 2: 49 return append(b, byte(pnum>>8), byte(pnum)) 50 case 3: 51 return append(b, byte(pnum>>16), byte(pnum>>8), byte(pnum)) 52 default: 53 return append(b, byte(pnum>>24), byte(pnum>>16), byte(pnum>>8), byte(pnum)) 54 } 55 } 56 57 // packetNumberLength returns the minimum length, in bytes, needed to encode 58 // a packet number given the largest acknowledged packet number. 59 // The packet number must be larger than the largest acknowledged packet number. 60 // 61 // https://www.rfc-editor.org/rfc/rfc9000.html#section-17.1-5 62 func packetNumberLength(pnum, largestAck packetNumber) int { 63 d := pnum - largestAck 64 switch { 65 case d < 0x80: 66 return 1 67 case d < 0x8000: 68 return 2 69 case d < 0x800000: 70 return 3 71 default: 72 return 4 73 } 74 }