http_compress.cpp 986 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #include "http.h"
  2. #include <zlib.h>
  3. namespace NHttp {
  4. TString THttpOutgoingResponse::CompressDeflate(TStringBuf source) {
  5. int compressionlevel = Z_BEST_COMPRESSION;
  6. z_stream zs = {};
  7. if (deflateInit(&zs, compressionlevel) != Z_OK) {
  8. throw yexception() << "deflateInit failed while compressing";
  9. }
  10. zs.next_in = (Bytef*)source.data();
  11. zs.avail_in = source.size();
  12. int ret;
  13. char outbuffer[32768];
  14. TString result;
  15. // retrieve the compressed bytes blockwise
  16. do {
  17. zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
  18. zs.avail_out = sizeof(outbuffer);
  19. ret = deflate(&zs, Z_FINISH);
  20. if (result.size() < zs.total_out) {
  21. result.append(outbuffer, zs.total_out - result.size());
  22. }
  23. } while (ret == Z_OK);
  24. deflateEnd(&zs);
  25. if (ret != Z_STREAM_END) {
  26. throw yexception() << "Exception during zlib compression: (" << ret << ") " << zs.msg;
  27. }
  28. return result;
  29. }
  30. }