/* */ #include "GZipEncoder.h" #include #include "StringFormat.h" #include "DlAbortEx.h" #include "util.h" namespace aria2 { namespace { const int OUTBUF_LENGTH = 4096; } GZipEncoder::GZipEncoder():_strm(0), _finished(false) {} GZipEncoder::~GZipEncoder() { release(); } void GZipEncoder::init() { _finished = false; release(); _strm = new z_stream(); _strm->zalloc = Z_NULL; _strm->zfree = Z_NULL; _strm->opaque = Z_NULL; _strm->avail_in = 0; _strm->next_in = Z_NULL; if(Z_OK != deflateInit2(_strm, 9, Z_DEFLATED, 31, 9, Z_DEFAULT_STRATEGY)) { throw DL_ABORT_EX("Initializing z_stream failed."); } } void GZipEncoder::release() { if(_strm) { deflateEnd(_strm); delete _strm; _strm = 0; } } std::string GZipEncoder::encode (const unsigned char* in, size_t length, int flush) { std::string out; _strm->avail_in = length; _strm->next_in = const_cast(in); unsigned char outbuf[OUTBUF_LENGTH]; while(1) { _strm->avail_out = OUTBUF_LENGTH; _strm->next_out = outbuf; int ret = ::deflate(_strm, flush); if(ret == Z_STREAM_END) { _finished = true; } else if(ret != Z_OK) { throw DL_ABORT_EX(StringFormat("libz::deflate() failed. cause:%s", _strm->msg).str()); } size_t produced = OUTBUF_LENGTH-_strm->avail_out; out.append(&outbuf[0], &outbuf[produced]); if(_strm->avail_out > 0) { break; } } return out; } bool GZipEncoder::finished() { return _finished; } std::string GZipEncoder::str() { _internalBuf += encode(0, 0, Z_FINISH); return _internalBuf; } GZipEncoder& GZipEncoder::operator<<(const char* s) { _internalBuf += encode(reinterpret_cast(s), strlen(s)); return *this; } GZipEncoder& GZipEncoder::operator<<(const std::string& s) { _internalBuf += encode (reinterpret_cast(s.data()), s.size()); return *this; } GZipEncoder& GZipEncoder::operator<<(int64_t i) { std::string s = util::itos(i); (*this) << s; return *this; } } // namespace aria2