proxygen
Huffman.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2015-present, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree. An additional grant
7  * of patent rights can be found in the PATENTS file in the same directory.
8  *
9  */
10 #pragma once
11 
12 #include <folly/FBString.h>
13 #include <folly/io/Cursor.h>
14 #include <folly/io/IOBuf.h>
16 #include <string>
17 
18 namespace proxygen { namespace huffman {
19 
20 // size of the huffman tables (codes and bits)
21 const uint32_t kTableSize = 256;
22 
23 // not used explicitly, since the prefixes are all 1's and they are
24 // used only for padding of up to 7 bits
25 const uint32_t kEOSHpack = 0x3fffffff;
26 
32 struct HuffNode {
33  union {
34  uint8_t ch; // leafs hold characters
36  } data{0};
37  struct {
38  uint8_t bits:4; // how many bits are used for representing ch, range is 0-8
39  bool isSuperNode:1;
40  } metadata{0,false};
41 
42  bool isLeaf() const {
43  return !metadata.isSuperNode;
44  }
45 };
46 
50 struct SuperHuffNode {
51  HuffNode index[256];
52 };
53 
84 class HuffTree {
85  public:
90  explicit HuffTree(const uint32_t* codes, const uint8_t* bits);
91  explicit HuffTree(HuffTree&& tree) = default;
92  ~HuffTree() {}
93 
103  bool decode(const uint8_t* buf, uint32_t size,
104  folly::fbstring& literal) const;
105 
113  folly::io::QueueAppender& buf) const;
114 
122  uint32_t getEncodeSize(folly::StringPiece literal) const;
123 
134  std::pair<uint32_t, uint8_t> getCode(uint8_t ch) const;
135 
136  // get internal tables for codes and bit lengths, useful for testing
137  const uint32_t* codesTable() const;
138  const uint8_t* bitsTable() const;
139 
140  private:
141  void fillIndex(SuperHuffNode& snode, uint32_t code, uint8_t bits, uint8_t ch,
142  uint8_t level);
143  void buildTree();
144  void insert(uint32_t code, uint8_t bits, uint8_t ch);
145 
146  uint32_t nodes_{0};
147  const uint32_t* codes_;
148  const uint8_t* bits_;
149 
150  protected:
151  explicit HuffTree(const HuffTree& tree);
152  SuperHuffNode table_[46];
153 };
154 
155 const HuffTree& huffTree();
156 
157 }}
unique_ptr< IOBuf > encode(vector< HPACKHeader > &headers, HPACKEncoder &encoder)
const uint32_t kEOSHpack
Definition: Huffman.h:25
const uint8_t * bits_
Definition: Huffman.h:148
TokenBindingMessage decode(folly::io::Cursor &cursor)
Definition: Types.cpp:132
struct proxygen::huffman::HuffNode::@104 metadata
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
union proxygen::huffman::HuffNode::@103 data
bool isLeaf() const
Definition: Huffman.h:42
const uint32_t * codes_
Definition: Huffman.h:147
const HuffTree & huffTree()
Definition: Huffman.cpp:252
const uint32_t kTableSize
Definition: Huffman.h:21