2

I'm trying to decompress binary data in memory using Boost gzip_decompressor. From this answer, I adapted the following code:

vector<char> unzip(const vector<char> compressed)
{
    vector<char> decompressed = vector<char>();

    boost::iostreams::filtering_ostream os;

    os.push(boost::iostreams::gzip_decompressor());
    os.push(boost::iostreams::back_inserter(decompressed));

    boost::iostreams::write(os, &compressed[0], compressed.size());

    return decompressed;
}

However, the returned vector has zero length. What am I doing wrong? I tried calling flush() on the os stream, but it did not make a difference

Community
  • 1
  • 1
dbkk
  • 12,643
  • 13
  • 53
  • 60

1 Answers1

3

Your code works for me with this simple test program:

#include <iostream>
#include <vector>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>

std::vector<char> unzip(const std::vector<char> compressed)
{
   std::vector<char> decompressed = std::vector<char>();

   boost::iostreams::filtering_ostream os;

   os.push(boost::iostreams::gzip_decompressor());
   os.push(boost::iostreams::back_inserter(decompressed));

   boost::iostreams::write(os, &compressed[0], compressed.size());

   return decompressed;
}

int main() {
   std::vector<char> compressed;
   {
      boost::iostreams::filtering_ostream os;
      os.push(boost::iostreams::gzip_compressor());
      os.push(boost::iostreams::back_inserter(compressed));
      os << "hello\n";
      os.reset();
   }
   std::cout << "Compressed size: " << compressed.size() << '\n';

   const std::vector<char> decompressed = unzip(compressed);
   std::cout << std::string(decompressed.begin(), decompressed.end());

   return 0;
}

Are you sure your input was compressed with gzip and not some other method (e.g. raw deflate)? gzip compressed data begins with bytes 1f 8b.

I generally use reset() or put the stream and filters in their own block to make sure that output is complete. I did both for compression above, just as an example.

rhashimoto
  • 15,650
  • 2
  • 52
  • 80
  • Weird, your example doesn't work for me (produces zero-length output). Perhaps it's a build issue. – dbkk May 23 '13 at 08:38
  • That is odd. It works for me on OS X 10.7.5 with boost 1.52 and Ubuntu 10.10 with boost 1.53. – rhashimoto May 23 '13 at 13:01