...
1
2
3
4
5
6
7 package quic
8
9
10
11
12
13 type packetNumber int64
14
15 const maxPacketNumber = 1<<62 - 1
16
17
18
19
20
21
22
23
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
40
41
42
43
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
58
59
60
61
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 }
75
View as plain text