summaryrefslogtreecommitdiffstats
path: root/net/quic/quic_data_writer.h
blob: 0171e52c97ad7808e34095146cd3f0df8a36de17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef NET_QUIC_QUIC_DATA_WRITER_H_
#define NET_QUIC_QUIC_DATA_WRITER_H_

#include <string>

#include "base/basictypes.h"
#include "base/logging.h"
#include "base/port.h"
#include "base/string_piece.h"
#include "net/base/net_export.h"
#include "net/quic/quic_protocol.h"
#include "net/quic/uint128.h"

namespace net {

// This class provides facilities for packing QUIC data.
//
// The QuicDataWriter supports appending primitive values (int, string, etc)
// to a frame instance.  The QuicDataWriter grows its internal memory buffer
// dynamically to hold the sequence of primitive values.   The internal memory
// buffer is exposed as the "data" of the QuicDataWriter.
class NET_EXPORT_PRIVATE QuicDataWriter {
 public:
  explicit QuicDataWriter(size_t length);

  ~QuicDataWriter();

  // Returns the size of the QuicDataWriter's data.
  size_t length() const { return length_; }

  // Takes the buffer from the QuicDataWriter.
  char* take();

  // Methods for adding to the payload.  These values are appended to the end
  // of the QuicDataWriter payload. Note - binary integers are written in
  // host byte order (little endian) not network byte order (big endian).
  bool WriteUInt8(uint8 value);
  bool WriteUInt16(uint16 value);
  bool WriteUInt32(uint32 value);
  bool WriteUInt48(uint64 value);
  bool WriteUInt64(uint64 value);
  bool WriteUInt128(uint128 value);
  bool WriteStringPiece16(base::StringPiece val);
  bool WriteBytes(const void* data, uint32 data_len);

  static void WriteUint8ToBuffer(uint8 value, char* buffer);
  static void WriteUint16ToBuffer(uint16 value, char* buffer);
  static void WriteUint32ToBuffer(uint32 value, char* buffer);
  static void WriteUint48ToBuffer(uint64 value, char* buffer);
  static void WriteUint64ToBuffer(uint64 value, char* buffer);
  static void WriteUint128ToBuffer(uint128 value, char* buffer);

  size_t capacity() const {
    return capacity_;
  }

 protected:
  const char* end_of_payload() const { return buffer_ + length_; }

 private:
  // Returns the location that the data should be written at, or NULL if there
  // is not enough room. Call EndWrite with the returned offset and the given
  // length to pad out for the next write.
  char* BeginWrite(size_t length);

  char* buffer_;
  size_t capacity_;  // Allocation size of payload (or -1 if buffer is const).
  size_t length_;    // Current length of the buffer.
};

}  // namespace net

#endif  // NET_QUIC_QUIC_DATA_WRITER_H_