compressed.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "compressed.h"
  2. #include "wire_format.h"
  3. #include <util/generic/yexception.h>
  4. #include <contrib/libs/lz4/lz4.h>
  5. #include <contrib/restricted/cityhash-1.0.2/city.h>
  6. #define DBMS_MAX_COMPRESSED_SIZE 0x40000000ULL // 1GB
  7. namespace NClickHouse {
  8. TCompressedInput::TCompressedInput(TCodedInputStream* input)
  9. : Input_(input)
  10. {
  11. }
  12. TCompressedInput::~TCompressedInput() {
  13. if (!Mem_.Exhausted()) {
  14. Y_ABORT("some data was not read");
  15. }
  16. }
  17. size_t TCompressedInput::DoNext(const void** ptr, size_t len) {
  18. if (Mem_.Exhausted()) {
  19. if (!Decompress()) {
  20. return 0;
  21. }
  22. }
  23. return Mem_.Next(ptr, len);
  24. }
  25. bool TCompressedInput::Decompress() {
  26. CityHash_v1_0_2::uint128 hash;
  27. ui32 compressed = 0;
  28. ui32 original = 0;
  29. ui8 method = 0;
  30. if (!TWireFormat::ReadFixed(Input_, &hash)) {
  31. return false;
  32. }
  33. if (!TWireFormat::ReadFixed(Input_, &method)) {
  34. return false;
  35. }
  36. if (method != 0x82) {
  37. ythrow yexception() << "unsupported compression method "
  38. << int(method);
  39. } else {
  40. if (!TWireFormat::ReadFixed(Input_, &compressed)) {
  41. return false;
  42. }
  43. if (!TWireFormat::ReadFixed(Input_, &original)) {
  44. return false;
  45. }
  46. if (compressed > DBMS_MAX_COMPRESSED_SIZE) {
  47. ythrow yexception() << "compressed data too big";
  48. }
  49. TTempBuf tmp(compressed);
  50. // Заполнить заголовок сжатых данных.
  51. tmp.Append(&method, sizeof(method));
  52. tmp.Append(&compressed, sizeof(compressed));
  53. tmp.Append(&original, sizeof(original));
  54. if (!TWireFormat::ReadBytes(Input_, tmp.Data() + 9, compressed - 9)) {
  55. return false;
  56. } else {
  57. if (hash != CityHash_v1_0_2::CityHash128(tmp.Data(), compressed)) {
  58. ythrow yexception() << "data was corrupted";
  59. }
  60. }
  61. Data_ = TTempBuf(original);
  62. if (LZ4_decompress_fast(tmp.Data() + 9, Data_.Data(), original) < 0) {
  63. ythrow yexception() << "can't decompress data";
  64. } else {
  65. Mem_.Reset(Data_.Data(), original);
  66. }
  67. }
  68. return true;
  69. }
  70. }