Uncompress data in memory using Boost gzip_decompr

2019-02-26 10:07发布

问题:

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

回答1:

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.