huffman_file_compression.sf 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. #!/usr/bin/ruby
  2. # Compress/decompress small files using Huffman coding.
  3. define(
  4. CHUNK_SIZE = 1024**2, # 1 MB
  5. SIGNATURE = ('HFM' + 3.chr),
  6. )
  7. func walk(Hash n, String s, Hash h) {
  8. if (n.has(:a)) {
  9. h{n{:a}} = s
  10. return nil
  11. }
  12. walk(n{:0}, s+'0', h) if n.has(:0)
  13. walk(n{:1}, s+'1', h) if n.has(:1)
  14. }
  15. func make_tree(Array bytes) {
  16. var nodes = bytes.freq.sort.map_2d { |b,f|
  17. Hash(a => b, freq => f)
  18. }
  19. loop {
  20. nodes.sort_by!{|h| h{:freq} }
  21. var(x, y) = (nodes.shift, nodes.shift)
  22. if (defined(x)) {
  23. if (defined(y)) {
  24. nodes << Hash(:0 => x, :1 => y, :freq => x{:freq}+y{:freq})
  25. }
  26. else {
  27. nodes << Hash(:0 => x, :freq => x{:freq})
  28. }
  29. }
  30. nodes.len > 1 || break
  31. }
  32. var n = nodes.first
  33. walk(n, '', n{:tree} = Hash())
  34. return n
  35. }
  36. func huffman_encode(Array bytes, Hash t) {
  37. join('', t{bytes...})
  38. }
  39. func huffman_decode (String bits, Hash tree) {
  40. bits.gsub(Regex('(' + tree.keys.sort_by { .len }.join('|') + ')'), {|s| tree{s} })
  41. }
  42. func create_huffman_entry (Array bytes, FileHandle out_fh) {
  43. var h = make_tree(bytes){:tree}
  44. var enc = huffman_encode(bytes, h)
  45. var dict = ''
  46. var codes = ''
  47. for i in (0..255) {
  48. var c = (h{i} \\ '')
  49. codes += c
  50. dict += c.len.chr
  51. }
  52. out_fh.print(dict)
  53. out_fh.print(pack("B*", codes))
  54. out_fh.print(pack("N", enc.len))
  55. out_fh.print(pack("B*", enc))
  56. }
  57. # Compress file
  58. func huffman_compress_file(File input, File output) {
  59. var in_fh = input.open('<:raw') || die "Can't open file <<#{input}>> for reading"
  60. var out_fh = output.open('>:raw') || die "Can't open file <<#{output}>> for writing"
  61. var header = SIGNATURE
  62. # Print the header
  63. out_fh.print(header)
  64. while (in_fh.read(\var chunk, CHUNK_SIZE)) {
  65. create_huffman_entry([unpack('C*', chunk)], out_fh)
  66. }
  67. # Close the files
  68. in_fh.close
  69. out_fh.close
  70. }
  71. func read_bits (FileHandle fh, Number bits_len) {
  72. var str = ''
  73. fh.read(\str, bits_len>>3)
  74. str = unpack('B*', str)
  75. while (str.len < bits_len) {
  76. str += unpack('B*', fh.getc \\ return nil)
  77. }
  78. if (str.len > bits_len) {
  79. str.substr!(0, bits_len)
  80. }
  81. return str
  82. }
  83. func decode_huffman_entry (FileHandle fh, FileHandle out_fh) {
  84. var codes = []
  85. var codes_len = 0
  86. fh.read(\var buffer, 256)
  87. [unpack('C*', buffer)].map{ Num(_) }.each_kv {|c,l|
  88. if (l > 0) {
  89. codes_len += l
  90. codes << [c, l]
  91. }
  92. }
  93. var codes_bin = read_bits(fh, codes_len)
  94. var rev_dict = Hash()
  95. for c,l in (codes) {
  96. var code = substr(codes_bin, 0, l)
  97. codes_bin.substr!(l)
  98. rev_dict{code} = c.chr
  99. }
  100. var enc_len = Num(unpack('N', 4.of{ fh.getc }.join))
  101. if (enc_len > 0) {
  102. var enc_data = read_bits(fh, enc_len)
  103. out_fh.print(huffman_decode(enc_data, rev_dict))
  104. return true
  105. }
  106. return false
  107. }
  108. # Decompress file
  109. func huffman_decompress_file(File input, File output) {
  110. var in_fh = input.open('<:raw') || die "Can't open file <<#{input}>> for reading"
  111. if (SIGNATURE.len.of { in_fh.getc }.join != SIGNATURE) {
  112. die "Not a HFM archive!\n"
  113. }
  114. var out_fh = output.open('>:raw') || die "Can't open file <<#{output}>> for writing"
  115. while (!in_fh.eof) {
  116. decode_huffman_entry(in_fh, out_fh) || break
  117. }
  118. in_fh.close
  119. out_fh.close
  120. }
  121. ARGV.getopt!('d', \var decode)
  122. var file = File(ARGV.shift) || do {
  123. say "usage: #{File(__MAIN__).basename} [-d] [input file]"
  124. Sys.exit(2)
  125. }
  126. if (decode || file.match(/\.hfm\.enc\z/)) {
  127. huffman_decompress_file(file, File("output.hfm.dec"))
  128. }
  129. else {
  130. huffman_compress_file(file, File("output.hfm.enc"))
  131. }