Boost Iostreams zlib_error with Custom Source

馋奶兔 提交于 2019-12-05 16:28:02

EDIT In response to the clarified question (in the comments below), here's a trivial adaptation I did of your original sample, that JustWorks™ on my box:

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

template <class cha_type, class iterator_type>
struct my_source {
    typedef cha_type char_type;
    typedef boost::iostreams::source_tag category;

    iterator_type& it;
    iterator_type end;

    my_source(iterator_type& it, iterator_type end = {}) : it(it), end(end) 
    { }

    std::streamsize read(char* s, std::streamsize n) {
        std::streamsize result = 0;
        while ((it!=end) && n--) {
            ++result;
            *s++ = *it++;
        }
        return result;
    }
};

int main() {       
    std::string const rawdata {'x', '\234', '\313', 'H', '\315', '\311', '\311', 'W', '(', '\317', '/', '\312', 'I', '\341', '\002', '\0', '\036', 'r', '\004', 'g' };
    std::istringstream iss(rawdata, std::ios::binary);

    auto start = std::istreambuf_iterator<char>(iss);
    my_source<char, decltype(start)> data(start);

    boost::iostreams::filtering_istreambuf def;
    def.push(boost::iostreams::zlib_decompressor());
    def.push(data);

    boost::iostreams::copy(def, std::cout);
}

See it Live On Coliru


Old answer:

I think you can use just any stream, like stringstream:

std::istringstream iss("hello world\n");

filtering_streambuf<input> def;
def.push(zlib_compressor());
def.push(iss);
boost::iostreams::copy(def, std::cout);

or to decompress:

std::string const rawdata {'x', '\234', '\313', 'H', '\315', '\311', '\311', 'W', '(', '\317', '/', '\312', 'I', '\341', '\002', '\0', '\036', 'r', '\004', 'g' };
std::istringstream iss(rawdata, std::ios::binary);

filtering_streambuf<input> def;
def.push(zlib_decompressor());
def.push(iss);
boost::iostreams::copy(def, std::cout);

This works like a charm here. (Sorry for the octal escapes: it's what bash gave me

printf "%q\n" "$(echo hello world | zlib-flate -compress)"

and I'm lazy enough to keep it that way).

See full example Live on Coliru


Alternatively Boost Iostreams accepts a streambuffer, so you can equivalently

def.push(*iss.rdbuf());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!