1// 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#ifndef NET_QUIC_QUIC_DATA_WRITER_H_ 6#define NET_QUIC_QUIC_DATA_WRITER_H_ 7 8#include <string> 9 10#include "base/basictypes.h" 11#include "base/logging.h" 12#include "base/port.h" 13#include "base/strings/string_piece.h" 14#include "net/base/int128.h" 15#include "net/base/net_export.h" 16#include "net/quic/quic_protocol.h" 17 18namespace net { 19 20// This class provides facilities for packing QUIC data. 21// 22// The QuicDataWriter supports appending primitive values (int, string, etc) 23// to a frame instance. The QuicDataWriter grows its internal memory buffer 24// dynamically to hold the sequence of primitive values. The internal memory 25// buffer is exposed as the "data" of the QuicDataWriter. 26class NET_EXPORT_PRIVATE QuicDataWriter { 27 public: 28 explicit QuicDataWriter(size_t length); 29 30 ~QuicDataWriter(); 31 32 // Returns the size of the QuicDataWriter's data. 33 size_t length() const { return length_; } 34 35 // Takes the buffer from the QuicDataWriter. 36 char* take(); 37 38 // Methods for adding to the payload. These values are appended to the end 39 // of the QuicDataWriter payload. Note - binary integers are written in 40 // host byte order (little endian) not network byte order (big endian). 41 bool WriteUInt8(uint8 value); 42 bool WriteUInt16(uint16 value); 43 bool WriteUInt32(uint32 value); 44 bool WriteUInt48(uint64 value); 45 bool WriteUInt64(uint64 value); 46 bool WriteUInt128(uint128 value); 47 bool WriteStringPiece16(base::StringPiece val); 48 bool WriteBytes(const void* data, size_t data_len); 49 bool WriteRepeatedByte(uint8 byte, size_t count); 50 // Fills the remaining buffer with null characters. 51 void WritePadding(); 52 53 // Methods for editing the payload at a specific offset, where the 54 // offset must be within the writer's capacity. 55 // Return true if there is enough space at that offset, false otherwise. 56 bool WriteUInt8ToOffset(uint8 value, size_t offset); 57 bool WriteUInt32ToOffset(uint32 value, size_t offset); 58 bool WriteUInt48ToOffset(uint64 value, size_t offset); 59 60 size_t capacity() const { 61 return capacity_; 62 } 63 64 protected: 65 const char* end_of_payload() const { return buffer_ + length_; } 66 67 private: 68 // Returns the location that the data should be written at, or NULL if there 69 // is not enough room. Call EndWrite with the returned offset and the given 70 // length to pad out for the next write. 71 char* BeginWrite(size_t length); 72 73 char* buffer_; 74 size_t capacity_; // Allocation size of payload (or -1 if buffer is const). 75 size_t length_; // Current length of the buffer. 76}; 77 78} // namespace net 79 80#endif // NET_QUIC_QUIC_DATA_WRITER_H_ 81