Boost gzip如何将压缩字符串输出为文本

Boost gzip how to output compressed string as text

我在这里使用 boost gzip 示例 code。 我正在尝试压缩一个简单的字符串 test 并期待压缩字符串 H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA 如此在线 compressor

static std::string compress(const std::string& data)
{
    namespace bio = boost::iostreams;
    std::stringstream compressed;
    std::stringstream origin(data);

    bio::filtering_streambuf<bio::input> out;
    out.push(bio::gzip_compressor(bio::gzip_params(bio::gzip::best_compression)));
    out.push(origin);
    
    bio::copy(out, compressed);
    return compressed.str();
}

int main(int argc, char* argv[]){
    std::cout << compress("text") << std::endl;
    // prints out garabage

    return 0;
}

然而,当我打印出转换结果时,我得到了像 +I- 这样的垃圾值。 ~

我知道这是一个有效的转换,因为解压值 returns 是正确的字符串。但是我需要字符串的格式是人类可读的,即 H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA.

如何修改代码以输出人类可读的文本?

谢谢

动机

垃圾格式与我将发送压缩文本的 JSON 库不兼容。

示例站点完全没有提到他们也对结果进行了 base64 编码:

base64 -d <<< 'H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA' | gunzip -

Prints:

test

简而言之,你也需要这样做:

Live On Coliru

#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <iostream>
#include <sstream>

#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>

std::string decode64(std::string const& val)
{
    using namespace boost::archive::iterators;
    return {
        transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>{
            std::begin(val)},
        {std::end(val)},
    };
}

std::string encode64(std::string const& val)
{
    using namespace boost::archive::iterators;
    std::string r{
        base64_from_binary<transform_width<std::string::const_iterator, 6, 8>>{
            std::begin(val)},
        {std::end(val)},
    };
    return r.append((3 - val.size() % 3) % 3, '=');
}

static std::string compress(const std::string& data)
{
    namespace bio = boost::iostreams;
    std::istringstream origin(data);

    bio::filtering_istreambuf in;
    in.push(
        bio::gzip_compressor(bio::gzip_params(bio::gzip::best_compression)));
    in.push(origin);

    std::ostringstream compressed;
    bio::copy(in, compressed);
    return compressed.str();
}

static std::string decompress(const std::string& data)
{
    namespace bio = boost::iostreams;
    std::istringstream compressed(data);

    bio::filtering_istreambuf in;
    in.push(bio::gzip_decompressor());
    in.push(compressed);

    std::ostringstream origin;
    bio::copy(in, origin);
    return origin.str();
}

int main() { 
    auto msg = encode64(compress("test"));
    std::cout << msg << std::endl;
    std::cout << decompress(decode64(msg)) << std::endl;
}

版画

H4sIAAAAAAAC/ytJLS4BAAx+f9gEAAAA
test