lzma_ut.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #include "lzma.h"
  2. #include <library/cpp/testing/unittest/registar.h>
  3. #include <util/stream/mem.h>
  4. #include <util/random/fast.h>
  5. #include <util/random/random.h>
  6. class TStrokaByOneByte: public IZeroCopyInput {
  7. public:
  8. TStrokaByOneByte(const TString& s)
  9. : Data(s)
  10. , Pos(s.data())
  11. {
  12. }
  13. private:
  14. size_t DoNext(const void** ptr, size_t len) override {
  15. if (Pos < Data.end()) {
  16. len = Min(len, static_cast<size_t>(1));
  17. *ptr = Pos;
  18. Pos += len;
  19. return len;
  20. } else {
  21. return 0;
  22. }
  23. }
  24. TString Data;
  25. const char* Pos;
  26. };
  27. class TLzmaTest: public TTestBase {
  28. UNIT_TEST_SUITE(TLzmaTest);
  29. UNIT_TEST(Test1)
  30. UNIT_TEST(Test2)
  31. UNIT_TEST_SUITE_END();
  32. private:
  33. inline TString GenData() {
  34. TString data;
  35. TReallyFastRng32 rnd(RandomNumber<ui64>());
  36. for (size_t i = 0; i < 50000; ++i) {
  37. const char ch = rnd.Uniform(256);
  38. const size_t len = 1 + rnd.Uniform(10);
  39. data += TString(len, ch);
  40. }
  41. return data;
  42. }
  43. inline void Test2() {
  44. class TExcOutput: public IOutputStream {
  45. public:
  46. ~TExcOutput() override {
  47. }
  48. void DoWrite(const void*, size_t) override {
  49. throw 12345;
  50. }
  51. };
  52. TString data(GenData());
  53. TMemoryInput mi(data.data(), data.size());
  54. TExcOutput out;
  55. try {
  56. TLzmaCompress c(&out);
  57. TransferData(&mi, &c);
  58. } catch (int i) {
  59. UNIT_ASSERT_EQUAL(i, 12345);
  60. }
  61. }
  62. inline void Test1() {
  63. TString data(GenData());
  64. TString data1;
  65. TString res;
  66. {
  67. TMemoryInput mi(data.data(), data.size());
  68. TStringOutput so(res);
  69. TLzmaCompress c(&so);
  70. TransferData(&mi, &c);
  71. c.Finish();
  72. }
  73. {
  74. TMemoryInput mi(res.data(), res.size());
  75. TStringOutput so(data1);
  76. TLzmaDecompress d((IInputStream*)&mi);
  77. TransferData(&d, &so);
  78. }
  79. UNIT_ASSERT_EQUAL(data, data1);
  80. data1.clear();
  81. {
  82. TMemoryInput mi(res.data(), res.size());
  83. TStringOutput so(data1);
  84. TLzmaDecompress d(&mi);
  85. TransferData(&d, &so);
  86. }
  87. UNIT_ASSERT_EQUAL(data, data1);
  88. data1.clear();
  89. {
  90. TStrokaByOneByte mi(res);
  91. TStringOutput so(data1);
  92. TLzmaDecompress d(&mi);
  93. TransferData(&d, &so);
  94. }
  95. UNIT_ASSERT_EQUAL(data, data1);
  96. }
  97. };
  98. UNIT_TEST_SUITE_REGISTRATION(TLzmaTest);