lib/http/2/huffman.rb in http-2-0.11.0 vs lib/http/2/huffman.rb in http-2-0.12.0
- old
+ new
@@ -1,5 +1,7 @@
+# frozen_string_literal: true
+
require_relative 'error'
module HTTP2
# Implementation of huffman encoding for HPACK
#
@@ -18,42 +20,42 @@
#
# @param str [String]
# @return [String] binary string
def encode(str)
bitstring = str.each_byte.map { |chr| ENCODE_TABLE[chr] }.join
- bitstring << '1' * ((8 - bitstring.size) % 8)
+ bitstring << ('1' * ((8 - bitstring.size) % 8))
[bitstring].pack('B*')
end
# Decodes provided Huffman coded string.
#
# @param buf [Buffer]
# @return [String] binary string
# @raise [CompressionError] when Huffman coded string is malformed
def decode(buf)
- emit = ''
+ emit = String.new
state = 0 # start state
mask = (1 << BITS_AT_ONCE) - 1
buf.each_byte do |chr|
- (8 / BITS_AT_ONCE - 1).downto(0) do |shift|
+ ((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]
- fail CompressionError, 'Huffman decode error (EOS found)' if trans.first == EOS
+ 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
- fail CompressionError, 'Huffman decode error (EOS invalid)'
- end
+ raise CompressionError, 'Huffman decode error (EOS invalid)' unless state <= MAX_FINAL_STATE
+
emit.force_encoding(Encoding::BINARY)
end
# Huffman table as specified in
# - http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-10#appendix-B
@@ -151,27 +153,27 @@
[0xfd, 8],
[0x1ffb, 13],
[0x7fff0, 19],
[0x1ffc, 13],
[0x3ffc, 14],
- [0x22, 6],
+ [0x22, 6],
[0x7ffd, 15],
- [0x3, 5],
- [0x23, 6],
- [0x4, 5],
- [0x24, 6],
- [0x5, 5],
+ [0x3, 5],
+ [0x23, 6],
+ [0x4, 5],
+ [0x24, 6],
+ [0x5, 5],
[0x25, 6],
[0x26, 6],
[0x27, 6],
- [0x6, 5],
+ [0x6, 5],
[0x74, 7],
[0x75, 7],
[0x28, 6],
[0x29, 6],
[0x2a, 6],
- [0x7, 5],
+ [0x7, 5],
[0x2b, 6],
[0x76, 7],
[0x2c, 6],
[0x8, 5],
[0x9, 5],
@@ -312,12 +314,12 @@
[0x7ffffed, 27],
[0x7ffffee, 27],
[0x7ffffef, 27],
[0x7fffff0, 27],
[0x3ffffee, 26],
- [0x3fffffff, 30],
+ [0x3fffffff, 30]
].each(&:freeze).freeze
- ENCODE_TABLE = CODES.map { |c, l| [c].pack('N').unpack('B*').first[-l..-1] }.each(&:freeze).freeze
+ ENCODE_TABLE = CODES.map { |c, l| [c].pack('N').unpack1('B*')[-l..-1] }.each(&:freeze).freeze
end
end
end