class Protocol::HPACK::Huffman
Implementation of huffman encoding for HPACK
.
Constants
- BITS_AT_ONCE
- CODES
Huffman
table as specified in tools.ietf.org/html/rfc7541#appendix-B- ENCODE_TABLE
- EOS
Public Instance Methods
decode(buffer)
click to toggle source
Decodes provided Huffman
coded string.
@param buf [Buffer] @return [String] binary string @raise [CompressionError] when Huffman
coded string is malformed
# File lib/protocol/hpack/huffman.rb, line 50 def decode(buffer) emit = String.new.b state = 0 # start state mask = (1 << BITS_AT_ONCE) - 1 buffer.each_byte do |c| (8 / BITS_AT_ONCE - 1).downto(0) do |shift| branch = (c >> (shift * BITS_AT_ONCE)) & mask # MACHINE[state] = [final, [transitions]] # [final] unfinished bits so far are prefix of the EOS code. # Each transition is [emit, next] # [emit] character to be emitted on this transition, empty string, or EOS. # [next] next state number. value, state = MACHINE[state][branch] raise CompressionError, 'Huffman decode error (EOS found)' if value == EOS emit << value.chr if value end end # Check whether partial input is correctly filled unless state <= MAX_FINAL_STATE raise CompressionError, 'Huffman decode error (EOS invalid)' end emit.force_encoding(Encoding::BINARY) end
encode(str)
click to toggle source
Encodes provided value via huffman encoding. Length is not encoded in this method.
@param str [String] @return [String] binary string
# File lib/protocol/hpack/huffman.rb, line 39 def encode(str) bitstring = str.each_byte.map {|chr| ENCODE_TABLE[chr]}.join bitstring << '1' * ((8 - bitstring.size) % 8) [bitstring].pack('B*') end