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.
7 #include "net/spdy/spdy_frame_builder.h"
8 #include "net/spdy/spdy_protocol.h"
14 // Creates a FlagsAndLength.
15 FlagsAndLength
CreateFlagsAndLength(SpdyControlFlags flags
, size_t length
) {
16 DCHECK_EQ(0u, length
& ~static_cast<size_t>(kLengthMask
));
17 FlagsAndLength flags_length
;
18 flags_length
.length_
= htonl(static_cast<uint32
>(length
));
19 DCHECK_EQ(0, flags
& ~kControlFlagsMask
);
20 flags_length
.flags_
[0] = flags
;
26 SpdyFrameBuilder::SpdyFrameBuilder(size_t size
)
27 : buffer_(new char[size
]),
32 SpdyFrameBuilder::SpdyFrameBuilder(SpdyControlType type
,
33 SpdyControlFlags flags
,
36 : buffer_(new char[size
]),
39 FlagsAndLength flags_length
= CreateFlagsAndLength(
40 flags
, size
- SpdyFrame::kHeaderSize
);
41 WriteUInt16(kControlFlagMask
| spdy_version
);
43 WriteBytes(&flags_length
, sizeof(flags_length
));
46 SpdyFrameBuilder::SpdyFrameBuilder(SpdyStreamId stream_id
,
49 : buffer_(new char[size
]),
52 DCHECK_EQ(0u, stream_id
& ~kStreamIdMask
);
53 WriteUInt32(stream_id
);
54 size_t length
= size
- SpdyFrame::kHeaderSize
;
55 DCHECK_EQ(0u, length
& ~static_cast<size_t>(kLengthMask
));
56 FlagsAndLength flags_length
;
57 flags_length
.length_
= htonl(length
);
58 DCHECK_EQ(0, flags
& ~kDataFlagsMask
);
59 flags_length
.flags_
[0] = flags
;
60 WriteBytes(&flags_length
, sizeof(flags_length
));
63 SpdyFrameBuilder::~SpdyFrameBuilder() {
66 char* SpdyFrameBuilder::BeginWrite(size_t length
) {
67 size_t offset
= length_
;
68 size_t needed_size
= length_
+ length
;
69 if (needed_size
> capacity_
)
72 #ifdef ARCH_CPU_64_BITS
73 DCHECK_LE(length
, std::numeric_limits
<uint32
>::max());
76 return buffer_
.get() + offset
;
79 void SpdyFrameBuilder::EndWrite(char* dest
, int length
) {
82 bool SpdyFrameBuilder::WriteBytes(const void* data
, uint32 data_len
) {
83 if (data_len
> kLengthMask
) {
87 char* dest
= BeginWrite(data_len
);
91 memcpy(dest
, data
, data_len
);
93 EndWrite(dest
, data_len
);
98 bool SpdyFrameBuilder::WriteString(const std::string
& value
) {
99 if (value
.size() > 0xffff)
102 if (!WriteUInt16(static_cast<int>(value
.size())))
105 return WriteBytes(value
.data(), static_cast<uint16
>(value
.size()));
108 bool SpdyFrameBuilder::WriteStringPiece32(const base::StringPiece
& value
) {
109 if (!WriteUInt32(value
.size())) {
113 return WriteBytes(value
.data(), value
.size());