Module: Huffman

Extended by:
Huffman
Included in:
Huffman
Defined in:
lib/huffman.rb,
lib/huffman/log.rb,
lib/huffman/tree.rb,
lib/huffman/node.rb,
lib/huffman/version.rb,
lib/huffman/binary_stream.rb,
lib/huffman/letter_frequency.rb

Defined Under Namespace

Modules: BinaryStream, LetterFrequency Classes: Log, Node, Tree

Constant Summary collapse

EOT =

Caractère fin de transmission

3.chr
VERSION =
"0.0.1"

Instance Method Summary collapse

Instance Method Details

#decode_file(file_path, dictionnary_file_path) ⇒ Object


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/huffman.rb', line 54

def decode_file(file_path, dictionnary_file_path)
	dictionnary, bits_buffer, next_char_is_the_symbol = {}, '',false

	File.read(dictionnary_file_path).each_char do |c|
		if c == "\t" 
			next_char_is_the_symbol = true
		elsif next_char_is_the_symbol
			dictionnary[bits_buffer] = c
			bits_buffer.clear
			next_char_is_the_symbol = false
		else
			bits_buffer += c
		end
	end

	encoded_text = File.read(file_path).unpack("B*").join
	original_text = decode_text(encoded_text,dictionnary)
	File.open(file_path+"-back-to-original", 'wb' ){|f| f.write original_text }
	nil
end

#decode_text(encoded_text, dictionnary) ⇒ Object


31
32
33
# File 'lib/huffman.rb', line 31

def decode_text(encoded_text,dictionnary)
	BinaryStream.get_text_from_bits(encoded_text,dictionnary)
end

#encode_file(file_path, options = {}) ⇒ Object


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/huffman.rb', line 35

def encode_file(file_path, options = {})
	
	options[:tree_path] ||= file_path
	txt = File.read(file_path).encode('UTF-8', :invalid => :replace)
	txt = txt + EOT # On ajoute le marqueur EOT (enf of transmission 003)
	encoded_text, dictionnary = encode_text(txt,options)	
	encoded_file_name =file_path+".huffman-encoded"

	
	File.open(encoded_file_name, 'wb' ){|f| f.write [encoded_text].pack("B*") }

	dictionnary_stream = dictionnary.collect { |bin, char| bin+"\t"+char }.join('')

	dictionnary_file_name = file_path+".huffman-dictionnary"
	File.open(dictionnary_file_name, 'wb' ){|f| f.write dictionnary_stream }
	
	nil
end

#encode_text(txt, options = {}) ⇒ Object


17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/huffman.rb', line 17

def encode_text(txt, options={})
	
	options[:tree_picture] ||= false
	options[:tree_path] ||= "tree"

	frequencies = LetterFrequency.get_frequencies(txt)
	tree = Tree.new(frequencies)
	dictionnary = tree.dictionnary
	tree.display_as_png(options[:tree_path]) if options[:tree_picture]
	encoded_text = BinaryStream.get_bits_from_text(txt,dictionnary)	 
	return encoded_text, dictionnary

end

#logObject


18
19
20
# File 'lib/huffman/log.rb', line 18

def log
	Log.instance
end