blob: 7116853e77dc091dfeb71944b6272fda5a895cc6 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/third_party/quiche/src/quic/core/quic_data_writer.h"
6
7#include <algorithm>
8#include <limits>
9
10#include "net/third_party/quiche/src/quic/core/crypto/quic_random.h"
danzh4fbea5d2019-03-20 10:31:44 -070011#include "net/third_party/quiche/src/quic/core/quic_constants.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050012#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
13#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
14#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"
15
16namespace quic {
17
18QuicDataWriter::QuicDataWriter(size_t size, char* buffer)
19 : QuicDataWriter(size, buffer, NETWORK_BYTE_ORDER) {}
20
21QuicDataWriter::QuicDataWriter(size_t size, char* buffer, Endianness endianness)
22 : buffer_(buffer), capacity_(size), length_(0), endianness_(endianness) {}
23
24QuicDataWriter::~QuicDataWriter() {}
25
26char* QuicDataWriter::data() {
27 return buffer_;
28}
29
30bool QuicDataWriter::WriteUInt8(uint8_t value) {
31 return WriteBytes(&value, sizeof(value));
32}
33
34bool QuicDataWriter::WriteUInt16(uint16_t value) {
35 if (endianness_ == NETWORK_BYTE_ORDER) {
36 value = QuicEndian::HostToNet16(value);
37 }
38 return WriteBytes(&value, sizeof(value));
39}
40
41bool QuicDataWriter::WriteUInt32(uint32_t value) {
42 if (endianness_ == NETWORK_BYTE_ORDER) {
43 value = QuicEndian::HostToNet32(value);
44 }
45 return WriteBytes(&value, sizeof(value));
46}
47
48bool QuicDataWriter::WriteUInt64(uint64_t value) {
49 if (endianness_ == NETWORK_BYTE_ORDER) {
50 value = QuicEndian::HostToNet64(value);
51 }
52 return WriteBytes(&value, sizeof(value));
53}
54
55bool QuicDataWriter::WriteBytesToUInt64(size_t num_bytes, uint64_t value) {
56 if (num_bytes > sizeof(value)) {
57 return false;
58 }
59 if (endianness_ == HOST_BYTE_ORDER) {
60 return WriteBytes(&value, num_bytes);
61 }
62
63 value = QuicEndian::HostToNet64(value);
64 return WriteBytes(reinterpret_cast<char*>(&value) + sizeof(value) - num_bytes,
65 num_bytes);
66}
67
68bool QuicDataWriter::WriteUFloat16(uint64_t value) {
69 uint16_t result;
70 if (value < (UINT64_C(1) << kUFloat16MantissaEffectiveBits)) {
71 // Fast path: either the value is denormalized, or has exponent zero.
72 // Both cases are represented by the value itself.
73 result = static_cast<uint16_t>(value);
74 } else if (value >= kUFloat16MaxValue) {
75 // Value is out of range; clamp it to the maximum representable.
76 result = std::numeric_limits<uint16_t>::max();
77 } else {
78 // The highest bit is between position 13 and 42 (zero-based), which
79 // corresponds to exponent 1-30. In the output, mantissa is from 0 to 10,
80 // hidden bit is 11 and exponent is 11 to 15. Shift the highest bit to 11
81 // and count the shifts.
82 uint16_t exponent = 0;
83 for (uint16_t offset = 16; offset > 0; offset /= 2) {
84 // Right-shift the value until the highest bit is in position 11.
85 // For offset of 16, 8, 4, 2 and 1 (binary search over 1-30),
86 // shift if the bit is at or above 11 + offset.
87 if (value >= (UINT64_C(1) << (kUFloat16MantissaBits + offset))) {
88 exponent += offset;
89 value >>= offset;
90 }
91 }
92
93 DCHECK_GE(exponent, 1);
94 DCHECK_LE(exponent, kUFloat16MaxExponent);
95 DCHECK_GE(value, UINT64_C(1) << kUFloat16MantissaBits);
96 DCHECK_LT(value, UINT64_C(1) << kUFloat16MantissaEffectiveBits);
97
98 // Hidden bit (position 11) is set. We should remove it and increment the
99 // exponent. Equivalently, we just add it to the exponent.
100 // This hides the bit.
101 result = static_cast<uint16_t>(value + (exponent << kUFloat16MantissaBits));
102 }
103
104 if (endianness_ == NETWORK_BYTE_ORDER) {
105 result = QuicEndian::HostToNet16(result);
106 }
107 return WriteBytes(&result, sizeof(result));
108}
109
110bool QuicDataWriter::WriteStringPiece16(QuicStringPiece val) {
111 if (val.size() > std::numeric_limits<uint16_t>::max()) {
112 return false;
113 }
114 if (!WriteUInt16(static_cast<uint16_t>(val.size()))) {
115 return false;
116 }
117 return WriteBytes(val.data(), val.size());
118}
119
120bool QuicDataWriter::WriteStringPiece(QuicStringPiece val) {
121 return WriteBytes(val.data(), val.size());
122}
123
124char* QuicDataWriter::BeginWrite(size_t length) {
125 if (length_ > capacity_) {
126 return nullptr;
127 }
128
129 if (capacity_ - length_ < length) {
130 return nullptr;
131 }
132
133#ifdef ARCH_CPU_64_BITS
134 DCHECK_LE(length, std::numeric_limits<uint32_t>::max());
135#endif
136
137 return buffer_ + length_;
138}
139
140bool QuicDataWriter::WriteBytes(const void* data, size_t data_len) {
141 char* dest = BeginWrite(data_len);
142 if (!dest) {
143 return false;
144 }
145
146 memcpy(dest, data, data_len);
147
148 length_ += data_len;
149 return true;
150}
151
152bool QuicDataWriter::WriteRepeatedByte(uint8_t byte, size_t count) {
153 char* dest = BeginWrite(count);
154 if (!dest) {
155 return false;
156 }
157
158 memset(dest, byte, count);
159
160 length_ += count;
161 return true;
162}
163
164void QuicDataWriter::WritePadding() {
165 DCHECK_LE(length_, capacity_);
166 if (length_ > capacity_) {
167 return;
168 }
169 memset(buffer_ + length_, 0x00, capacity_ - length_);
170 length_ = capacity_;
171}
172
173bool QuicDataWriter::WritePaddingBytes(size_t count) {
174 return WriteRepeatedByte(0x00, count);
175}
176
177bool QuicDataWriter::WriteConnectionId(QuicConnectionId connection_id) {
178 if (connection_id.IsEmpty()) {
179 return true;
180 }
181 return WriteBytes(connection_id.data(), connection_id.length());
182}
183
184bool QuicDataWriter::WriteTag(uint32_t tag) {
185 return WriteBytes(&tag, sizeof(tag));
186}
187
188bool QuicDataWriter::WriteRandomBytes(QuicRandom* random, size_t length) {
189 char* dest = BeginWrite(length);
190 if (!dest) {
191 return false;
192 }
193
194 random->RandBytes(dest, length);
195 length_ += length;
196 return true;
197}
198
199// Converts a uint64_t into an IETF/Quic formatted Variable Length
200// Integer. IETF Variable Length Integers have 62 significant bits, so
201// the value to write must be in the range of 0..(2^62)-1.
202//
203// Performance notes
204//
205// Measurements and experiments showed that unrolling the four cases
206// like this and dereferencing next_ as we do (*(next_+n)) gains about
207// 10% over making a loop and dereferencing it as *(next_++)
208//
209// Using a register for next didn't help.
210//
211// Branches are ordered to increase the likelihood of the first being
212// taken.
213//
214// Low-level optimization is useful here because this function will be
215// called frequently, leading to outsize benefits.
216bool QuicDataWriter::WriteVarInt62(uint64_t value) {
217 DCHECK_EQ(endianness_, NETWORK_BYTE_ORDER);
218
219 size_t remaining = capacity_ - length_;
220 char* next = buffer_ + length_;
221
222 if ((value & kVarInt62ErrorMask) == 0) {
223 // We know the high 2 bits are 0 so |value| is legal.
224 // We can do the encoding.
225 if ((value & kVarInt62Mask8Bytes) != 0) {
226 // Someplace in the high-4 bytes is a 1-bit. Do an 8-byte
227 // encoding.
228 if (remaining >= 8) {
229 *(next + 0) = ((value >> 56) & 0x3f) + 0xc0;
230 *(next + 1) = (value >> 48) & 0xff;
231 *(next + 2) = (value >> 40) & 0xff;
232 *(next + 3) = (value >> 32) & 0xff;
233 *(next + 4) = (value >> 24) & 0xff;
234 *(next + 5) = (value >> 16) & 0xff;
235 *(next + 6) = (value >> 8) & 0xff;
236 *(next + 7) = value & 0xff;
237 length_ += 8;
238 return true;
239 }
240 return false;
241 }
242 // The high-order-4 bytes are all 0, check for a 1, 2, or 4-byte
243 // encoding
244 if ((value & kVarInt62Mask4Bytes) != 0) {
245 // The encoding will not fit into 2 bytes, Do a 4-byte
246 // encoding.
247 if (remaining >= 4) {
248 *(next + 0) = ((value >> 24) & 0x3f) + 0x80;
249 *(next + 1) = (value >> 16) & 0xff;
250 *(next + 2) = (value >> 8) & 0xff;
251 *(next + 3) = value & 0xff;
252 length_ += 4;
253 return true;
254 }
255 return false;
256 }
257 // The high-order bits are all 0. Check to see if the number
258 // can be encoded as one or two bytes. One byte encoding has
259 // only 6 significant bits (bits 0xffffffff ffffffc0 are all 0).
260 // Two byte encoding has more than 6, but 14 or less significant
261 // bits (bits 0xffffffff ffffc000 are 0 and 0x00000000 00003fc0
262 // are not 0)
263 if ((value & kVarInt62Mask2Bytes) != 0) {
264 // Do 2-byte encoding
265 if (remaining >= 2) {
266 *(next + 0) = ((value >> 8) & 0x3f) + 0x40;
267 *(next + 1) = (value)&0xff;
268 length_ += 2;
269 return true;
270 }
271 return false;
272 }
273 if (remaining >= 1) {
274 // Do 1-byte encoding
275 *next = (value & 0x3f);
276 length_ += 1;
277 return true;
278 }
279 return false;
280 }
281 // Can not encode, high 2 bits not 0
282 return false;
283}
284
285bool QuicDataWriter::WriteVarInt62(
286 uint64_t value,
287 QuicVariableLengthIntegerLength write_length) {
288 DCHECK_EQ(endianness_, NETWORK_BYTE_ORDER);
289
290 size_t remaining = capacity_ - length_;
291 if (remaining < write_length) {
292 return false;
293 }
294
295 const QuicVariableLengthIntegerLength min_length = GetVarInt62Len(value);
296 if (write_length < min_length) {
297 QUIC_BUG << "Cannot write value " << value << " with write_length "
298 << write_length;
299 return false;
300 }
301 if (write_length == min_length) {
302 return WriteVarInt62(value);
303 }
304
305 if (write_length == VARIABLE_LENGTH_INTEGER_LENGTH_2) {
306 return WriteUInt8(0b01000000) && WriteUInt8(value);
307 }
308 if (write_length == VARIABLE_LENGTH_INTEGER_LENGTH_4) {
309 return WriteUInt8(0b10000000) && WriteUInt8(0) && WriteUInt16(value);
310 }
311 if (write_length == VARIABLE_LENGTH_INTEGER_LENGTH_8) {
312 return WriteUInt8(0b11000000) && WriteUInt8(0) && WriteUInt16(0) &&
313 WriteUInt32(value);
314 }
315
316 QUIC_BUG << "Invalid write_length " << static_cast<int>(write_length);
317 return false;
318}
319
320// static
321QuicVariableLengthIntegerLength QuicDataWriter::GetVarInt62Len(uint64_t value) {
322 if ((value & kVarInt62ErrorMask) != 0) {
323 QUIC_BUG << "Attempted to encode a value, " << value
324 << ", that is too big for VarInt62";
325 return VARIABLE_LENGTH_INTEGER_LENGTH_0;
326 }
327 if ((value & kVarInt62Mask8Bytes) != 0) {
328 return VARIABLE_LENGTH_INTEGER_LENGTH_8;
329 }
330 if ((value & kVarInt62Mask4Bytes) != 0) {
331 return VARIABLE_LENGTH_INTEGER_LENGTH_4;
332 }
333 if ((value & kVarInt62Mask2Bytes) != 0) {
334 return VARIABLE_LENGTH_INTEGER_LENGTH_2;
335 }
336 return VARIABLE_LENGTH_INTEGER_LENGTH_1;
337}
338
339bool QuicDataWriter::WriteStringPieceVarInt62(
340 const QuicStringPiece& string_piece) {
341 if (!WriteVarInt62(string_piece.size())) {
342 return false;
343 }
344 if (!string_piece.empty()) {
345 if (!WriteBytes(string_piece.data(), string_piece.size())) {
346 return false;
347 }
348 }
349 return true;
350}
351
vasilvvc48c8712019-03-11 13:38:16 -0700352std::string QuicDataWriter::DebugString() const {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500353 return QuicStrCat(" { capacity: ", capacity_, ", length: ", length_, " }");
354}
355
356} // namespace quic