class Protocol::HPACK::Huffman

def decode(buf)

Raises:
  • (CompressionError) - when Huffman coded string is malformed

Returns:
  • (String) - binary string

Parameters:
  • buf (Buffer) --
def decode(buf)
	emit = ''
	state = 0 # start state
	mask = (1 << BITS_AT_ONCE) - 1
	buf.each_byte do |chr|
		(8 / BITS_AT_ONCE - 1).downto(0) do |shift|
			branch = (chr >> (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.
			trans = MACHINE[state][branch]
			raise CompressionError, 'Huffman decode error (EOS found)' if trans.first == EOS
			emit << trans.first.chr if trans.first
			state = trans.last
		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

def encode(str)

Returns:
  • (String) - binary string

Parameters:
  • str (String) --
def encode(str)
	bitstring = str.each_byte.map {|chr| ENCODE_TABLE[chr]}.join
	bitstring << '1' * ((8 - bitstring.size) % 8)
	[bitstring].pack('B*')
end