1 // Copyright 2014 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.
5 #include "net/spdy/hpack_output_stream.h"
7 #include "base/logging.h"
9 using base::StringPiece;
15 HpackOutputStream::HpackOutputStream(uint32 max_string_literal_size)
16 : max_string_literal_size_(max_string_literal_size),
19 HpackOutputStream::~HpackOutputStream() {}
21 void HpackOutputStream::AppendIndexedHeader(uint32 index_or_zero) {
22 AppendPrefix(kIndexedOpcode);
23 AppendUint32(index_or_zero);
26 bool HpackOutputStream::AppendLiteralHeaderNoIndexingWithName(
27 StringPiece name, StringPiece value) {
28 AppendPrefix(kLiteralNoIndexOpcode);
29 AppendBits(0x0, 8 - kLiteralNoIndexOpcode.bit_size);
30 if (!AppendStringLiteral(name))
32 if (!AppendStringLiteral(value))
37 void HpackOutputStream::TakeString(string* output) {
38 // This must hold, since all public functions cause the buffer to
39 // end on a byte boundary.
40 DCHECK_EQ(bit_offset_, 0u);
41 buffer_.swap(*output);
46 void HpackOutputStream::AppendBits(uint8 bits, size_t bit_size) {
47 DCHECK_GT(bit_size, 0u);
48 DCHECK_LE(bit_size, 8u);
49 DCHECK_EQ(bits >> bit_size, 0);
50 size_t new_bit_offset = bit_offset_ + bit_size;
51 if (bit_offset_ == 0) {
52 // Buffer ends on a byte boundary.
53 DCHECK_LE(bit_size, 8u);
54 buffer_.append(1, bits << (8 - bit_size));
55 } else if (new_bit_offset <= 8) {
56 // Buffer does not end on a byte boundary but the given bits fit
57 // in the remainder of the last byte.
58 *buffer_.rbegin() |= bits << (8 - new_bit_offset);
60 // Buffer does not end on a byte boundary and the given bits do
61 // not fit in the remainder of the last byte.
62 *buffer_.rbegin() |= bits >> (new_bit_offset - 8);
63 buffer_.append(1, bits << (16 - new_bit_offset));
65 bit_offset_ = new_bit_offset % 8;
68 void HpackOutputStream::AppendPrefix(HpackPrefix prefix) {
69 AppendBits(prefix.bits, prefix.bit_size);
72 void HpackOutputStream::AppendUint32(uint32 I) {
73 // The algorithm below is adapted from the pseudocode in 4.1.1.
74 size_t N = 8 - bit_offset_;
75 uint8 max_first_byte = static_cast<uint8>((1 << N) - 1);
76 if (I < max_first_byte) {
77 AppendBits(static_cast<uint8>(I), N);
79 AppendBits(max_first_byte, N);
81 while ((I & ~0x7f) != 0) {
82 buffer_.append(1, (I & 0x7f) | 0x80);
85 AppendBits(static_cast<uint8>(I), 8);
89 bool HpackOutputStream::AppendStringLiteral(base::StringPiece str) {
90 DCHECK_EQ(bit_offset_, 0u);
91 // TODO(akalin): Implement Huffman encoding.
92 AppendPrefix(kStringLiteralIdentityEncoded);
93 if (str.size() > max_string_literal_size_)
95 AppendUint32(static_cast<uint32>(str.size()));
96 buffer_.append(str.data(), str.size());