2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/io/Compression.h>
23 #include <unordered_map>
26 #include <boost/noncopyable.hpp>
27 #include <glog/logging.h>
29 #include <folly/Benchmark.h>
30 #include <folly/Hash.h>
31 #include <folly/Memory.h>
32 #include <folly/Random.h>
33 #include <folly/Varint.h>
34 #include <folly/io/IOBufQueue.h>
35 #include <folly/portability/GTest.h>
37 #if FOLLY_HAVE_LIBZSTD
41 namespace folly { namespace io { namespace test {
43 class DataHolder : private boost::noncopyable {
45 uint64_t hash(size_t size) const;
46 ByteRange data(size_t size) const;
49 explicit DataHolder(size_t sizeLog2);
51 std::unique_ptr<uint8_t[]> data_;
52 mutable std::unordered_map<uint64_t, uint64_t> hashCache_;
55 DataHolder::DataHolder(size_t sizeLog2)
56 : size_(size_t(1) << sizeLog2),
57 data_(new uint8_t[size_]) {
60 uint64_t DataHolder::hash(size_t size) const {
61 CHECK_LE(size, size_);
62 auto p = hashCache_.find(size);
63 if (p != hashCache_.end()) {
67 uint64_t h = folly::hash::fnv64_buf(data_.get(), size);
72 ByteRange DataHolder::data(size_t size) const {
73 CHECK_LE(size, size_);
74 return ByteRange(data_.get(), size);
77 uint64_t hashIOBuf(const IOBuf* buf) {
78 uint64_t h = folly::hash::FNV_64_HASH_START;
79 for (auto& range : *buf) {
80 h = folly::hash::fnv64_buf(range.data(), range.size(), h);
85 class RandomDataHolder : public DataHolder {
87 explicit RandomDataHolder(size_t sizeLog2);
90 RandomDataHolder::RandomDataHolder(size_t sizeLog2)
91 : DataHolder(sizeLog2) {
92 static constexpr size_t numThreadsLog2 = 3;
93 static constexpr size_t numThreads = size_t(1) << numThreadsLog2;
95 uint32_t seed = randomNumberSeed();
97 std::vector<std::thread> threads;
98 threads.reserve(numThreads);
99 for (size_t t = 0; t < numThreads; ++t) {
100 threads.emplace_back([this, seed, t, sizeLog2] {
101 std::mt19937 rng(seed + t);
102 size_t countLog2 = sizeLog2 - numThreadsLog2;
103 size_t start = size_t(t) << countLog2;
104 for (size_t i = 0; i < countLog2; ++i) {
105 this->data_[start + i] = rng();
110 for (auto& t : threads) {
115 class ConstantDataHolder : public DataHolder {
117 explicit ConstantDataHolder(size_t sizeLog2);
120 ConstantDataHolder::ConstantDataHolder(size_t sizeLog2)
121 : DataHolder(sizeLog2) {
122 memset(data_.get(), 'a', size_);
125 constexpr size_t dataSizeLog2 = 27; // 128MiB
126 RandomDataHolder randomDataHolder(dataSizeLog2);
127 ConstantDataHolder constantDataHolder(dataSizeLog2);
129 // The intersection of the provided codecs & those that are compiled in.
130 static std::vector<CodecType> supportedCodecs(std::vector<CodecType> const& v) {
131 std::vector<CodecType> supported;
136 std::back_inserter(supported),
142 // All compiled-in compression codecs.
143 static std::vector<CodecType> availableCodecs() {
144 std::vector<CodecType> codecs;
146 for (size_t i = 0; i < static_cast<size_t>(CodecType::NUM_CODEC_TYPES); ++i) {
147 auto type = static_cast<CodecType>(i);
148 if (hasCodec(type)) {
149 codecs.push_back(type);
156 static std::vector<CodecType> availableStreamCodecs() {
157 std::vector<CodecType> codecs;
159 for (size_t i = 0; i < static_cast<size_t>(CodecType::NUM_CODEC_TYPES); ++i) {
160 auto type = static_cast<CodecType>(i);
161 if (hasStreamCodec(type)) {
162 codecs.push_back(type);
169 TEST(CompressionTestNeedsUncompressedLength, Simple) {
170 static const struct { CodecType type; bool needsUncompressedLength; }
172 { CodecType::NO_COMPRESSION, false },
173 { CodecType::LZ4, true },
174 { CodecType::SNAPPY, false },
175 { CodecType::ZLIB, false },
176 { CodecType::LZ4_VARINT_SIZE, false },
177 { CodecType::LZMA2, false },
178 { CodecType::LZMA2_VARINT_SIZE, false },
179 { CodecType::ZSTD, false },
180 { CodecType::GZIP, false },
181 { CodecType::LZ4_FRAME, false },
182 { CodecType::BZIP2, false },
185 for (auto const& test : expectations) {
186 if (hasCodec(test.type)) {
187 EXPECT_EQ(getCodec(test.type)->needsUncompressedLength(),
188 test.needsUncompressedLength);
193 class CompressionTest
194 : public testing::TestWithParam<std::tr1::tuple<int, int, CodecType>> {
196 void SetUp() override {
197 auto tup = GetParam();
198 uncompressedLength_ = uint64_t(1) << std::tr1::get<0>(tup);
199 chunks_ = std::tr1::get<1>(tup);
200 codec_ = getCodec(std::tr1::get<2>(tup));
203 void runSimpleIOBufTest(const DataHolder& dh);
205 void runSimpleStringTest(const DataHolder& dh);
208 std::unique_ptr<IOBuf> split(std::unique_ptr<IOBuf> data) const;
210 uint64_t uncompressedLength_;
212 std::unique_ptr<Codec> codec_;
215 void CompressionTest::runSimpleIOBufTest(const DataHolder& dh) {
216 const auto original = split(IOBuf::wrapBuffer(dh.data(uncompressedLength_)));
217 const auto compressed = split(codec_->compress(original.get()));
218 if (!codec_->needsUncompressedLength()) {
219 auto uncompressed = codec_->uncompress(compressed.get());
220 EXPECT_EQ(uncompressedLength_, uncompressed->computeChainDataLength());
221 EXPECT_EQ(dh.hash(uncompressedLength_), hashIOBuf(uncompressed.get()));
224 auto uncompressed = codec_->uncompress(compressed.get(),
225 uncompressedLength_);
226 EXPECT_EQ(uncompressedLength_, uncompressed->computeChainDataLength());
227 EXPECT_EQ(dh.hash(uncompressedLength_), hashIOBuf(uncompressed.get()));
231 void CompressionTest::runSimpleStringTest(const DataHolder& dh) {
232 const auto original = std::string(
233 reinterpret_cast<const char*>(dh.data(uncompressedLength_).data()),
234 uncompressedLength_);
235 const auto compressed = codec_->compress(original);
236 if (!codec_->needsUncompressedLength()) {
237 auto uncompressed = codec_->uncompress(compressed);
238 EXPECT_EQ(uncompressedLength_, uncompressed.length());
239 EXPECT_EQ(uncompressed, original);
242 auto uncompressed = codec_->uncompress(compressed, uncompressedLength_);
243 EXPECT_EQ(uncompressedLength_, uncompressed.length());
244 EXPECT_EQ(uncompressed, original);
248 // Uniformly split data into (potentially empty) chunks.
249 std::unique_ptr<IOBuf> CompressionTest::split(
250 std::unique_ptr<IOBuf> data) const {
251 if (data->isChained()) {
255 const size_t size = data->computeChainDataLength();
257 std::multiset<size_t> splits;
258 for (size_t i = 1; i < chunks_; ++i) {
259 splits.insert(Random::rand64(size));
262 folly::IOBufQueue result;
265 for (size_t split : splits) {
266 result.append(IOBuf::copyBuffer(data->data() + offset, split - offset));
269 result.append(IOBuf::copyBuffer(data->data() + offset, size - offset));
271 return result.move();
274 TEST_P(CompressionTest, RandomData) {
275 runSimpleIOBufTest(randomDataHolder);
278 TEST_P(CompressionTest, ConstantData) {
279 runSimpleIOBufTest(constantDataHolder);
282 TEST_P(CompressionTest, RandomDataString) {
283 runSimpleStringTest(randomDataHolder);
286 TEST_P(CompressionTest, ConstantDataString) {
287 runSimpleStringTest(constantDataHolder);
290 INSTANTIATE_TEST_CASE_P(
294 testing::Values(0, 1, 12, 22, 25, 27),
295 testing::Values(1, 2, 3, 8, 65),
296 testing::ValuesIn(availableCodecs())));
298 class CompressionVarintTest
299 : public testing::TestWithParam<std::tr1::tuple<int, CodecType>> {
301 void SetUp() override {
302 auto tup = GetParam();
303 uncompressedLength_ = uint64_t(1) << std::tr1::get<0>(tup);
304 codec_ = getCodec(std::tr1::get<1>(tup));
307 void runSimpleTest(const DataHolder& dh);
309 uint64_t uncompressedLength_;
310 std::unique_ptr<Codec> codec_;
313 inline uint64_t oneBasedMsbPos(uint64_t number) {
315 for (; number > 0; ++pos, number >>= 1) {
320 void CompressionVarintTest::runSimpleTest(const DataHolder& dh) {
321 auto original = IOBuf::wrapBuffer(dh.data(uncompressedLength_));
322 auto compressed = codec_->compress(original.get());
326 std::max(uint64_t(9), oneBasedMsbPos(uncompressedLength_)) / 9UL);
327 auto tinyBuf = IOBuf::copyBuffer(compressed->data(),
328 std::min(compressed->length(), breakPoint));
329 compressed->trimStart(breakPoint);
330 tinyBuf->prependChain(std::move(compressed));
331 compressed = std::move(tinyBuf);
333 auto uncompressed = codec_->uncompress(compressed.get());
335 EXPECT_EQ(uncompressedLength_, uncompressed->computeChainDataLength());
336 EXPECT_EQ(dh.hash(uncompressedLength_), hashIOBuf(uncompressed.get()));
339 TEST_P(CompressionVarintTest, RandomData) {
340 runSimpleTest(randomDataHolder);
343 TEST_P(CompressionVarintTest, ConstantData) {
344 runSimpleTest(constantDataHolder);
347 INSTANTIATE_TEST_CASE_P(
348 CompressionVarintTest,
349 CompressionVarintTest,
351 testing::Values(0, 1, 12, 22, 25, 27),
352 testing::ValuesIn(supportedCodecs({
353 CodecType::LZ4_VARINT_SIZE,
354 CodecType::LZMA2_VARINT_SIZE,
357 class CompressionCorruptionTest : public testing::TestWithParam<CodecType> {
359 void SetUp() override { codec_ = getCodec(GetParam()); }
361 void runSimpleTest(const DataHolder& dh);
363 std::unique_ptr<Codec> codec_;
366 void CompressionCorruptionTest::runSimpleTest(const DataHolder& dh) {
367 constexpr uint64_t uncompressedLength = 42;
368 auto original = IOBuf::wrapBuffer(dh.data(uncompressedLength));
369 auto compressed = codec_->compress(original.get());
371 if (!codec_->needsUncompressedLength()) {
372 auto uncompressed = codec_->uncompress(compressed.get());
373 EXPECT_EQ(uncompressedLength, uncompressed->computeChainDataLength());
374 EXPECT_EQ(dh.hash(uncompressedLength), hashIOBuf(uncompressed.get()));
377 auto uncompressed = codec_->uncompress(compressed.get(),
379 EXPECT_EQ(uncompressedLength, uncompressed->computeChainDataLength());
380 EXPECT_EQ(dh.hash(uncompressedLength), hashIOBuf(uncompressed.get()));
383 EXPECT_THROW(codec_->uncompress(compressed.get(), uncompressedLength + 1),
386 // Corrupt the first character
387 ++(compressed->writableData()[0]);
389 if (!codec_->needsUncompressedLength()) {
390 EXPECT_THROW(codec_->uncompress(compressed.get()),
394 EXPECT_THROW(codec_->uncompress(compressed.get(), uncompressedLength),
398 TEST_P(CompressionCorruptionTest, RandomData) {
399 runSimpleTest(randomDataHolder);
402 TEST_P(CompressionCorruptionTest, ConstantData) {
403 runSimpleTest(constantDataHolder);
406 INSTANTIATE_TEST_CASE_P(
407 CompressionCorruptionTest,
408 CompressionCorruptionTest,
410 // NO_COMPRESSION can't detect corruption
411 // LZ4 can't detect corruption reliably (sigh)
417 CodecType::LZ4_FRAME,
421 class StreamingUnitTest : public testing::TestWithParam<CodecType> {
423 void SetUp() override {
424 codec_ = getStreamCodec(GetParam());
427 std::unique_ptr<StreamCodec> codec_;
430 TEST_P(StreamingUnitTest, maxCompressedLength) {
431 EXPECT_EQ(0, codec_->maxCompressedLength(0));
432 for (uint64_t const length : {1, 10, 100, 1000, 10000, 100000, 1000000}) {
433 EXPECT_GE(codec_->maxCompressedLength(length), length);
437 TEST_P(StreamingUnitTest, getUncompressedLength) {
438 auto const empty = IOBuf::create(0);
439 EXPECT_EQ(uint64_t(0), codec_->getUncompressedLength(empty.get()));
440 EXPECT_EQ(uint64_t(0), codec_->getUncompressedLength(empty.get(), 0));
442 auto const data = IOBuf::wrapBuffer(randomDataHolder.data(100));
443 auto const compressed = codec_->compress(data.get());
445 EXPECT_ANY_THROW(codec_->getUncompressedLength(data.get(), 0));
446 if (auto const length = codec_->getUncompressedLength(data.get())) {
447 EXPECT_EQ(100, *length);
449 EXPECT_EQ(uint64_t(100), codec_->getUncompressedLength(data.get(), 100));
450 // If the uncompressed length is stored in the frame, then make sure it throws
451 // when it is given the wrong length.
452 if (codec_->getUncompressedLength(data.get()) == uint64_t(100)) {
453 EXPECT_ANY_THROW(codec_->getUncompressedLength(data.get(), 200));
457 TEST_P(StreamingUnitTest, emptyData) {
459 auto buffer = IOBuf::create(1);
460 buffer->append(buffer->capacity());
461 MutableByteRange output{};
463 // Test compressing empty data in one pass
464 EXPECT_TRUE(codec_->compressStream(input, output, StreamCodec::FlushOp::END));
465 codec_->resetStream(0);
466 EXPECT_TRUE(codec_->compressStream(input, output, StreamCodec::FlushOp::END));
467 codec_->resetStream();
468 output = {buffer->writableData(), buffer->length()};
469 EXPECT_TRUE(codec_->compressStream(input, output, StreamCodec::FlushOp::END));
470 EXPECT_EQ(buffer->length(), output.size());
472 // Test compressing empty data with multiple calls to compressStream()
473 codec_->resetStream();
475 EXPECT_FALSE(codec_->compressStream(input, output));
477 codec_->compressStream(input, output, StreamCodec::FlushOp::FLUSH));
478 EXPECT_TRUE(codec_->compressStream(input, output, StreamCodec::FlushOp::END));
479 codec_->resetStream();
480 output = {buffer->writableData(), buffer->length()};
481 EXPECT_FALSE(codec_->compressStream(input, output));
483 codec_->compressStream(input, output, StreamCodec::FlushOp::FLUSH));
484 EXPECT_TRUE(codec_->compressStream(input, output, StreamCodec::FlushOp::END));
485 EXPECT_EQ(buffer->length(), output.size());
487 // Test uncompressing empty data
489 codec_->resetStream();
490 EXPECT_TRUE(codec_->uncompressStream(input, output));
491 codec_->resetStream();
493 codec_->uncompressStream(input, output, StreamCodec::FlushOp::FLUSH));
494 codec_->resetStream();
496 codec_->uncompressStream(input, output, StreamCodec::FlushOp::END));
497 codec_->resetStream(0);
498 EXPECT_TRUE(codec_->uncompressStream(input, output));
499 codec_->resetStream(0);
501 codec_->uncompressStream(input, output, StreamCodec::FlushOp::FLUSH));
502 codec_->resetStream(0);
504 codec_->uncompressStream(input, output, StreamCodec::FlushOp::END));
507 TEST_P(StreamingUnitTest, noForwardProgressOkay) {
508 auto inBuffer = IOBuf::create(2);
509 inBuffer->writableData()[0] = 'a';
510 inBuffer->writableData()[0] = 'a';
512 auto input = inBuffer->coalesce();
513 auto compressed = codec_->compress(inBuffer.get());
515 auto outBuffer = IOBuf::create(codec_->maxCompressedLength(2));
516 MutableByteRange output{outBuffer->writableTail(), outBuffer->tailroom()};
518 ByteRange emptyInput;
519 MutableByteRange emptyOutput;
521 // Compress some data to avoid empty data special casing
522 codec_->resetStream();
523 while (!input.empty()) {
524 codec_->compressStream(input, output);
526 // empty input and output is okay for flush NONE and FLUSH.
527 codec_->compressStream(emptyInput, emptyOutput);
528 codec_->compressStream(emptyInput, emptyOutput, StreamCodec::FlushOp::FLUSH);
530 codec_->resetStream();
531 input = inBuffer->coalesce();
532 output = {outBuffer->writableTail(), outBuffer->tailroom()};
533 while (!input.empty()) {
534 codec_->compressStream(input, output);
536 // empty input and output is okay for flush END.
537 codec_->compressStream(emptyInput, emptyOutput, StreamCodec::FlushOp::END);
539 codec_->resetStream();
540 input = compressed->coalesce();
541 input.uncheckedSubtract(1); // Remove last byte so the operation is incomplete
542 output = {inBuffer->writableData(), inBuffer->length()};
543 // Uncompress some data to avoid empty data special casing
544 while (!input.empty()) {
545 EXPECT_FALSE(codec_->uncompressStream(input, output));
547 // empty input and output is okay for all flush values.
548 EXPECT_FALSE(codec_->uncompressStream(emptyInput, emptyOutput));
549 EXPECT_FALSE(codec_->uncompressStream(
550 emptyInput, emptyOutput, StreamCodec::FlushOp::FLUSH));
551 EXPECT_FALSE(codec_->uncompressStream(
552 emptyInput, emptyOutput, StreamCodec::FlushOp::END));
555 TEST_P(StreamingUnitTest, stateTransitions) {
556 auto inBuffer = IOBuf::create(1);
557 inBuffer->writableData()[0] = 'a';
559 auto compressed = codec_->compress(inBuffer.get());
560 ByteRange const in = compressed->coalesce();
561 auto outBuffer = IOBuf::create(codec_->maxCompressedLength(in.size()));
562 MutableByteRange const out{outBuffer->writableTail(), outBuffer->tailroom()};
565 StreamCodec::FlushOp flushOp = StreamCodec::FlushOp::NONE,
566 bool empty = false) {
568 auto output = empty ? MutableByteRange{} : out;
569 return codec_->compressStream(input, output, flushOp);
571 auto uncompress = [&](
572 StreamCodec::FlushOp flushOp = StreamCodec::FlushOp::NONE,
573 bool empty = false) {
575 auto output = empty ? MutableByteRange{} : out;
576 return codec_->uncompressStream(input, output, flushOp);
580 codec_->resetStream();
581 EXPECT_FALSE(compress());
582 EXPECT_FALSE(compress());
583 EXPECT_TRUE(compress(StreamCodec::FlushOp::FLUSH));
584 EXPECT_FALSE(compress());
585 EXPECT_TRUE(compress(StreamCodec::FlushOp::END));
586 // uncompression flow
587 codec_->resetStream();
588 EXPECT_FALSE(uncompress(StreamCodec::FlushOp::NONE, true));
589 codec_->resetStream();
590 EXPECT_FALSE(uncompress(StreamCodec::FlushOp::FLUSH, true));
591 codec_->resetStream();
592 EXPECT_FALSE(uncompress(StreamCodec::FlushOp::NONE, true));
593 codec_->resetStream();
594 EXPECT_FALSE(uncompress(StreamCodec::FlushOp::NONE, true));
595 codec_->resetStream();
596 EXPECT_TRUE(uncompress(StreamCodec::FlushOp::FLUSH));
597 // compress -> uncompress
598 codec_->resetStream();
599 EXPECT_FALSE(compress());
600 EXPECT_THROW(uncompress(), std::logic_error);
601 // uncompress -> compress
602 codec_->resetStream();
603 EXPECT_TRUE(uncompress(StreamCodec::FlushOp::FLUSH));
604 EXPECT_THROW(compress(), std::logic_error);
606 codec_->resetStream();
607 EXPECT_FALSE(compress());
608 EXPECT_TRUE(compress(StreamCodec::FlushOp::END));
609 EXPECT_THROW(compress(), std::logic_error);
611 codec_->resetStream();
612 EXPECT_TRUE(uncompress(StreamCodec::FlushOp::FLUSH));
613 EXPECT_THROW(uncompress(), std::logic_error);
615 codec_->resetStream();
616 EXPECT_FALSE(compress(StreamCodec::FlushOp::FLUSH, true));
617 EXPECT_THROW(compress(), std::logic_error);
619 codec_->resetStream();
620 EXPECT_FALSE(compress(StreamCodec::FlushOp::FLUSH, true));
621 EXPECT_THROW(compress(StreamCodec::FlushOp::END), std::logic_error);
622 // undefined -> compress
623 codec_->compress(inBuffer.get());
624 EXPECT_THROW(compress(), std::logic_error);
625 codec_->uncompress(compressed.get());
626 EXPECT_THROW(compress(), std::logic_error);
627 // undefined -> undefined
628 codec_->uncompress(compressed.get());
629 codec_->compress(inBuffer.get());
632 INSTANTIATE_TEST_CASE_P(
635 testing::ValuesIn(availableStreamCodecs()));
637 class StreamingCompressionTest
638 : public testing::TestWithParam<std::tuple<int, int, CodecType>> {
640 void SetUp() override {
641 auto const tup = GetParam();
642 uncompressedLength_ = uint64_t(1) << std::get<0>(tup);
643 chunkSize_ = size_t(1) << std::get<1>(tup);
644 codec_ = getStreamCodec(std::get<2>(tup));
647 void runResetStreamTest(DataHolder const& dh);
648 void runCompressStreamTest(DataHolder const& dh);
649 void runUncompressStreamTest(DataHolder const& dh);
650 void runFlushTest(DataHolder const& dh);
653 std::vector<ByteRange> split(ByteRange data) const;
655 uint64_t uncompressedLength_;
657 std::unique_ptr<StreamCodec> codec_;
660 std::vector<ByteRange> StreamingCompressionTest::split(ByteRange data) const {
661 size_t const pieces = std::max<size_t>(1, data.size() / chunkSize_);
662 std::vector<ByteRange> result;
663 result.reserve(pieces + 1);
664 while (!data.empty()) {
665 size_t const pieceSize = std::min(data.size(), chunkSize_);
666 result.push_back(data.subpiece(0, pieceSize));
667 data.uncheckedAdvance(pieceSize);
672 static std::unique_ptr<IOBuf> compressSome(
676 StreamCodec::FlushOp flush) {
680 auto buffer = IOBuf::create(bufferSize);
681 buffer->append(buffer->capacity());
682 MutableByteRange output{buffer->writableData(), buffer->length()};
684 result = codec->compressStream(data, output, flush);
685 buffer->trimEnd(output.size());
686 queue.append(std::move(buffer));
688 } while (!(flush == StreamCodec::FlushOp::NONE && data.empty()) && !result);
689 EXPECT_TRUE(data.empty());
693 static std::pair<bool, std::unique_ptr<IOBuf>> uncompressSome(
697 StreamCodec::FlushOp flush) {
701 auto buffer = IOBuf::create(bufferSize);
702 buffer->append(buffer->capacity());
703 MutableByteRange output{buffer->writableData(), buffer->length()};
705 result = codec->uncompressStream(data, output, flush);
706 buffer->trimEnd(output.size());
707 queue.append(std::move(buffer));
709 } while (queue.tailroom() == 0 && !result);
710 return std::make_pair(result, queue.move());
713 void StreamingCompressionTest::runResetStreamTest(DataHolder const& dh) {
714 auto const input = dh.data(uncompressedLength_);
715 // Compress some but leave state unclean
716 codec_->resetStream(uncompressedLength_);
717 compressSome(codec_.get(), input, chunkSize_, StreamCodec::FlushOp::NONE);
718 // Reset stream and compress all
719 codec_->resetStream();
721 compressSome(codec_.get(), input, chunkSize_, StreamCodec::FlushOp::END);
722 auto const uncompressed = codec_->uncompress(compressed.get(), input.size());
723 EXPECT_EQ(dh.hash(uncompressedLength_), hashIOBuf(uncompressed.get()));
726 TEST_P(StreamingCompressionTest, resetStream) {
727 runResetStreamTest(constantDataHolder);
728 runResetStreamTest(randomDataHolder);
731 void StreamingCompressionTest::runCompressStreamTest(
732 const folly::io::test::DataHolder& dh) {
733 auto const inputs = split(dh.data(uncompressedLength_));
736 codec_->resetStream(uncompressedLength_);
737 // Compress many inputs in a row
738 for (auto const input : inputs) {
739 queue.append(compressSome(
740 codec_.get(), input, chunkSize_, StreamCodec::FlushOp::NONE));
742 // Finish the operation with empty input.
745 compressSome(codec_.get(), empty, chunkSize_, StreamCodec::FlushOp::END));
747 auto const uncompressed = codec_->uncompress(queue.front());
748 EXPECT_EQ(dh.hash(uncompressedLength_), hashIOBuf(uncompressed.get()));
751 TEST_P(StreamingCompressionTest, compressStream) {
752 runCompressStreamTest(constantDataHolder);
753 runCompressStreamTest(randomDataHolder);
756 void StreamingCompressionTest::runUncompressStreamTest(
757 const folly::io::test::DataHolder& dh) {
758 auto const data = IOBuf::wrapBuffer(dh.data(uncompressedLength_));
759 // Concatenate 3 compressed frames in a row
760 auto compressed = codec_->compress(data.get());
761 compressed->prependChain(codec_->compress(data.get()));
762 compressed->prependChain(codec_->compress(data.get()));
763 // Pass all 3 compressed frames in one input buffer
764 auto input = compressed->coalesce();
765 // Uncompress the first frame
766 codec_->resetStream(data->computeChainDataLength());
768 auto const result = uncompressSome(
769 codec_.get(), input, chunkSize_, StreamCodec::FlushOp::FLUSH);
770 ASSERT_TRUE(result.first);
771 ASSERT_EQ(hashIOBuf(data.get()), hashIOBuf(result.second.get()));
773 // Uncompress the second frame
774 codec_->resetStream();
776 auto const result = uncompressSome(
777 codec_.get(), input, chunkSize_, StreamCodec::FlushOp::END);
778 ASSERT_TRUE(result.first);
779 ASSERT_EQ(hashIOBuf(data.get()), hashIOBuf(result.second.get()));
781 // Uncompress the third frame
782 codec_->resetStream();
784 auto const result = uncompressSome(
785 codec_.get(), input, chunkSize_, StreamCodec::FlushOp::FLUSH);
786 ASSERT_TRUE(result.first);
787 ASSERT_EQ(hashIOBuf(data.get()), hashIOBuf(result.second.get()));
789 EXPECT_TRUE(input.empty());
792 TEST_P(StreamingCompressionTest, uncompressStream) {
793 runUncompressStreamTest(constantDataHolder);
794 runUncompressStreamTest(randomDataHolder);
797 void StreamingCompressionTest::runFlushTest(DataHolder const& dh) {
798 auto const inputs = split(dh.data(uncompressedLength_));
799 auto uncodec = getStreamCodec(codec_->type());
801 codec_->resetStream();
802 for (auto input : inputs) {
803 // Compress some data and flush the stream
804 auto compressed = compressSome(
805 codec_.get(), input, chunkSize_, StreamCodec::FlushOp::FLUSH);
806 auto compressedRange = compressed->coalesce();
807 // Uncompress the compressed data
808 auto result = uncompressSome(
812 StreamCodec::FlushOp::FLUSH);
813 // All compressed data should have been consumed
814 EXPECT_TRUE(compressedRange.empty());
815 // The frame isn't complete
816 EXPECT_FALSE(result.first);
817 // The uncompressed data should be exactly the input data
818 EXPECT_EQ(input.size(), result.second->computeChainDataLength());
819 auto const data = IOBuf::wrapBuffer(input);
820 EXPECT_EQ(hashIOBuf(data.get()), hashIOBuf(result.second.get()));
824 TEST_P(StreamingCompressionTest, testFlush) {
825 runFlushTest(constantDataHolder);
826 runFlushTest(randomDataHolder);
829 INSTANTIATE_TEST_CASE_P(
830 StreamingCompressionTest,
831 StreamingCompressionTest,
833 testing::Values(0, 1, 12, 22, 27),
834 testing::Values(12, 17, 20),
835 testing::ValuesIn(availableStreamCodecs())));
837 class AutomaticCodecTest : public testing::TestWithParam<CodecType> {
839 void SetUp() override {
840 codec_ = getCodec(GetParam());
841 auto_ = getAutoUncompressionCodec();
844 void runSimpleTest(const DataHolder& dh);
846 std::unique_ptr<Codec> codec_;
847 std::unique_ptr<Codec> auto_;
850 void AutomaticCodecTest::runSimpleTest(const DataHolder& dh) {
851 constexpr uint64_t uncompressedLength = 1000;
852 auto original = IOBuf::wrapBuffer(dh.data(uncompressedLength));
853 auto compressed = codec_->compress(original.get());
855 if (!codec_->needsUncompressedLength()) {
856 auto uncompressed = auto_->uncompress(compressed.get());
857 EXPECT_EQ(uncompressedLength, uncompressed->computeChainDataLength());
858 EXPECT_EQ(dh.hash(uncompressedLength), hashIOBuf(uncompressed.get()));
861 auto uncompressed = auto_->uncompress(compressed.get(), uncompressedLength);
862 EXPECT_EQ(uncompressedLength, uncompressed->computeChainDataLength());
863 EXPECT_EQ(dh.hash(uncompressedLength), hashIOBuf(uncompressed.get()));
865 ASSERT_GE(compressed->computeChainDataLength(), 8);
866 for (size_t i = 0; i < 8; ++i) {
867 auto split = compressed->clone();
868 auto rest = compressed->clone();
869 split->trimEnd(split->length() - i);
871 split->appendChain(std::move(rest));
872 auto uncompressed = auto_->uncompress(split.get(), uncompressedLength);
873 EXPECT_EQ(uncompressedLength, uncompressed->computeChainDataLength());
874 EXPECT_EQ(dh.hash(uncompressedLength), hashIOBuf(uncompressed.get()));
878 TEST_P(AutomaticCodecTest, RandomData) {
879 runSimpleTest(randomDataHolder);
882 TEST_P(AutomaticCodecTest, ConstantData) {
883 runSimpleTest(constantDataHolder);
886 TEST_P(AutomaticCodecTest, ValidPrefixes) {
887 const auto prefixes = codec_->validPrefixes();
888 for (const auto& prefix : prefixes) {
889 EXPECT_FALSE(prefix.empty());
890 // Ensure that all strings are at least 8 bytes for LZMA2.
891 // The bytes after the prefix should be ignored by `canUncompress()`.
892 IOBuf data{IOBuf::COPY_BUFFER, prefix, 0, 8};
894 EXPECT_TRUE(codec_->canUncompress(&data));
895 EXPECT_TRUE(auto_->canUncompress(&data));
899 TEST_P(AutomaticCodecTest, NeedsUncompressedLength) {
900 if (codec_->needsUncompressedLength()) {
901 EXPECT_TRUE(auto_->needsUncompressedLength());
905 TEST_P(AutomaticCodecTest, maxUncompressedLength) {
906 EXPECT_LE(codec_->maxUncompressedLength(), auto_->maxUncompressedLength());
909 TEST_P(AutomaticCodecTest, DefaultCodec) {
910 const uint64_t length = 42;
911 std::vector<std::unique_ptr<Codec>> codecs;
912 codecs.push_back(getCodec(CodecType::ZSTD));
913 auto automatic = getAutoUncompressionCodec(std::move(codecs));
914 auto original = IOBuf::wrapBuffer(constantDataHolder.data(length));
915 auto compressed = codec_->compress(original.get());
916 auto decompressed = automatic->uncompress(compressed.get());
918 EXPECT_EQ(constantDataHolder.hash(length), hashIOBuf(decompressed.get()));
922 class CustomCodec : public Codec {
924 static std::unique_ptr<Codec> create(std::string prefix, CodecType type) {
925 return std::make_unique<CustomCodec>(std::move(prefix), type);
927 explicit CustomCodec(std::string prefix, CodecType type)
928 : Codec(CodecType::USER_DEFINED),
929 prefix_(std::move(prefix)),
930 codec_(getCodec(type)) {}
933 std::vector<std::string> validPrefixes() const override {
937 uint64_t doMaxCompressedLength(uint64_t uncompressedLength) const override {
938 return codec_->maxCompressedLength(uncompressedLength) + prefix_.size();
941 bool canUncompress(const IOBuf* data, Optional<uint64_t>) const override {
942 auto clone = data->cloneCoalescedAsValue();
943 if (clone.length() < prefix_.size()) {
946 return memcmp(clone.data(), prefix_.data(), prefix_.size()) == 0;
949 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override {
950 auto result = IOBuf::copyBuffer(prefix_);
951 result->appendChain(codec_->compress(data));
952 EXPECT_TRUE(canUncompress(result.get(), data->computeChainDataLength()));
956 std::unique_ptr<IOBuf> doUncompress(
958 Optional<uint64_t> uncompressedLength) override {
959 EXPECT_TRUE(canUncompress(data, uncompressedLength));
960 auto clone = data->cloneCoalescedAsValue();
961 clone.trimStart(prefix_.size());
962 return codec_->uncompress(&clone, uncompressedLength);
966 std::unique_ptr<Codec> codec_;
970 TEST_P(AutomaticCodecTest, CustomCodec) {
971 const uint64_t length = 42;
972 auto ab = CustomCodec::create("ab", CodecType::ZSTD);
973 std::vector<std::unique_ptr<Codec>> codecs;
974 codecs.push_back(CustomCodec::create("ab", CodecType::ZSTD));
975 auto automatic = getAutoUncompressionCodec(std::move(codecs));
976 auto original = IOBuf::wrapBuffer(constantDataHolder.data(length));
978 auto abCompressed = ab->compress(original.get());
979 auto abDecompressed = automatic->uncompress(abCompressed.get());
980 EXPECT_TRUE(automatic->canUncompress(abCompressed.get()));
981 EXPECT_FALSE(auto_->canUncompress(abCompressed.get()));
982 EXPECT_EQ(constantDataHolder.hash(length), hashIOBuf(abDecompressed.get()));
984 auto compressed = codec_->compress(original.get());
985 auto decompressed = automatic->uncompress(compressed.get());
986 EXPECT_EQ(constantDataHolder.hash(length), hashIOBuf(decompressed.get()));
989 TEST_P(AutomaticCodecTest, CustomDefaultCodec) {
990 const uint64_t length = 42;
991 auto none = CustomCodec::create("none", CodecType::NO_COMPRESSION);
992 std::vector<std::unique_ptr<Codec>> codecs;
993 codecs.push_back(CustomCodec::create("none", CodecType::NO_COMPRESSION));
994 codecs.push_back(getCodec(CodecType::LZ4_FRAME));
995 auto automatic = getAutoUncompressionCodec(std::move(codecs));
996 auto original = IOBuf::wrapBuffer(constantDataHolder.data(length));
998 auto noneCompressed = none->compress(original.get());
999 auto noneDecompressed = automatic->uncompress(noneCompressed.get());
1000 EXPECT_TRUE(automatic->canUncompress(noneCompressed.get()));
1001 EXPECT_FALSE(auto_->canUncompress(noneCompressed.get()));
1002 EXPECT_EQ(constantDataHolder.hash(length), hashIOBuf(noneDecompressed.get()));
1004 auto compressed = codec_->compress(original.get());
1005 auto decompressed = automatic->uncompress(compressed.get());
1006 EXPECT_EQ(constantDataHolder.hash(length), hashIOBuf(decompressed.get()));
1009 TEST_P(AutomaticCodecTest, canUncompressOneBytes) {
1010 // No default codec can uncompress 1 bytes.
1011 IOBuf buf{IOBuf::CREATE, 1};
1013 EXPECT_FALSE(codec_->canUncompress(&buf, 1));
1014 EXPECT_FALSE(codec_->canUncompress(&buf, folly::none));
1015 EXPECT_FALSE(auto_->canUncompress(&buf, 1));
1016 EXPECT_FALSE(auto_->canUncompress(&buf, folly::none));
1019 INSTANTIATE_TEST_CASE_P(
1023 CodecType::LZ4_FRAME,
1030 TEST(ValidPrefixesTest, CustomCodec) {
1031 std::vector<std::unique_ptr<Codec>> codecs;
1032 codecs.push_back(CustomCodec::create("none", CodecType::NO_COMPRESSION));
1033 const auto none = getAutoUncompressionCodec(std::move(codecs));
1034 const auto prefixes = none->validPrefixes();
1035 const auto it = std::find(prefixes.begin(), prefixes.end(), "none");
1036 EXPECT_TRUE(it != prefixes.end());
1039 #define EXPECT_THROW_IF_DEBUG(statement, expected_exception) \
1042 EXPECT_THROW((statement), expected_exception); \
1044 EXPECT_NO_THROW((statement)); \
1048 TEST(CheckCompatibleTest, SimplePrefixSecond) {
1049 std::vector<std::unique_ptr<Codec>> codecs;
1050 codecs.push_back(CustomCodec::create("abc", CodecType::NO_COMPRESSION));
1051 codecs.push_back(CustomCodec::create("ab", CodecType::NO_COMPRESSION));
1052 EXPECT_THROW_IF_DEBUG(
1053 getAutoUncompressionCodec(std::move(codecs)), std::invalid_argument);
1056 TEST(CheckCompatibleTest, SimplePrefixFirst) {
1057 std::vector<std::unique_ptr<Codec>> codecs;
1058 codecs.push_back(CustomCodec::create("ab", CodecType::NO_COMPRESSION));
1059 codecs.push_back(CustomCodec::create("abc", CodecType::NO_COMPRESSION));
1060 EXPECT_THROW_IF_DEBUG(
1061 getAutoUncompressionCodec(std::move(codecs)), std::invalid_argument);
1064 TEST(CheckCompatibleTest, Empty) {
1065 std::vector<std::unique_ptr<Codec>> codecs;
1066 codecs.push_back(CustomCodec::create("", CodecType::NO_COMPRESSION));
1067 EXPECT_THROW_IF_DEBUG(
1068 getAutoUncompressionCodec(std::move(codecs)), std::invalid_argument);
1071 TEST(CheckCompatibleTest, ZstdPrefix) {
1072 std::vector<std::unique_ptr<Codec>> codecs;
1073 codecs.push_back(CustomCodec::create("\x28\xB5\x2F", CodecType::ZSTD));
1074 EXPECT_THROW_IF_DEBUG(
1075 getAutoUncompressionCodec(std::move(codecs)), std::invalid_argument);
1078 TEST(CheckCompatibleTest, ZstdDuplicate) {
1079 std::vector<std::unique_ptr<Codec>> codecs;
1080 codecs.push_back(CustomCodec::create("\x28\xB5\x2F\xFD", CodecType::ZSTD));
1081 EXPECT_THROW_IF_DEBUG(
1082 getAutoUncompressionCodec(std::move(codecs)), std::invalid_argument);
1085 TEST(CheckCompatibleTest, ZlibIsPrefix) {
1086 std::vector<std::unique_ptr<Codec>> codecs;
1087 codecs.push_back(CustomCodec::create("\x18\x76zzasdf", CodecType::ZSTD));
1088 EXPECT_THROW_IF_DEBUG(
1089 getAutoUncompressionCodec(std::move(codecs)), std::invalid_argument);
1092 #if FOLLY_HAVE_LIBZSTD
1094 TEST(ZstdTest, BackwardCompatible) {
1095 auto codec = getCodec(CodecType::ZSTD);
1097 auto const data = IOBuf::wrapBuffer(randomDataHolder.data(size_t(1) << 20));
1098 auto compressed = codec->compress(data.get());
1099 compressed->coalesce();
1102 ZSTD_getDecompressedSize(compressed->data(), compressed->length()));
1106 IOBuf::wrapBuffer(randomDataHolder.data(size_t(100) << 20));
1107 auto compressed = codec->compress(data.get());
1108 compressed->coalesce();
1111 ZSTD_getDecompressedSize(compressed->data(), compressed->length()));
1118 int main(int argc, char *argv[]) {
1119 testing::InitGoogleTest(&argc, argv);
1120 gflags::ParseCommandLineFlags(&argc, &argv, true);
1122 auto ret = RUN_ALL_TESTS();
1124 folly::runBenchmarksOnFlag();