zlib.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <library/cpp/blockcodecs/core/codecs.h>
  2. #include <library/cpp/blockcodecs/core/common.h>
  3. #include <library/cpp/blockcodecs/core/register.h>
  4. #include <zlib.h>
  5. using namespace NBlockCodecs;
  6. namespace {
  7. struct TZLibCodec: public TAddLengthCodec<TZLibCodec> {
  8. inline TZLibCodec(int level)
  9. : MyName("zlib-" + ToString(level))
  10. , Level(level)
  11. {
  12. }
  13. static inline size_t DoMaxCompressedLength(size_t in) noexcept {
  14. return compressBound(in);
  15. }
  16. TStringBuf Name() const noexcept override {
  17. return MyName;
  18. }
  19. inline size_t DoCompress(const TData& in, void* buf) const {
  20. //TRASH detected
  21. uLong ret = Max<unsigned int>();
  22. int cres = compress2((Bytef*)buf, &ret, (const Bytef*)in.data(), in.size(), Level);
  23. if (cres != Z_OK) {
  24. ythrow TCompressError(cres);
  25. }
  26. return ret;
  27. }
  28. inline void DoDecompress(const TData& in, void* out, size_t len) const {
  29. uLong ret = len;
  30. int uncres = uncompress((Bytef*)out, &ret, (const Bytef*)in.data(), in.size());
  31. if (uncres != Z_OK) {
  32. ythrow TDecompressError(uncres);
  33. }
  34. if (ret != len) {
  35. ythrow TDecompressError(len, ret);
  36. }
  37. }
  38. const TString MyName;
  39. const int Level;
  40. };
  41. struct TZLibRegistrar {
  42. TZLibRegistrar() {
  43. for (int i = 0; i < 10; ++i) {
  44. RegisterCodec(MakeHolder<TZLibCodec>(i));
  45. }
  46. RegisterAlias("zlib", "zlib-6");
  47. }
  48. };
  49. const TZLibRegistrar Registrar{};
  50. }