Class: Cabriolet::HLP::QuickHelp::HuffmanDecoder

Inherits:
Object
  • Object
show all
Defined in:
lib/cabriolet/hlp/quickhelp/huffman_tree.rb

Overview

Decoder for Huffman-encoded data

Usage:

decoder = tree.create_decoder
while !decoder.has_value?
  decoder.push(bitstream.read_bit)
end
symbol = decoder.value

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tree) ⇒ HuffmanDecoder

Initialize decoder

Parameters:



127
128
129
130
# File 'lib/cabriolet/hlp/quickhelp/huffman_tree.rb', line 127

def initialize(tree)
  @tree = tree
  @current_node = tree.root
end

Instance Attribute Details

#current_nodeObject (readonly)

Returns the value of attribute current_node.



122
123
124
# File 'lib/cabriolet/hlp/quickhelp/huffman_tree.rb', line 122

def current_node
  @current_node
end

Instance Method Details

#has_value?Boolean

Check if decoder has decoded a complete symbol

Returns:

  • (Boolean)

    true if value is ready



135
136
137
# File 'lib/cabriolet/hlp/quickhelp/huffman_tree.rb', line 135

def has_value?
  !@current_node.nil? && @current_node.leaf?
end

#push(bit) ⇒ Object

Push a bit into the decoder

Parameters:

  • bit (Boolean, Integer)

    Bit value (true/1 for right, false/0 for left)

Raises:

  • (RuntimeError)

    if tree is empty or at leaf



153
154
155
156
157
158
# File 'lib/cabriolet/hlp/quickhelp/huffman_tree.rb', line 153

def push(bit)
  raise "Cannot walk an empty tree" if @current_node.nil?
  raise "Cannot walk further from a leaf" if @current_node.leaf?

  @current_node = bit ? @current_node.right_child : @current_node.left_child
end

#resetObject

Reset decoder to tree root



161
162
163
# File 'lib/cabriolet/hlp/quickhelp/huffman_tree.rb', line 161

def reset
  @current_node = @tree.root
end

#valueInteger

Get decoded symbol value

Returns:

  • (Integer)

    Symbol value (0-255)

Raises:

  • (RuntimeError)

    if no value is ready



143
144
145
146
147
# File 'lib/cabriolet/hlp/quickhelp/huffman_tree.rb', line 143

def value
  raise "Decoder does not have a value" unless has_value?

  @current_node.symbol
end