Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: uncompress zlib-wrapped deflate data

Tags:

ruby

zlib

In Ruby, I have a buffer containing data compressed with the zlib compress2() method. However I found no way to decompress this data using the Zlib functionality in the Ruby standard library which only supports data created by deflate or data in GZip format.

How can I achieve the equivalent of uncompress() in Ruby, preferably without resorting to creating a custom C-extension?

Edit:

I found the solution. After fiddling around with the window_bits argument to the Inflate constructor without success, I finally understood that zlib prefixes the compressed data with a four-byte header. So I simply removed that header and suddenly it worked like a charm:

  data[0..3] = ''
  data = Zlib::Inflate.inflate(data)
like image 707
milgner Avatar asked Nov 15 '25 17:11

milgner


2 Answers

You need to use negative value for window_bits as stated here. I've faced similar problem but for compressing on Ruby and decompressing on JS (my gist for that). Hope it helps to avoid magic with four bites :)

like image 177
Andrii Lazarchuk Avatar answered Nov 18 '25 18:11

Andrii Lazarchuk


The documentation indicates that the Ruby inflate class will decompress the output of compress2(), which is in the zlib format. I just tried it, and it works fine. Your compressed data may not be making it over to Ruby intact.

like image 28
Mark Adler Avatar answered Nov 18 '25 18:11

Mark Adler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!