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>
22 #if LZ4_VERSION_NUMBER >= 10301
27 #include <glog/logging.h>
29 #if FOLLY_HAVE_LIBSNAPPY
31 #include <snappy-sinksource.h>
38 #if FOLLY_HAVE_LIBLZMA
42 #if FOLLY_HAVE_LIBZSTD
46 #include <folly/Bits.h>
47 #include <folly/Conv.h>
48 #include <folly/Memory.h>
49 #include <folly/Portability.h>
50 #include <folly/ScopeGuard.h>
51 #include <folly/Varint.h>
52 #include <folly/io/Cursor.h>
54 #include <unordered_set>
56 namespace folly { namespace io {
58 Codec::Codec(CodecType type) : type_(type) { }
60 // Ensure consistent behavior in the nullptr case
61 std::unique_ptr<IOBuf> Codec::compress(const IOBuf* data) {
62 uint64_t len = data->computeChainDataLength();
64 return IOBuf::create(0);
66 if (len > maxUncompressedLength()) {
67 throw std::runtime_error("Codec: uncompressed length too large");
70 return doCompress(data);
73 std::string Codec::compress(const StringPiece data) {
74 const uint64_t len = data.size();
78 if (len > maxUncompressedLength()) {
79 throw std::runtime_error("Codec: uncompressed length too large");
82 return doCompressString(data);
85 std::unique_ptr<IOBuf> Codec::uncompress(const IOBuf* data,
86 uint64_t uncompressedLength) {
87 if (uncompressedLength == UNKNOWN_UNCOMPRESSED_LENGTH) {
88 if (needsUncompressedLength()) {
89 throw std::invalid_argument("Codec: uncompressed length required");
91 } else if (uncompressedLength > maxUncompressedLength()) {
92 throw std::runtime_error("Codec: uncompressed length too large");
96 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
97 uncompressedLength != 0) {
98 throw std::runtime_error("Codec: invalid uncompressed length");
100 return IOBuf::create(0);
103 return doUncompress(data, uncompressedLength);
106 std::string Codec::uncompress(
107 const StringPiece data,
108 uint64_t uncompressedLength) {
109 if (uncompressedLength == UNKNOWN_UNCOMPRESSED_LENGTH) {
110 if (needsUncompressedLength()) {
111 throw std::invalid_argument("Codec: uncompressed length required");
113 } else if (uncompressedLength > maxUncompressedLength()) {
114 throw std::runtime_error("Codec: uncompressed length too large");
118 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
119 uncompressedLength != 0) {
120 throw std::runtime_error("Codec: invalid uncompressed length");
125 return doUncompressString(data, uncompressedLength);
128 bool Codec::needsUncompressedLength() const {
129 return doNeedsUncompressedLength();
132 uint64_t Codec::maxUncompressedLength() const {
133 return doMaxUncompressedLength();
136 bool Codec::doNeedsUncompressedLength() const {
140 uint64_t Codec::doMaxUncompressedLength() const {
141 return UNLIMITED_UNCOMPRESSED_LENGTH;
144 std::vector<std::string> Codec::validPrefixes() const {
148 bool Codec::canUncompress(const IOBuf*, uint64_t) const {
152 std::string Codec::doCompressString(const StringPiece data) {
153 const IOBuf inputBuffer{IOBuf::WRAP_BUFFER, data};
154 auto outputBuffer = doCompress(&inputBuffer);
156 output.reserve(outputBuffer->computeChainDataLength());
157 for (auto range : *outputBuffer) {
158 output.append(reinterpret_cast<const char*>(range.data()), range.size());
163 std::string Codec::doUncompressString(
164 const StringPiece data,
165 uint64_t uncompressedLength) {
166 const IOBuf inputBuffer{IOBuf::WRAP_BUFFER, data};
167 auto outputBuffer = doUncompress(&inputBuffer, uncompressedLength);
169 output.reserve(outputBuffer->computeChainDataLength());
170 for (auto range : *outputBuffer) {
171 output.append(reinterpret_cast<const char*>(range.data()), range.size());
181 class NoCompressionCodec final : public Codec {
183 static std::unique_ptr<Codec> create(int level, CodecType type);
184 explicit NoCompressionCodec(int level, CodecType type);
187 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
188 std::unique_ptr<IOBuf> doUncompress(
190 uint64_t uncompressedLength) override;
193 std::unique_ptr<Codec> NoCompressionCodec::create(int level, CodecType type) {
194 return make_unique<NoCompressionCodec>(level, type);
197 NoCompressionCodec::NoCompressionCodec(int level, CodecType type)
199 DCHECK(type == CodecType::NO_COMPRESSION);
201 case COMPRESSION_LEVEL_DEFAULT:
202 case COMPRESSION_LEVEL_FASTEST:
203 case COMPRESSION_LEVEL_BEST:
207 throw std::invalid_argument(to<std::string>(
208 "NoCompressionCodec: invalid level ", level));
212 std::unique_ptr<IOBuf> NoCompressionCodec::doCompress(
214 return data->clone();
217 std::unique_ptr<IOBuf> NoCompressionCodec::doUncompress(
219 uint64_t uncompressedLength) {
220 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
221 data->computeChainDataLength() != uncompressedLength) {
222 throw std::runtime_error(to<std::string>(
223 "NoCompressionCodec: invalid uncompressed length"));
225 return data->clone();
228 #if (FOLLY_HAVE_LIBLZ4 || FOLLY_HAVE_LIBLZMA)
232 void encodeVarintToIOBuf(uint64_t val, folly::IOBuf* out) {
233 DCHECK_GE(out->tailroom(), kMaxVarintLength64);
234 out->append(encodeVarint(val, out->writableTail()));
237 inline uint64_t decodeVarintFromCursor(folly::io::Cursor& cursor) {
240 for (int shift = 0; shift <= 63; shift += 7) {
241 b = cursor.read<int8_t>();
242 val |= static_cast<uint64_t>(b & 0x7f) << shift;
248 throw std::invalid_argument("Invalid varint value. Too big.");
255 #endif // FOLLY_HAVE_LIBLZ4 || FOLLY_HAVE_LIBLZMA
259 * Reads sizeof(T) bytes, and returns false if not enough bytes are available.
260 * Returns true if the first n bytes are equal to prefix when interpreted as
263 template <typename T>
264 typename std::enable_if<std::is_unsigned<T>::value, bool>::type
265 dataStartsWithLE(const IOBuf* data, T prefix, uint64_t n = sizeof(T)) {
267 DCHECK_LE(n, sizeof(T));
270 if (!cursor.tryReadLE(value)) {
273 const T mask = n == sizeof(T) ? T(-1) : (T(1) << (8 * n)) - 1;
274 return prefix == (value & mask);
277 template <typename T>
278 typename std::enable_if<std::is_arithmetic<T>::value, std::string>::type
279 prefixToStringLE(T prefix, uint64_t n = sizeof(T)) {
281 DCHECK_LE(n, sizeof(T));
282 prefix = Endian::little(prefix);
285 memcpy(&result[0], &prefix, n);
290 #if FOLLY_HAVE_LIBLZ4
295 class LZ4Codec final : public Codec {
297 static std::unique_ptr<Codec> create(int level, CodecType type);
298 explicit LZ4Codec(int level, CodecType type);
301 bool doNeedsUncompressedLength() const override;
302 uint64_t doMaxUncompressedLength() const override;
304 bool encodeSize() const { return type() == CodecType::LZ4_VARINT_SIZE; }
306 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
307 std::unique_ptr<IOBuf> doUncompress(
309 uint64_t uncompressedLength) override;
311 bool highCompression_;
314 std::unique_ptr<Codec> LZ4Codec::create(int level, CodecType type) {
315 return make_unique<LZ4Codec>(level, type);
318 LZ4Codec::LZ4Codec(int level, CodecType type) : Codec(type) {
319 DCHECK(type == CodecType::LZ4 || type == CodecType::LZ4_VARINT_SIZE);
322 case COMPRESSION_LEVEL_FASTEST:
323 case COMPRESSION_LEVEL_DEFAULT:
326 case COMPRESSION_LEVEL_BEST:
330 if (level < 1 || level > 2) {
331 throw std::invalid_argument(to<std::string>(
332 "LZ4Codec: invalid level: ", level));
334 highCompression_ = (level > 1);
337 bool LZ4Codec::doNeedsUncompressedLength() const {
338 return !encodeSize();
341 // The value comes from lz4.h in lz4-r117, but older versions of lz4 don't
342 // define LZ4_MAX_INPUT_SIZE (even though the max size is the same), so do it
344 #ifndef LZ4_MAX_INPUT_SIZE
345 # define LZ4_MAX_INPUT_SIZE 0x7E000000
348 uint64_t LZ4Codec::doMaxUncompressedLength() const {
349 return LZ4_MAX_INPUT_SIZE;
352 std::unique_ptr<IOBuf> LZ4Codec::doCompress(const IOBuf* data) {
354 if (data->isChained()) {
355 // LZ4 doesn't support streaming, so we have to coalesce
356 clone = data->cloneCoalescedAsValue();
360 uint32_t extraSize = encodeSize() ? kMaxVarintLength64 : 0;
361 auto out = IOBuf::create(extraSize + LZ4_compressBound(data->length()));
363 encodeVarintToIOBuf(data->length(), out.get());
367 auto input = reinterpret_cast<const char*>(data->data());
368 auto output = reinterpret_cast<char*>(out->writableTail());
369 const auto inputLength = data->length();
370 #if LZ4_VERSION_NUMBER >= 10700
371 if (highCompression_) {
372 n = LZ4_compress_HC(input, output, inputLength, out->tailroom(), 0);
374 n = LZ4_compress_default(input, output, inputLength, out->tailroom());
377 if (highCompression_) {
378 n = LZ4_compressHC(input, output, inputLength);
380 n = LZ4_compress(input, output, inputLength);
385 CHECK_LE(n, out->capacity());
391 std::unique_ptr<IOBuf> LZ4Codec::doUncompress(
393 uint64_t uncompressedLength) {
395 if (data->isChained()) {
396 // LZ4 doesn't support streaming, so we have to coalesce
397 clone = data->cloneCoalescedAsValue();
401 folly::io::Cursor cursor(data);
402 uint64_t actualUncompressedLength;
404 actualUncompressedLength = decodeVarintFromCursor(cursor);
405 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
406 uncompressedLength != actualUncompressedLength) {
407 throw std::runtime_error("LZ4Codec: invalid uncompressed length");
410 actualUncompressedLength = uncompressedLength;
411 if (actualUncompressedLength == UNKNOWN_UNCOMPRESSED_LENGTH ||
412 actualUncompressedLength > maxUncompressedLength()) {
413 throw std::runtime_error("LZ4Codec: invalid uncompressed length");
417 auto sp = StringPiece{cursor.peekBytes()};
418 auto out = IOBuf::create(actualUncompressedLength);
419 int n = LZ4_decompress_safe(
421 reinterpret_cast<char*>(out->writableTail()),
423 actualUncompressedLength);
425 if (n < 0 || uint64_t(n) != actualUncompressedLength) {
426 throw std::runtime_error(to<std::string>(
427 "LZ4 decompression returned invalid value ", n));
429 out->append(actualUncompressedLength);
433 #if LZ4_VERSION_NUMBER >= 10301
435 class LZ4FrameCodec final : public Codec {
437 static std::unique_ptr<Codec> create(int level, CodecType type);
438 explicit LZ4FrameCodec(int level, CodecType type);
441 std::vector<std::string> validPrefixes() const override;
442 bool canUncompress(const IOBuf* data, uint64_t uncompressedLength)
446 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
447 std::unique_ptr<IOBuf> doUncompress(
449 uint64_t uncompressedLength) override;
451 // Reset the dctx_ if it is dirty or null.
455 LZ4F_decompressionContext_t dctx_{nullptr};
459 /* static */ std::unique_ptr<Codec> LZ4FrameCodec::create(
462 return make_unique<LZ4FrameCodec>(level, type);
465 static constexpr uint32_t kLZ4FrameMagicLE = 0x184D2204;
467 std::vector<std::string> LZ4FrameCodec::validPrefixes() const {
468 return {prefixToStringLE(kLZ4FrameMagicLE)};
471 bool LZ4FrameCodec::canUncompress(const IOBuf* data, uint64_t) const {
472 return dataStartsWithLE(data, kLZ4FrameMagicLE);
475 static size_t lz4FrameThrowOnError(size_t code) {
476 if (LZ4F_isError(code)) {
477 throw std::runtime_error(
478 to<std::string>("LZ4Frame error: ", LZ4F_getErrorName(code)));
483 void LZ4FrameCodec::resetDCtx() {
484 if (dctx_ && !dirty_) {
488 LZ4F_freeDecompressionContext(dctx_);
490 lz4FrameThrowOnError(LZ4F_createDecompressionContext(&dctx_, 100));
494 LZ4FrameCodec::LZ4FrameCodec(int level, CodecType type) : Codec(type) {
495 DCHECK(type == CodecType::LZ4_FRAME);
497 case COMPRESSION_LEVEL_FASTEST:
498 case COMPRESSION_LEVEL_DEFAULT:
501 case COMPRESSION_LEVEL_BEST:
510 LZ4FrameCodec::~LZ4FrameCodec() {
512 LZ4F_freeDecompressionContext(dctx_);
516 std::unique_ptr<IOBuf> LZ4FrameCodec::doCompress(const IOBuf* data) {
517 // LZ4 Frame compression doesn't support streaming so we have to coalesce
519 if (data->isChained()) {
520 clone = data->cloneCoalescedAsValue();
524 const auto uncompressedLength = data->length();
525 LZ4F_preferences_t prefs{};
526 prefs.compressionLevel = level_;
527 prefs.frameInfo.contentSize = uncompressedLength;
529 auto buf = IOBuf::create(LZ4F_compressFrameBound(uncompressedLength, &prefs));
530 const size_t written = lz4FrameThrowOnError(LZ4F_compressFrame(
536 buf->append(written);
540 std::unique_ptr<IOBuf> LZ4FrameCodec::doUncompress(
542 uint64_t uncompressedLength) {
543 // Reset the dctx if any errors have occurred
546 ByteRange in = *data->begin();
548 if (data->isChained()) {
549 clone = data->cloneCoalescedAsValue();
550 in = clone.coalesce();
553 // Select decompression options
554 LZ4F_decompressOptions_t options;
555 options.stableDst = 1;
556 // Select blockSize and growthSize for the IOBufQueue
557 IOBufQueue queue(IOBufQueue::cacheChainLength());
558 auto blockSize = uint64_t{64} << 10;
559 auto growthSize = uint64_t{4} << 20;
560 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH) {
561 // Allocate uncompressedLength in one chunk (up to 64 MB)
562 const auto allocateSize = std::min(uncompressedLength, uint64_t{64} << 20);
563 queue.preallocate(allocateSize, allocateSize);
564 blockSize = std::min(uncompressedLength, blockSize);
565 growthSize = std::min(uncompressedLength, growthSize);
567 // Reduce growthSize for small data
568 const auto guessUncompressedLen = 4 * std::max(blockSize, in.size());
569 growthSize = std::min(guessUncompressedLen, growthSize);
571 // Once LZ4_decompress() is called, the dctx_ cannot be reused until it
574 // Decompress until the frame is over
577 // Allocate enough space to decompress at least a block
580 std::tie(out, outSize) = queue.preallocate(blockSize, growthSize);
582 size_t inSize = in.size();
583 code = lz4FrameThrowOnError(
584 LZ4F_decompress(dctx_, out, &outSize, in.data(), &inSize, &options));
585 if (in.empty() && outSize == 0 && code != 0) {
586 // We passed no input, no output was produced, and the frame isn't over
587 // No more forward progress is possible
588 throw std::runtime_error("LZ4Frame error: Incomplete frame");
590 in.uncheckedAdvance(inSize);
591 queue.postallocate(outSize);
593 // At this point the decompression context can be reused
595 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
596 queue.chainLength() != uncompressedLength) {
597 throw std::runtime_error("LZ4Frame error: Invalid uncompressedLength");
602 #endif // LZ4_VERSION_NUMBER >= 10301
603 #endif // FOLLY_HAVE_LIBLZ4
605 #if FOLLY_HAVE_LIBSNAPPY
612 * Implementation of snappy::Source that reads from a IOBuf chain.
614 class IOBufSnappySource final : public snappy::Source {
616 explicit IOBufSnappySource(const IOBuf* data);
617 size_t Available() const override;
618 const char* Peek(size_t* len) override;
619 void Skip(size_t n) override;
625 IOBufSnappySource::IOBufSnappySource(const IOBuf* data)
626 : available_(data->computeChainDataLength()),
630 size_t IOBufSnappySource::Available() const {
634 const char* IOBufSnappySource::Peek(size_t* len) {
635 auto sp = StringPiece{cursor_.peekBytes()};
640 void IOBufSnappySource::Skip(size_t n) {
641 CHECK_LE(n, available_);
646 class SnappyCodec final : public Codec {
648 static std::unique_ptr<Codec> create(int level, CodecType type);
649 explicit SnappyCodec(int level, CodecType type);
652 uint64_t doMaxUncompressedLength() const override;
653 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
654 std::unique_ptr<IOBuf> doUncompress(
656 uint64_t uncompressedLength) override;
659 std::unique_ptr<Codec> SnappyCodec::create(int level, CodecType type) {
660 return make_unique<SnappyCodec>(level, type);
663 SnappyCodec::SnappyCodec(int level, CodecType type) : Codec(type) {
664 DCHECK(type == CodecType::SNAPPY);
666 case COMPRESSION_LEVEL_FASTEST:
667 case COMPRESSION_LEVEL_DEFAULT:
668 case COMPRESSION_LEVEL_BEST:
672 throw std::invalid_argument(to<std::string>(
673 "SnappyCodec: invalid level: ", level));
677 uint64_t SnappyCodec::doMaxUncompressedLength() const {
678 // snappy.h uses uint32_t for lengths, so there's that.
679 return std::numeric_limits<uint32_t>::max();
682 std::unique_ptr<IOBuf> SnappyCodec::doCompress(const IOBuf* data) {
683 IOBufSnappySource source(data);
685 IOBuf::create(snappy::MaxCompressedLength(source.Available()));
687 snappy::UncheckedByteArraySink sink(reinterpret_cast<char*>(
688 out->writableTail()));
690 size_t n = snappy::Compress(&source, &sink);
692 CHECK_LE(n, out->capacity());
697 std::unique_ptr<IOBuf> SnappyCodec::doUncompress(const IOBuf* data,
698 uint64_t uncompressedLength) {
699 uint32_t actualUncompressedLength = 0;
702 IOBufSnappySource source(data);
703 if (!snappy::GetUncompressedLength(&source, &actualUncompressedLength)) {
704 throw std::runtime_error("snappy::GetUncompressedLength failed");
706 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
707 uncompressedLength != actualUncompressedLength) {
708 throw std::runtime_error("snappy: invalid uncompressed length");
712 auto out = IOBuf::create(actualUncompressedLength);
715 IOBufSnappySource source(data);
716 if (!snappy::RawUncompress(&source,
717 reinterpret_cast<char*>(out->writableTail()))) {
718 throw std::runtime_error("snappy::RawUncompress failed");
722 out->append(actualUncompressedLength);
726 #endif // FOLLY_HAVE_LIBSNAPPY
732 class ZlibCodec final : public Codec {
734 static std::unique_ptr<Codec> create(int level, CodecType type);
735 explicit ZlibCodec(int level, CodecType type);
737 std::vector<std::string> validPrefixes() const override;
738 bool canUncompress(const IOBuf* data, uint64_t uncompressedLength)
742 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
743 std::unique_ptr<IOBuf> doUncompress(
745 uint64_t uncompressedLength) override;
747 std::unique_ptr<IOBuf> addOutputBuffer(z_stream* stream, uint32_t length);
748 bool doInflate(z_stream* stream, IOBuf* head, uint32_t bufferLength);
753 static constexpr uint16_t kGZIPMagicLE = 0x8B1F;
755 std::vector<std::string> ZlibCodec::validPrefixes() const {
756 if (type() == CodecType::ZLIB) {
757 // Zlib streams start with a 2 byte header.
764 // We won't restrict the values of any sub-fields except as described below.
766 // The lowest 4 bits of CMF is the compression method (CM).
767 // CM == 0x8 is the deflate compression method, which is currently the only
768 // supported compression method, so any valid prefix must have CM == 0x8.
770 // The lowest 5 bits of FLG is FCHECK.
771 // FCHECK must be such that the two header bytes are a multiple of 31 when
772 // interpreted as a big endian 16-bit number.
773 std::vector<std::string> result;
774 // 16 values for the first byte, 8 values for the second byte.
775 // There are also 4 combinations where both 0x00 and 0x1F work as FCHECK.
777 // Select all values for the CMF byte that use the deflate algorithm 0x8.
778 for (uint32_t first = 0x0800; first <= 0xF800; first += 0x1000) {
779 // Select all values for the FLG, but leave FCHECK as 0 since it's fixed.
780 for (uint32_t second = 0x00; second <= 0xE0; second += 0x20) {
781 uint16_t prefix = first | second;
783 prefix += 31 - (prefix % 31);
784 result.push_back(prefixToStringLE(Endian::big(prefix)));
785 // zlib won't produce this, but it is a valid prefix.
786 if ((prefix & 0x1F) == 31) {
788 result.push_back(prefixToStringLE(Endian::big(prefix)));
794 // The gzip frame starts with 2 magic bytes.
795 return {prefixToStringLE(kGZIPMagicLE)};
799 bool ZlibCodec::canUncompress(const IOBuf* data, uint64_t) const {
800 if (type() == CodecType::ZLIB) {
803 if (!cursor.tryReadBE(value)) {
806 // zlib compressed if using deflate and is a multiple of 31.
807 return (value & 0x0F00) == 0x0800 && value % 31 == 0;
809 return dataStartsWithLE(data, kGZIPMagicLE);
813 std::unique_ptr<Codec> ZlibCodec::create(int level, CodecType type) {
814 return make_unique<ZlibCodec>(level, type);
817 ZlibCodec::ZlibCodec(int level, CodecType type) : Codec(type) {
818 DCHECK(type == CodecType::ZLIB || type == CodecType::GZIP);
820 case COMPRESSION_LEVEL_FASTEST:
823 case COMPRESSION_LEVEL_DEFAULT:
824 level = Z_DEFAULT_COMPRESSION;
826 case COMPRESSION_LEVEL_BEST:
830 if (level != Z_DEFAULT_COMPRESSION && (level < 0 || level > 9)) {
831 throw std::invalid_argument(to<std::string>(
832 "ZlibCodec: invalid level: ", level));
837 std::unique_ptr<IOBuf> ZlibCodec::addOutputBuffer(z_stream* stream,
839 CHECK_EQ(stream->avail_out, 0);
841 auto buf = IOBuf::create(length);
844 stream->next_out = buf->writableData();
845 stream->avail_out = buf->length();
850 bool ZlibCodec::doInflate(z_stream* stream,
852 uint32_t bufferLength) {
853 if (stream->avail_out == 0) {
854 head->prependChain(addOutputBuffer(stream, bufferLength));
857 int rc = inflate(stream, Z_NO_FLUSH);
868 throw std::runtime_error(to<std::string>(
869 "ZlibCodec: inflate error: ", rc, ": ", stream->msg));
871 CHECK(false) << rc << ": " << stream->msg;
877 std::unique_ptr<IOBuf> ZlibCodec::doCompress(const IOBuf* data) {
879 stream.zalloc = nullptr;
880 stream.zfree = nullptr;
881 stream.opaque = nullptr;
883 // Using deflateInit2() to support gzip. "The windowBits parameter is the
884 // base two logarithm of the maximum window size (...) The default value is
885 // 15 (...) Add 16 to windowBits to write a simple gzip header and trailer
886 // around the compressed data instead of a zlib wrapper. The gzip header
887 // will have no file name, no extra data, no comment, no modification time
888 // (set to zero), no header crc, and the operating system will be set to 255
890 int windowBits = 15 + (type() == CodecType::GZIP ? 16 : 0);
891 // All other parameters (method, memLevel, strategy) get default values from
893 int rc = deflateInit2(&stream,
900 throw std::runtime_error(to<std::string>(
901 "ZlibCodec: deflateInit error: ", rc, ": ", stream.msg));
904 stream.next_in = stream.next_out = nullptr;
905 stream.avail_in = stream.avail_out = 0;
906 stream.total_in = stream.total_out = 0;
908 bool success = false;
911 rc = deflateEnd(&stream);
912 // If we're here because of an exception, it's okay if some data
914 CHECK(rc == Z_OK || (!success && rc == Z_DATA_ERROR))
915 << rc << ": " << stream.msg;
918 uint64_t uncompressedLength = data->computeChainDataLength();
919 uint64_t maxCompressedLength = deflateBound(&stream, uncompressedLength);
921 // Max 64MiB in one go
922 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
923 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
925 auto out = addOutputBuffer(
927 (maxCompressedLength <= maxSingleStepLength ?
928 maxCompressedLength :
929 defaultBufferLength));
931 for (auto& range : *data) {
932 uint64_t remaining = range.size();
933 uint64_t written = 0;
935 uint32_t step = (remaining > maxSingleStepLength ?
936 maxSingleStepLength : remaining);
937 stream.next_in = const_cast<uint8_t*>(range.data() + written);
938 stream.avail_in = step;
942 while (stream.avail_in != 0) {
943 if (stream.avail_out == 0) {
944 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
947 rc = deflate(&stream, Z_NO_FLUSH);
949 CHECK_EQ(rc, Z_OK) << stream.msg;
955 if (stream.avail_out == 0) {
956 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
959 rc = deflate(&stream, Z_FINISH);
960 } while (rc == Z_OK);
962 CHECK_EQ(rc, Z_STREAM_END) << stream.msg;
964 out->prev()->trimEnd(stream.avail_out);
966 success = true; // we survived
971 static uint64_t computeBufferLength(uint64_t const compressedLength) {
972 constexpr uint64_t kMaxBufferLength = uint64_t(4) << 20; // 4 MiB
973 constexpr uint64_t kBlockSize = uint64_t(32) << 10; // 32 KiB
974 const uint64_t goodBufferSize = 4 * std::max(kBlockSize, compressedLength);
975 return std::min(goodBufferSize, kMaxBufferLength);
978 std::unique_ptr<IOBuf> ZlibCodec::doUncompress(const IOBuf* data,
979 uint64_t uncompressedLength) {
981 stream.zalloc = nullptr;
982 stream.zfree = nullptr;
983 stream.opaque = nullptr;
985 // "The windowBits parameter is the base two logarithm of the maximum window
986 // size (...) The default value is 15 (...) add 16 to decode only the gzip
987 // format (the zlib format will return a Z_DATA_ERROR)."
988 int windowBits = 15 + (type() == CodecType::GZIP ? 16 : 0);
989 int rc = inflateInit2(&stream, windowBits);
991 throw std::runtime_error(to<std::string>(
992 "ZlibCodec: inflateInit error: ", rc, ": ", stream.msg));
995 stream.next_in = stream.next_out = nullptr;
996 stream.avail_in = stream.avail_out = 0;
997 stream.total_in = stream.total_out = 0;
999 bool success = false;
1002 rc = inflateEnd(&stream);
1003 // If we're here because of an exception, it's okay if some data
1005 CHECK(rc == Z_OK || (!success && rc == Z_DATA_ERROR))
1006 << rc << ": " << stream.msg;
1009 // Max 64MiB in one go
1010 constexpr uint64_t maxSingleStepLength = uint64_t(64) << 20; // 64MiB
1011 const uint64_t defaultBufferLength =
1012 computeBufferLength(data->computeChainDataLength());
1014 auto out = addOutputBuffer(
1016 ((uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
1017 uncompressedLength <= maxSingleStepLength) ?
1018 uncompressedLength :
1019 defaultBufferLength));
1021 bool streamEnd = false;
1022 for (auto& range : *data) {
1023 if (range.empty()) {
1027 stream.next_in = const_cast<uint8_t*>(range.data());
1028 stream.avail_in = range.size();
1030 while (stream.avail_in != 0) {
1032 throw std::runtime_error(to<std::string>(
1033 "ZlibCodec: junk after end of data"));
1036 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
1040 while (!streamEnd) {
1041 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
1044 out->prev()->trimEnd(stream.avail_out);
1046 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
1047 uncompressedLength != stream.total_out) {
1048 throw std::runtime_error(to<std::string>(
1049 "ZlibCodec: invalid uncompressed length"));
1052 success = true; // we survived
1057 #endif // FOLLY_HAVE_LIBZ
1059 #if FOLLY_HAVE_LIBLZMA
1064 class LZMA2Codec final : public Codec {
1066 static std::unique_ptr<Codec> create(int level, CodecType type);
1067 explicit LZMA2Codec(int level, CodecType type);
1069 std::vector<std::string> validPrefixes() const override;
1070 bool canUncompress(const IOBuf* data, uint64_t uncompressedLength)
1074 bool doNeedsUncompressedLength() const override;
1075 uint64_t doMaxUncompressedLength() const override;
1077 bool encodeSize() const { return type() == CodecType::LZMA2_VARINT_SIZE; }
1079 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
1080 std::unique_ptr<IOBuf> doUncompress(
1082 uint64_t uncompressedLength) override;
1084 std::unique_ptr<IOBuf> addOutputBuffer(lzma_stream* stream, size_t length);
1085 bool doInflate(lzma_stream* stream, IOBuf* head, size_t bufferLength);
1090 static constexpr uint64_t kLZMA2MagicLE = 0x005A587A37FD;
1091 static constexpr unsigned kLZMA2MagicBytes = 6;
1093 std::vector<std::string> LZMA2Codec::validPrefixes() const {
1094 if (type() == CodecType::LZMA2_VARINT_SIZE) {
1097 return {prefixToStringLE(kLZMA2MagicLE, kLZMA2MagicBytes)};
1100 bool LZMA2Codec::canUncompress(const IOBuf* data, uint64_t) const {
1101 if (type() == CodecType::LZMA2_VARINT_SIZE) {
1104 // Returns false for all inputs less than 8 bytes.
1105 // This is okay, because no valid LZMA2 streams are less than 8 bytes.
1106 return dataStartsWithLE(data, kLZMA2MagicLE, kLZMA2MagicBytes);
1109 std::unique_ptr<Codec> LZMA2Codec::create(int level, CodecType type) {
1110 return make_unique<LZMA2Codec>(level, type);
1113 LZMA2Codec::LZMA2Codec(int level, CodecType type) : Codec(type) {
1114 DCHECK(type == CodecType::LZMA2 || type == CodecType::LZMA2_VARINT_SIZE);
1116 case COMPRESSION_LEVEL_FASTEST:
1119 case COMPRESSION_LEVEL_DEFAULT:
1120 level = LZMA_PRESET_DEFAULT;
1122 case COMPRESSION_LEVEL_BEST:
1126 if (level < 0 || level > 9) {
1127 throw std::invalid_argument(to<std::string>(
1128 "LZMA2Codec: invalid level: ", level));
1133 bool LZMA2Codec::doNeedsUncompressedLength() const {
1137 uint64_t LZMA2Codec::doMaxUncompressedLength() const {
1138 // From lzma/base.h: "Stream is roughly 8 EiB (2^63 bytes)"
1139 return uint64_t(1) << 63;
1142 std::unique_ptr<IOBuf> LZMA2Codec::addOutputBuffer(
1143 lzma_stream* stream,
1146 CHECK_EQ(stream->avail_out, 0);
1148 auto buf = IOBuf::create(length);
1149 buf->append(length);
1151 stream->next_out = buf->writableData();
1152 stream->avail_out = buf->length();
1157 std::unique_ptr<IOBuf> LZMA2Codec::doCompress(const IOBuf* data) {
1159 lzma_stream stream = LZMA_STREAM_INIT;
1161 rc = lzma_easy_encoder(&stream, level_, LZMA_CHECK_NONE);
1162 if (rc != LZMA_OK) {
1163 throw std::runtime_error(folly::to<std::string>(
1164 "LZMA2Codec: lzma_easy_encoder error: ", rc));
1167 SCOPE_EXIT { lzma_end(&stream); };
1169 uint64_t uncompressedLength = data->computeChainDataLength();
1170 uint64_t maxCompressedLength = lzma_stream_buffer_bound(uncompressedLength);
1172 // Max 64MiB in one go
1173 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
1174 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
1176 auto out = addOutputBuffer(
1178 (maxCompressedLength <= maxSingleStepLength ?
1179 maxCompressedLength :
1180 defaultBufferLength));
1183 auto size = IOBuf::createCombined(kMaxVarintLength64);
1184 encodeVarintToIOBuf(uncompressedLength, size.get());
1185 size->appendChain(std::move(out));
1186 out = std::move(size);
1189 for (auto& range : *data) {
1190 if (range.empty()) {
1194 stream.next_in = const_cast<uint8_t*>(range.data());
1195 stream.avail_in = range.size();
1197 while (stream.avail_in != 0) {
1198 if (stream.avail_out == 0) {
1199 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
1202 rc = lzma_code(&stream, LZMA_RUN);
1204 if (rc != LZMA_OK) {
1205 throw std::runtime_error(folly::to<std::string>(
1206 "LZMA2Codec: lzma_code error: ", rc));
1212 if (stream.avail_out == 0) {
1213 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
1216 rc = lzma_code(&stream, LZMA_FINISH);
1217 } while (rc == LZMA_OK);
1219 if (rc != LZMA_STREAM_END) {
1220 throw std::runtime_error(folly::to<std::string>(
1221 "LZMA2Codec: lzma_code ended with error: ", rc));
1224 out->prev()->trimEnd(stream.avail_out);
1229 bool LZMA2Codec::doInflate(lzma_stream* stream,
1231 size_t bufferLength) {
1232 if (stream->avail_out == 0) {
1233 head->prependChain(addOutputBuffer(stream, bufferLength));
1236 lzma_ret rc = lzma_code(stream, LZMA_RUN);
1241 case LZMA_STREAM_END:
1244 throw std::runtime_error(to<std::string>(
1245 "LZMA2Codec: lzma_code error: ", rc));
1251 std::unique_ptr<IOBuf> LZMA2Codec::doUncompress(const IOBuf* data,
1252 uint64_t uncompressedLength) {
1254 lzma_stream stream = LZMA_STREAM_INIT;
1256 rc = lzma_auto_decoder(&stream, std::numeric_limits<uint64_t>::max(), 0);
1257 if (rc != LZMA_OK) {
1258 throw std::runtime_error(folly::to<std::string>(
1259 "LZMA2Codec: lzma_auto_decoder error: ", rc));
1262 SCOPE_EXIT { lzma_end(&stream); };
1264 // Max 64MiB in one go
1265 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
1266 constexpr uint32_t defaultBufferLength = uint32_t(256) << 10; // 256 KiB
1268 folly::io::Cursor cursor(data);
1270 const uint64_t actualUncompressedLength = decodeVarintFromCursor(cursor);
1271 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
1272 uncompressedLength != actualUncompressedLength) {
1273 throw std::runtime_error("LZMA2Codec: invalid uncompressed length");
1275 uncompressedLength = actualUncompressedLength;
1278 auto out = addOutputBuffer(
1280 ((uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
1281 uncompressedLength <= maxSingleStepLength)
1282 ? uncompressedLength
1283 : defaultBufferLength));
1285 bool streamEnd = false;
1286 auto buf = cursor.peekBytes();
1287 while (!buf.empty()) {
1288 stream.next_in = const_cast<uint8_t*>(buf.data());
1289 stream.avail_in = buf.size();
1291 while (stream.avail_in != 0) {
1293 throw std::runtime_error(to<std::string>(
1294 "LZMA2Codec: junk after end of data"));
1297 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
1300 cursor.skip(buf.size());
1301 buf = cursor.peekBytes();
1304 while (!streamEnd) {
1305 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
1308 out->prev()->trimEnd(stream.avail_out);
1310 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
1311 uncompressedLength != stream.total_out) {
1312 throw std::runtime_error(
1313 to<std::string>("LZMA2Codec: invalid uncompressed length"));
1319 #endif // FOLLY_HAVE_LIBLZMA
1321 #ifdef FOLLY_HAVE_LIBZSTD
1326 class ZSTDCodec final : public Codec {
1328 static std::unique_ptr<Codec> create(int level, CodecType);
1329 explicit ZSTDCodec(int level, CodecType type);
1331 std::vector<std::string> validPrefixes() const override;
1332 bool canUncompress(const IOBuf* data, uint64_t uncompressedLength)
1336 bool doNeedsUncompressedLength() const override;
1337 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
1338 std::unique_ptr<IOBuf> doUncompress(
1340 uint64_t uncompressedLength) override;
1345 static constexpr uint32_t kZSTDMagicLE = 0xFD2FB528;
1347 std::vector<std::string> ZSTDCodec::validPrefixes() const {
1348 return {prefixToStringLE(kZSTDMagicLE)};
1351 bool ZSTDCodec::canUncompress(const IOBuf* data, uint64_t) const {
1352 return dataStartsWithLE(data, kZSTDMagicLE);
1355 std::unique_ptr<Codec> ZSTDCodec::create(int level, CodecType type) {
1356 return make_unique<ZSTDCodec>(level, type);
1359 ZSTDCodec::ZSTDCodec(int level, CodecType type) : Codec(type) {
1360 DCHECK(type == CodecType::ZSTD);
1362 case COMPRESSION_LEVEL_FASTEST:
1365 case COMPRESSION_LEVEL_DEFAULT:
1368 case COMPRESSION_LEVEL_BEST:
1372 if (level < 1 || level > ZSTD_maxCLevel()) {
1373 throw std::invalid_argument(
1374 to<std::string>("ZSTD: invalid level: ", level));
1379 bool ZSTDCodec::doNeedsUncompressedLength() const {
1383 void zstdThrowIfError(size_t rc) {
1384 if (!ZSTD_isError(rc)) {
1387 throw std::runtime_error(
1388 to<std::string>("ZSTD returned an error: ", ZSTD_getErrorName(rc)));
1391 std::unique_ptr<IOBuf> ZSTDCodec::doCompress(const IOBuf* data) {
1392 // Support earlier versions of the codec (working with a single IOBuf,
1393 // and using ZSTD_decompress which requires ZSTD frame to contain size,
1394 // which isn't populated by streaming API).
1395 if (!data->isChained()) {
1396 auto out = IOBuf::createCombined(ZSTD_compressBound(data->length()));
1397 const auto rc = ZSTD_compress(
1398 out->writableData(),
1403 zstdThrowIfError(rc);
1408 auto zcs = ZSTD_createCStream();
1410 ZSTD_freeCStream(zcs);
1413 auto rc = ZSTD_initCStream(zcs, level_);
1414 zstdThrowIfError(rc);
1416 Cursor cursor(data);
1417 auto result = IOBuf::createCombined(ZSTD_compressBound(cursor.totalLength()));
1420 out.dst = result->writableTail();
1421 out.size = result->capacity();
1424 for (auto buffer = cursor.peekBytes(); !buffer.empty();) {
1426 in.src = buffer.data();
1427 in.size = buffer.size();
1428 for (in.pos = 0; in.pos != in.size;) {
1429 rc = ZSTD_compressStream(zcs, &out, &in);
1430 zstdThrowIfError(rc);
1432 cursor.skip(in.size);
1433 buffer = cursor.peekBytes();
1436 rc = ZSTD_endStream(zcs, &out);
1437 zstdThrowIfError(rc);
1440 result->append(out.pos);
1444 static std::unique_ptr<IOBuf> zstdUncompressBuffer(
1446 uint64_t uncompressedLength) {
1447 // Check preconditions
1448 DCHECK(!data->isChained());
1449 DCHECK(uncompressedLength != Codec::UNKNOWN_UNCOMPRESSED_LENGTH);
1451 auto uncompressed = IOBuf::create(uncompressedLength);
1452 const auto decompressedSize = ZSTD_decompress(
1453 uncompressed->writableTail(),
1454 uncompressed->tailroom(),
1457 zstdThrowIfError(decompressedSize);
1458 if (decompressedSize != uncompressedLength) {
1459 throw std::runtime_error("ZSTD: invalid uncompressed length");
1461 uncompressed->append(decompressedSize);
1462 return uncompressed;
1465 static std::unique_ptr<IOBuf> zstdUncompressStream(
1467 uint64_t uncompressedLength) {
1468 auto zds = ZSTD_createDStream();
1470 ZSTD_freeDStream(zds);
1473 auto rc = ZSTD_initDStream(zds);
1474 zstdThrowIfError(rc);
1476 ZSTD_outBuffer out{};
1479 auto outputSize = ZSTD_DStreamOutSize();
1480 if (uncompressedLength != Codec::UNKNOWN_UNCOMPRESSED_LENGTH) {
1481 outputSize = uncompressedLength;
1484 IOBufQueue queue(IOBufQueue::cacheChainLength());
1486 Cursor cursor(data);
1488 if (in.pos == in.size) {
1489 auto buffer = cursor.peekBytes();
1490 in.src = buffer.data();
1491 in.size = buffer.size();
1493 cursor.skip(in.size);
1494 if (rc > 1 && in.size == 0) {
1495 throw std::runtime_error(to<std::string>("ZSTD: incomplete input"));
1498 if (out.pos == out.size) {
1500 queue.postallocate(out.pos);
1502 auto buffer = queue.preallocate(outputSize, outputSize);
1503 out.dst = buffer.first;
1504 out.size = buffer.second;
1506 outputSize = ZSTD_DStreamOutSize();
1508 rc = ZSTD_decompressStream(zds, &out, &in);
1509 zstdThrowIfError(rc);
1515 queue.postallocate(out.pos);
1517 if (in.pos != in.size || !cursor.isAtEnd()) {
1518 throw std::runtime_error("ZSTD: junk after end of data");
1520 if (uncompressedLength != Codec::UNKNOWN_UNCOMPRESSED_LENGTH &&
1521 queue.chainLength() != uncompressedLength) {
1522 throw std::runtime_error("ZSTD: invalid uncompressed length");
1525 return queue.move();
1528 std::unique_ptr<IOBuf> ZSTDCodec::doUncompress(
1530 uint64_t uncompressedLength) {
1532 // Read decompressed size from frame if available in first IOBuf.
1533 const auto decompressedSize =
1534 ZSTD_getDecompressedSize(data->data(), data->length());
1535 if (decompressedSize != 0) {
1536 if (uncompressedLength != Codec::UNKNOWN_UNCOMPRESSED_LENGTH &&
1537 uncompressedLength != decompressedSize) {
1538 throw std::runtime_error("ZSTD: invalid uncompressed length");
1540 uncompressedLength = decompressedSize;
1543 // Faster to decompress using ZSTD_decompress() if we can.
1544 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH && !data->isChained()) {
1545 return zstdUncompressBuffer(data, uncompressedLength);
1547 // Fall back to slower streaming decompression.
1548 return zstdUncompressStream(data, uncompressedLength);
1551 #endif // FOLLY_HAVE_LIBZSTD
1554 * Automatic decompression
1556 class AutomaticCodec final : public Codec {
1558 static std::unique_ptr<Codec> create(
1559 std::vector<std::unique_ptr<Codec>> customCodecs);
1560 explicit AutomaticCodec(std::vector<std::unique_ptr<Codec>> customCodecs);
1562 std::vector<std::string> validPrefixes() const override;
1563 bool canUncompress(const IOBuf* data, uint64_t uncompressedLength)
1567 bool doNeedsUncompressedLength() const override;
1568 uint64_t doMaxUncompressedLength() const override;
1570 std::unique_ptr<IOBuf> doCompress(const IOBuf*) override {
1571 throw std::runtime_error("AutomaticCodec error: compress() not supported.");
1573 std::unique_ptr<IOBuf> doUncompress(
1575 uint64_t uncompressedLength) override;
1577 void addCodecIfSupported(CodecType type);
1579 // Throws iff the codecs aren't compatible (very slow)
1580 void checkCompatibleCodecs() const;
1582 std::vector<std::unique_ptr<Codec>> codecs_;
1583 bool needsUncompressedLength_;
1584 uint64_t maxUncompressedLength_;
1587 std::vector<std::string> AutomaticCodec::validPrefixes() const {
1588 std::unordered_set<std::string> prefixes;
1589 for (const auto& codec : codecs_) {
1590 const auto codecPrefixes = codec->validPrefixes();
1591 prefixes.insert(codecPrefixes.begin(), codecPrefixes.end());
1593 return std::vector<std::string>{prefixes.begin(), prefixes.end()};
1596 bool AutomaticCodec::canUncompress(
1598 uint64_t uncompressedLength) const {
1602 [data, uncompressedLength](std::unique_ptr<Codec> const& codec) {
1603 return codec->canUncompress(data, uncompressedLength);
1607 void AutomaticCodec::addCodecIfSupported(CodecType type) {
1608 const bool present = std::any_of(
1611 [&type](std::unique_ptr<Codec> const& codec) {
1612 return codec->type() == type;
1614 if (hasCodec(type) && !present) {
1615 codecs_.push_back(getCodec(type));
1619 /* static */ std::unique_ptr<Codec> AutomaticCodec::create(
1620 std::vector<std::unique_ptr<Codec>> customCodecs) {
1621 return make_unique<AutomaticCodec>(std::move(customCodecs));
1624 AutomaticCodec::AutomaticCodec(std::vector<std::unique_ptr<Codec>> customCodecs)
1625 : Codec(CodecType::USER_DEFINED), codecs_(std::move(customCodecs)) {
1626 // Fastest -> slowest
1627 addCodecIfSupported(CodecType::LZ4_FRAME);
1628 addCodecIfSupported(CodecType::ZSTD);
1629 addCodecIfSupported(CodecType::ZLIB);
1630 addCodecIfSupported(CodecType::GZIP);
1631 addCodecIfSupported(CodecType::LZMA2);
1633 checkCompatibleCodecs();
1635 // Check that none of the codes are are null
1636 DCHECK(std::none_of(
1637 codecs_.begin(), codecs_.end(), [](std::unique_ptr<Codec> const& codec) {
1638 return codec == nullptr;
1641 needsUncompressedLength_ = std::any_of(
1642 codecs_.begin(), codecs_.end(), [](std::unique_ptr<Codec> const& codec) {
1643 return codec->needsUncompressedLength();
1646 const auto it = std::max_element(
1649 [](std::unique_ptr<Codec> const& lhs, std::unique_ptr<Codec> const& rhs) {
1650 return lhs->maxUncompressedLength() < rhs->maxUncompressedLength();
1652 DCHECK(it != codecs_.end());
1653 maxUncompressedLength_ = (*it)->maxUncompressedLength();
1656 void AutomaticCodec::checkCompatibleCodecs() const {
1657 // Keep track of all the possible headers.
1658 std::unordered_set<std::string> headers;
1659 // The empty header is not allowed.
1662 // Construct a set of headers and check that none of the headers occur twice.
1663 // Eliminate edge cases.
1664 for (auto&& codec : codecs_) {
1665 const auto codecHeaders = codec->validPrefixes();
1666 // Codecs without any valid headers are not allowed.
1667 if (codecHeaders.empty()) {
1668 throw std::invalid_argument{
1669 "AutomaticCodec: validPrefixes() must not be empty."};
1671 // Insert all the headers for the current codec.
1672 const size_t beforeSize = headers.size();
1673 headers.insert(codecHeaders.begin(), codecHeaders.end());
1674 // Codecs are not compatible if any header occurred twice.
1675 if (beforeSize + codecHeaders.size() != headers.size()) {
1676 throw std::invalid_argument{
1677 "AutomaticCodec: Two valid prefixes collide."};
1681 // Check if any strict non-empty prefix of any header is a header.
1682 for (const auto& header : headers) {
1683 for (size_t i = 1; i < header.size(); ++i) {
1684 if (headers.count(header.substr(0, i))) {
1685 throw std::invalid_argument{
1686 "AutomaticCodec: One valid prefix is a prefix of another valid "
1693 bool AutomaticCodec::doNeedsUncompressedLength() const {
1694 return needsUncompressedLength_;
1697 uint64_t AutomaticCodec::doMaxUncompressedLength() const {
1698 return maxUncompressedLength_;
1701 std::unique_ptr<IOBuf> AutomaticCodec::doUncompress(
1703 uint64_t uncompressedLength) {
1704 for (auto&& codec : codecs_) {
1705 if (codec->canUncompress(data, uncompressedLength)) {
1706 return codec->uncompress(data, uncompressedLength);
1709 throw std::runtime_error("AutomaticCodec error: Unknown compressed data");
1714 typedef std::unique_ptr<Codec> (*CodecFactory)(int, CodecType);
1715 static constexpr CodecFactory
1716 codecFactories[static_cast<size_t>(CodecType::NUM_CODEC_TYPES)] = {
1717 nullptr, // USER_DEFINED
1718 NoCompressionCodec::create,
1720 #if FOLLY_HAVE_LIBLZ4
1726 #if FOLLY_HAVE_LIBSNAPPY
1727 SnappyCodec::create,
1738 #if FOLLY_HAVE_LIBLZ4
1744 #if FOLLY_HAVE_LIBLZMA
1752 #if FOLLY_HAVE_LIBZSTD
1764 #if (FOLLY_HAVE_LIBLZ4 && LZ4_VERSION_NUMBER >= 10301)
1765 LZ4FrameCodec::create,
1771 bool hasCodec(CodecType type) {
1772 size_t idx = static_cast<size_t>(type);
1773 if (idx >= static_cast<size_t>(CodecType::NUM_CODEC_TYPES)) {
1774 throw std::invalid_argument(
1775 to<std::string>("Compression type ", idx, " invalid"));
1777 return codecFactories[idx] != nullptr;
1780 std::unique_ptr<Codec> getCodec(CodecType type, int level) {
1781 size_t idx = static_cast<size_t>(type);
1782 if (idx >= static_cast<size_t>(CodecType::NUM_CODEC_TYPES)) {
1783 throw std::invalid_argument(
1784 to<std::string>("Compression type ", idx, " invalid"));
1786 auto factory = codecFactories[idx];
1788 throw std::invalid_argument(to<std::string>(
1789 "Compression type ", idx, " not supported"));
1791 auto codec = (*factory)(level, type);
1792 DCHECK_EQ(static_cast<size_t>(codec->type()), idx);
1796 std::unique_ptr<Codec> getAutoUncompressionCodec(
1797 std::vector<std::unique_ptr<Codec>> customCodecs) {
1798 return AutomaticCodec::create(std::move(customCodecs));