Advertisement
Guest User

Untitled

a guest
Mar 12th, 2014
476
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. #include <stdexcept>
  2.  
  3. #include <iomanip>
  4. #include <sstream>
  5.  
  6. #include <zlib.h>
  7.  
  8. std::string compress_string(const std::string& str,
  9.                             int compressionlevel = Z_BEST_COMPRESSION)
  10. {
  11.     z_stream zs;                        // z_stream is zlib's control structure
  12.     memset(&zs, 0, sizeof(zs));
  13.  
  14.     if (deflateInit(&zs, compressionlevel) != Z_OK)
  15.         throw(std::runtime_error("deflateInit failed while compressing."));
  16.  
  17.     zs.next_in = (Bytef*)str.data();
  18.     zs.avail_in = str.size();           // set the z_stream's input
  19.  
  20.     int ret;
  21.     char outbuffer[32768];
  22.     std::string outstring;
  23.  
  24.     // retrieve the compressed bytes blockwise
  25.     do {
  26.         zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
  27.         zs.avail_out = sizeof(outbuffer);
  28.  
  29.         ret = deflate(&zs, Z_FINISH);
  30.  
  31.         if (outstring.size() < zs.total_out) {
  32.             // append the block to the output string
  33.             outstring.append(outbuffer,
  34.                              zs.total_out - outstring.size());
  35.         }
  36.     } while (ret == Z_OK);
  37.  
  38.     deflateEnd(&zs);
  39.  
  40.     if (ret != Z_STREAM_END) {          // an error occurred that was not EOF
  41.         std::ostringstream oss;
  42.         oss << "Exception during zlib compression: (" << ret << ") " << zs.msg;
  43.         throw(std::runtime_error(oss.str()));
  44.     }
  45.  
  46.     return outstring;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement