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>
24 #include <glog/logging.h>
26 #if FOLLY_HAVE_LIBSNAPPY
28 #include <snappy-sinksource.h>
35 #if FOLLY_HAVE_LIBLZMA
39 #if FOLLY_HAVE_LIBZSTD
43 #include <folly/Conv.h>
44 #include <folly/Memory.h>
45 #include <folly/Portability.h>
46 #include <folly/ScopeGuard.h>
47 #include <folly/Varint.h>
48 #include <folly/io/Cursor.h>
50 namespace folly { namespace io {
52 Codec::Codec(CodecType type) : type_(type) { }
54 // Ensure consistent behavior in the nullptr case
55 std::unique_ptr<IOBuf> Codec::compress(const IOBuf* data) {
56 uint64_t len = data->computeChainDataLength();
58 return IOBuf::create(0);
60 if (len > maxUncompressedLength()) {
61 throw std::runtime_error("Codec: uncompressed length too large");
64 return doCompress(data);
67 std::string Codec::compress(const StringPiece data) {
68 const uint64_t len = data.size();
72 if (len > maxUncompressedLength()) {
73 throw std::runtime_error("Codec: uncompressed length too large");
76 return doCompressString(data);
79 std::unique_ptr<IOBuf> Codec::uncompress(const IOBuf* data,
80 uint64_t uncompressedLength) {
81 if (uncompressedLength == UNKNOWN_UNCOMPRESSED_LENGTH) {
82 if (needsUncompressedLength()) {
83 throw std::invalid_argument("Codec: uncompressed length required");
85 } else if (uncompressedLength > maxUncompressedLength()) {
86 throw std::runtime_error("Codec: uncompressed length too large");
90 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
91 uncompressedLength != 0) {
92 throw std::runtime_error("Codec: invalid uncompressed length");
94 return IOBuf::create(0);
97 return doUncompress(data, uncompressedLength);
100 std::string Codec::uncompress(
101 const StringPiece data,
102 uint64_t uncompressedLength) {
103 if (uncompressedLength == UNKNOWN_UNCOMPRESSED_LENGTH) {
104 if (needsUncompressedLength()) {
105 throw std::invalid_argument("Codec: uncompressed length required");
107 } else if (uncompressedLength > maxUncompressedLength()) {
108 throw std::runtime_error("Codec: uncompressed length too large");
112 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
113 uncompressedLength != 0) {
114 throw std::runtime_error("Codec: invalid uncompressed length");
119 return doUncompressString(data, uncompressedLength);
122 bool Codec::needsUncompressedLength() const {
123 return doNeedsUncompressedLength();
126 uint64_t Codec::maxUncompressedLength() const {
127 return doMaxUncompressedLength();
130 bool Codec::doNeedsUncompressedLength() const {
134 uint64_t Codec::doMaxUncompressedLength() const {
135 return UNLIMITED_UNCOMPRESSED_LENGTH;
138 std::string Codec::doCompressString(const StringPiece data) {
139 const IOBuf inputBuffer{IOBuf::WRAP_BUFFER, data};
140 auto outputBuffer = doCompress(&inputBuffer);
142 output.reserve(outputBuffer->computeChainDataLength());
143 for (auto range : *outputBuffer) {
144 output.append(reinterpret_cast<const char*>(range.data()), range.size());
149 std::string Codec::doUncompressString(
150 const StringPiece data,
151 uint64_t uncompressedLength) {
152 const IOBuf inputBuffer{IOBuf::WRAP_BUFFER, data};
153 auto outputBuffer = doUncompress(&inputBuffer, uncompressedLength);
155 output.reserve(outputBuffer->computeChainDataLength());
156 for (auto range : *outputBuffer) {
157 output.append(reinterpret_cast<const char*>(range.data()), range.size());
167 class NoCompressionCodec final : public Codec {
169 static std::unique_ptr<Codec> create(int level, CodecType type);
170 explicit NoCompressionCodec(int level, CodecType type);
173 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
174 std::unique_ptr<IOBuf> doUncompress(
176 uint64_t uncompressedLength) override;
179 std::unique_ptr<Codec> NoCompressionCodec::create(int level, CodecType type) {
180 return make_unique<NoCompressionCodec>(level, type);
183 NoCompressionCodec::NoCompressionCodec(int level, CodecType type)
185 DCHECK(type == CodecType::NO_COMPRESSION);
187 case COMPRESSION_LEVEL_DEFAULT:
188 case COMPRESSION_LEVEL_FASTEST:
189 case COMPRESSION_LEVEL_BEST:
193 throw std::invalid_argument(to<std::string>(
194 "NoCompressionCodec: invalid level ", level));
198 std::unique_ptr<IOBuf> NoCompressionCodec::doCompress(
200 return data->clone();
203 std::unique_ptr<IOBuf> NoCompressionCodec::doUncompress(
205 uint64_t uncompressedLength) {
206 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
207 data->computeChainDataLength() != uncompressedLength) {
208 throw std::runtime_error(to<std::string>(
209 "NoCompressionCodec: invalid uncompressed length"));
211 return data->clone();
214 #if (FOLLY_HAVE_LIBLZ4 || FOLLY_HAVE_LIBLZMA)
218 void encodeVarintToIOBuf(uint64_t val, folly::IOBuf* out) {
219 DCHECK_GE(out->tailroom(), kMaxVarintLength64);
220 out->append(encodeVarint(val, out->writableTail()));
223 inline uint64_t decodeVarintFromCursor(folly::io::Cursor& cursor) {
226 for (int shift = 0; shift <= 63; shift += 7) {
227 b = cursor.read<int8_t>();
228 val |= static_cast<uint64_t>(b & 0x7f) << shift;
234 throw std::invalid_argument("Invalid varint value. Too big.");
241 #endif // FOLLY_HAVE_LIBLZ4 || FOLLY_HAVE_LIBLZMA
243 #if FOLLY_HAVE_LIBLZ4
248 class LZ4Codec final : public Codec {
250 static std::unique_ptr<Codec> create(int level, CodecType type);
251 explicit LZ4Codec(int level, CodecType type);
254 bool doNeedsUncompressedLength() const override;
255 uint64_t doMaxUncompressedLength() const override;
257 bool encodeSize() const { return type() == CodecType::LZ4_VARINT_SIZE; }
259 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
260 std::unique_ptr<IOBuf> doUncompress(
262 uint64_t uncompressedLength) override;
264 bool highCompression_;
267 std::unique_ptr<Codec> LZ4Codec::create(int level, CodecType type) {
268 return make_unique<LZ4Codec>(level, type);
271 LZ4Codec::LZ4Codec(int level, CodecType type) : Codec(type) {
272 DCHECK(type == CodecType::LZ4 || type == CodecType::LZ4_VARINT_SIZE);
275 case COMPRESSION_LEVEL_FASTEST:
276 case COMPRESSION_LEVEL_DEFAULT:
279 case COMPRESSION_LEVEL_BEST:
283 if (level < 1 || level > 2) {
284 throw std::invalid_argument(to<std::string>(
285 "LZ4Codec: invalid level: ", level));
287 highCompression_ = (level > 1);
290 bool LZ4Codec::doNeedsUncompressedLength() const {
291 return !encodeSize();
294 // The value comes from lz4.h in lz4-r117, but older versions of lz4 don't
295 // define LZ4_MAX_INPUT_SIZE (even though the max size is the same), so do it
297 #ifndef LZ4_MAX_INPUT_SIZE
298 # define LZ4_MAX_INPUT_SIZE 0x7E000000
301 uint64_t LZ4Codec::doMaxUncompressedLength() const {
302 return LZ4_MAX_INPUT_SIZE;
305 std::unique_ptr<IOBuf> LZ4Codec::doCompress(const IOBuf* data) {
307 if (data->isChained()) {
308 // LZ4 doesn't support streaming, so we have to coalesce
309 clone = data->cloneCoalescedAsValue();
313 uint32_t extraSize = encodeSize() ? kMaxVarintLength64 : 0;
314 auto out = IOBuf::create(extraSize + LZ4_compressBound(data->length()));
316 encodeVarintToIOBuf(data->length(), out.get());
320 auto input = reinterpret_cast<const char*>(data->data());
321 auto output = reinterpret_cast<char*>(out->writableTail());
322 const auto inputLength = data->length();
323 #if LZ4_VERSION_NUMBER >= 10700
324 if (highCompression_) {
325 n = LZ4_compress_HC(input, output, inputLength, out->tailroom(), 0);
327 n = LZ4_compress_default(input, output, inputLength, out->tailroom());
330 if (highCompression_) {
331 n = LZ4_compressHC(input, output, inputLength);
333 n = LZ4_compress(input, output, inputLength);
338 CHECK_LE(n, out->capacity());
344 std::unique_ptr<IOBuf> LZ4Codec::doUncompress(
346 uint64_t uncompressedLength) {
348 if (data->isChained()) {
349 // LZ4 doesn't support streaming, so we have to coalesce
350 clone = data->cloneCoalescedAsValue();
354 folly::io::Cursor cursor(data);
355 uint64_t actualUncompressedLength;
357 actualUncompressedLength = decodeVarintFromCursor(cursor);
358 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
359 uncompressedLength != actualUncompressedLength) {
360 throw std::runtime_error("LZ4Codec: invalid uncompressed length");
363 actualUncompressedLength = uncompressedLength;
364 if (actualUncompressedLength == UNKNOWN_UNCOMPRESSED_LENGTH ||
365 actualUncompressedLength > maxUncompressedLength()) {
366 throw std::runtime_error("LZ4Codec: invalid uncompressed length");
370 auto sp = StringPiece{cursor.peekBytes()};
371 auto out = IOBuf::create(actualUncompressedLength);
372 int n = LZ4_decompress_safe(
374 reinterpret_cast<char*>(out->writableTail()),
376 actualUncompressedLength);
378 if (n < 0 || uint64_t(n) != actualUncompressedLength) {
379 throw std::runtime_error(to<std::string>(
380 "LZ4 decompression returned invalid value ", n));
382 out->append(actualUncompressedLength);
386 #endif // FOLLY_HAVE_LIBLZ4
388 #if FOLLY_HAVE_LIBSNAPPY
395 * Implementation of snappy::Source that reads from a IOBuf chain.
397 class IOBufSnappySource final : public snappy::Source {
399 explicit IOBufSnappySource(const IOBuf* data);
400 size_t Available() const override;
401 const char* Peek(size_t* len) override;
402 void Skip(size_t n) override;
408 IOBufSnappySource::IOBufSnappySource(const IOBuf* data)
409 : available_(data->computeChainDataLength()),
413 size_t IOBufSnappySource::Available() const {
417 const char* IOBufSnappySource::Peek(size_t* len) {
418 auto sp = StringPiece{cursor_.peekBytes()};
423 void IOBufSnappySource::Skip(size_t n) {
424 CHECK_LE(n, available_);
429 class SnappyCodec final : public Codec {
431 static std::unique_ptr<Codec> create(int level, CodecType type);
432 explicit SnappyCodec(int level, CodecType type);
435 uint64_t doMaxUncompressedLength() const override;
436 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
437 std::unique_ptr<IOBuf> doUncompress(
439 uint64_t uncompressedLength) override;
442 std::unique_ptr<Codec> SnappyCodec::create(int level, CodecType type) {
443 return make_unique<SnappyCodec>(level, type);
446 SnappyCodec::SnappyCodec(int level, CodecType type) : Codec(type) {
447 DCHECK(type == CodecType::SNAPPY);
449 case COMPRESSION_LEVEL_FASTEST:
450 case COMPRESSION_LEVEL_DEFAULT:
451 case COMPRESSION_LEVEL_BEST:
455 throw std::invalid_argument(to<std::string>(
456 "SnappyCodec: invalid level: ", level));
460 uint64_t SnappyCodec::doMaxUncompressedLength() const {
461 // snappy.h uses uint32_t for lengths, so there's that.
462 return std::numeric_limits<uint32_t>::max();
465 std::unique_ptr<IOBuf> SnappyCodec::doCompress(const IOBuf* data) {
466 IOBufSnappySource source(data);
468 IOBuf::create(snappy::MaxCompressedLength(source.Available()));
470 snappy::UncheckedByteArraySink sink(reinterpret_cast<char*>(
471 out->writableTail()));
473 size_t n = snappy::Compress(&source, &sink);
475 CHECK_LE(n, out->capacity());
480 std::unique_ptr<IOBuf> SnappyCodec::doUncompress(const IOBuf* data,
481 uint64_t uncompressedLength) {
482 uint32_t actualUncompressedLength = 0;
485 IOBufSnappySource source(data);
486 if (!snappy::GetUncompressedLength(&source, &actualUncompressedLength)) {
487 throw std::runtime_error("snappy::GetUncompressedLength failed");
489 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
490 uncompressedLength != actualUncompressedLength) {
491 throw std::runtime_error("snappy: invalid uncompressed length");
495 auto out = IOBuf::create(actualUncompressedLength);
498 IOBufSnappySource source(data);
499 if (!snappy::RawUncompress(&source,
500 reinterpret_cast<char*>(out->writableTail()))) {
501 throw std::runtime_error("snappy::RawUncompress failed");
505 out->append(actualUncompressedLength);
509 #endif // FOLLY_HAVE_LIBSNAPPY
515 class ZlibCodec final : public Codec {
517 static std::unique_ptr<Codec> create(int level, CodecType type);
518 explicit ZlibCodec(int level, CodecType type);
521 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
522 std::unique_ptr<IOBuf> doUncompress(
524 uint64_t uncompressedLength) override;
526 std::unique_ptr<IOBuf> addOutputBuffer(z_stream* stream, uint32_t length);
527 bool doInflate(z_stream* stream, IOBuf* head, uint32_t bufferLength);
532 std::unique_ptr<Codec> ZlibCodec::create(int level, CodecType type) {
533 return make_unique<ZlibCodec>(level, type);
536 ZlibCodec::ZlibCodec(int level, CodecType type) : Codec(type) {
537 DCHECK(type == CodecType::ZLIB || type == CodecType::GZIP);
539 case COMPRESSION_LEVEL_FASTEST:
542 case COMPRESSION_LEVEL_DEFAULT:
543 level = Z_DEFAULT_COMPRESSION;
545 case COMPRESSION_LEVEL_BEST:
549 if (level != Z_DEFAULT_COMPRESSION && (level < 0 || level > 9)) {
550 throw std::invalid_argument(to<std::string>(
551 "ZlibCodec: invalid level: ", level));
556 std::unique_ptr<IOBuf> ZlibCodec::addOutputBuffer(z_stream* stream,
558 CHECK_EQ(stream->avail_out, 0);
560 auto buf = IOBuf::create(length);
563 stream->next_out = buf->writableData();
564 stream->avail_out = buf->length();
569 bool ZlibCodec::doInflate(z_stream* stream,
571 uint32_t bufferLength) {
572 if (stream->avail_out == 0) {
573 head->prependChain(addOutputBuffer(stream, bufferLength));
576 int rc = inflate(stream, Z_NO_FLUSH);
587 throw std::runtime_error(to<std::string>(
588 "ZlibCodec: inflate error: ", rc, ": ", stream->msg));
590 CHECK(false) << rc << ": " << stream->msg;
596 std::unique_ptr<IOBuf> ZlibCodec::doCompress(const IOBuf* data) {
598 stream.zalloc = nullptr;
599 stream.zfree = nullptr;
600 stream.opaque = nullptr;
602 // Using deflateInit2() to support gzip. "The windowBits parameter is the
603 // base two logarithm of the maximum window size (...) The default value is
604 // 15 (...) Add 16 to windowBits to write a simple gzip header and trailer
605 // around the compressed data instead of a zlib wrapper. The gzip header
606 // will have no file name, no extra data, no comment, no modification time
607 // (set to zero), no header crc, and the operating system will be set to 255
609 int windowBits = 15 + (type() == CodecType::GZIP ? 16 : 0);
610 // All other parameters (method, memLevel, strategy) get default values from
612 int rc = deflateInit2(&stream,
619 throw std::runtime_error(to<std::string>(
620 "ZlibCodec: deflateInit error: ", rc, ": ", stream.msg));
623 stream.next_in = stream.next_out = nullptr;
624 stream.avail_in = stream.avail_out = 0;
625 stream.total_in = stream.total_out = 0;
627 bool success = false;
630 rc = deflateEnd(&stream);
631 // If we're here because of an exception, it's okay if some data
633 CHECK(rc == Z_OK || (!success && rc == Z_DATA_ERROR))
634 << rc << ": " << stream.msg;
637 uint64_t uncompressedLength = data->computeChainDataLength();
638 uint64_t maxCompressedLength = deflateBound(&stream, uncompressedLength);
640 // Max 64MiB in one go
641 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
642 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
644 auto out = addOutputBuffer(
646 (maxCompressedLength <= maxSingleStepLength ?
647 maxCompressedLength :
648 defaultBufferLength));
650 for (auto& range : *data) {
651 uint64_t remaining = range.size();
652 uint64_t written = 0;
654 uint32_t step = (remaining > maxSingleStepLength ?
655 maxSingleStepLength : remaining);
656 stream.next_in = const_cast<uint8_t*>(range.data() + written);
657 stream.avail_in = step;
661 while (stream.avail_in != 0) {
662 if (stream.avail_out == 0) {
663 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
666 rc = deflate(&stream, Z_NO_FLUSH);
668 CHECK_EQ(rc, Z_OK) << stream.msg;
674 if (stream.avail_out == 0) {
675 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
678 rc = deflate(&stream, Z_FINISH);
679 } while (rc == Z_OK);
681 CHECK_EQ(rc, Z_STREAM_END) << stream.msg;
683 out->prev()->trimEnd(stream.avail_out);
685 success = true; // we survived
690 std::unique_ptr<IOBuf> ZlibCodec::doUncompress(const IOBuf* data,
691 uint64_t uncompressedLength) {
693 stream.zalloc = nullptr;
694 stream.zfree = nullptr;
695 stream.opaque = nullptr;
697 // "The windowBits parameter is the base two logarithm of the maximum window
698 // size (...) The default value is 15 (...) add 16 to decode only the gzip
699 // format (the zlib format will return a Z_DATA_ERROR)."
700 int windowBits = 15 + (type() == CodecType::GZIP ? 16 : 0);
701 int rc = inflateInit2(&stream, windowBits);
703 throw std::runtime_error(to<std::string>(
704 "ZlibCodec: inflateInit error: ", rc, ": ", stream.msg));
707 stream.next_in = stream.next_out = nullptr;
708 stream.avail_in = stream.avail_out = 0;
709 stream.total_in = stream.total_out = 0;
711 bool success = false;
714 rc = inflateEnd(&stream);
715 // If we're here because of an exception, it's okay if some data
717 CHECK(rc == Z_OK || (!success && rc == Z_DATA_ERROR))
718 << rc << ": " << stream.msg;
721 // Max 64MiB in one go
722 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
723 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
725 auto out = addOutputBuffer(
727 ((uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
728 uncompressedLength <= maxSingleStepLength) ?
730 defaultBufferLength));
732 bool streamEnd = false;
733 for (auto& range : *data) {
738 stream.next_in = const_cast<uint8_t*>(range.data());
739 stream.avail_in = range.size();
741 while (stream.avail_in != 0) {
743 throw std::runtime_error(to<std::string>(
744 "ZlibCodec: junk after end of data"));
747 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
752 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
755 out->prev()->trimEnd(stream.avail_out);
757 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
758 uncompressedLength != stream.total_out) {
759 throw std::runtime_error(to<std::string>(
760 "ZlibCodec: invalid uncompressed length"));
763 success = true; // we survived
768 #endif // FOLLY_HAVE_LIBZ
770 #if FOLLY_HAVE_LIBLZMA
775 class LZMA2Codec final : public Codec {
777 static std::unique_ptr<Codec> create(int level, CodecType type);
778 explicit LZMA2Codec(int level, CodecType type);
781 bool doNeedsUncompressedLength() const override;
782 uint64_t doMaxUncompressedLength() const override;
784 bool encodeSize() const { return type() == CodecType::LZMA2_VARINT_SIZE; }
786 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
787 std::unique_ptr<IOBuf> doUncompress(
789 uint64_t uncompressedLength) override;
791 std::unique_ptr<IOBuf> addOutputBuffer(lzma_stream* stream, size_t length);
792 bool doInflate(lzma_stream* stream, IOBuf* head, size_t bufferLength);
797 std::unique_ptr<Codec> LZMA2Codec::create(int level, CodecType type) {
798 return make_unique<LZMA2Codec>(level, type);
801 LZMA2Codec::LZMA2Codec(int level, CodecType type) : Codec(type) {
802 DCHECK(type == CodecType::LZMA2 || type == CodecType::LZMA2_VARINT_SIZE);
804 case COMPRESSION_LEVEL_FASTEST:
807 case COMPRESSION_LEVEL_DEFAULT:
808 level = LZMA_PRESET_DEFAULT;
810 case COMPRESSION_LEVEL_BEST:
814 if (level < 0 || level > 9) {
815 throw std::invalid_argument(to<std::string>(
816 "LZMA2Codec: invalid level: ", level));
821 bool LZMA2Codec::doNeedsUncompressedLength() const {
822 return !encodeSize();
825 uint64_t LZMA2Codec::doMaxUncompressedLength() const {
826 // From lzma/base.h: "Stream is roughly 8 EiB (2^63 bytes)"
827 return uint64_t(1) << 63;
830 std::unique_ptr<IOBuf> LZMA2Codec::addOutputBuffer(
834 CHECK_EQ(stream->avail_out, 0);
836 auto buf = IOBuf::create(length);
839 stream->next_out = buf->writableData();
840 stream->avail_out = buf->length();
845 std::unique_ptr<IOBuf> LZMA2Codec::doCompress(const IOBuf* data) {
847 lzma_stream stream = LZMA_STREAM_INIT;
849 rc = lzma_easy_encoder(&stream, level_, LZMA_CHECK_NONE);
851 throw std::runtime_error(folly::to<std::string>(
852 "LZMA2Codec: lzma_easy_encoder error: ", rc));
855 SCOPE_EXIT { lzma_end(&stream); };
857 uint64_t uncompressedLength = data->computeChainDataLength();
858 uint64_t maxCompressedLength = lzma_stream_buffer_bound(uncompressedLength);
860 // Max 64MiB in one go
861 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
862 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
864 auto out = addOutputBuffer(
866 (maxCompressedLength <= maxSingleStepLength ?
867 maxCompressedLength :
868 defaultBufferLength));
871 auto size = IOBuf::createCombined(kMaxVarintLength64);
872 encodeVarintToIOBuf(uncompressedLength, size.get());
873 size->appendChain(std::move(out));
874 out = std::move(size);
877 for (auto& range : *data) {
882 stream.next_in = const_cast<uint8_t*>(range.data());
883 stream.avail_in = range.size();
885 while (stream.avail_in != 0) {
886 if (stream.avail_out == 0) {
887 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
890 rc = lzma_code(&stream, LZMA_RUN);
893 throw std::runtime_error(folly::to<std::string>(
894 "LZMA2Codec: lzma_code error: ", rc));
900 if (stream.avail_out == 0) {
901 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
904 rc = lzma_code(&stream, LZMA_FINISH);
905 } while (rc == LZMA_OK);
907 if (rc != LZMA_STREAM_END) {
908 throw std::runtime_error(folly::to<std::string>(
909 "LZMA2Codec: lzma_code ended with error: ", rc));
912 out->prev()->trimEnd(stream.avail_out);
917 bool LZMA2Codec::doInflate(lzma_stream* stream,
919 size_t bufferLength) {
920 if (stream->avail_out == 0) {
921 head->prependChain(addOutputBuffer(stream, bufferLength));
924 lzma_ret rc = lzma_code(stream, LZMA_RUN);
929 case LZMA_STREAM_END:
932 throw std::runtime_error(to<std::string>(
933 "LZMA2Codec: lzma_code error: ", rc));
939 std::unique_ptr<IOBuf> LZMA2Codec::doUncompress(const IOBuf* data,
940 uint64_t uncompressedLength) {
942 lzma_stream stream = LZMA_STREAM_INIT;
944 rc = lzma_auto_decoder(&stream, std::numeric_limits<uint64_t>::max(), 0);
946 throw std::runtime_error(folly::to<std::string>(
947 "LZMA2Codec: lzma_auto_decoder error: ", rc));
950 SCOPE_EXIT { lzma_end(&stream); };
952 // Max 64MiB in one go
953 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
954 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
956 folly::io::Cursor cursor(data);
957 uint64_t actualUncompressedLength;
959 actualUncompressedLength = decodeVarintFromCursor(cursor);
960 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
961 uncompressedLength != actualUncompressedLength) {
962 throw std::runtime_error("LZMA2Codec: invalid uncompressed length");
965 actualUncompressedLength = uncompressedLength;
966 DCHECK_NE(actualUncompressedLength, UNKNOWN_UNCOMPRESSED_LENGTH);
969 auto out = addOutputBuffer(
971 (actualUncompressedLength <= maxSingleStepLength ?
972 actualUncompressedLength :
973 defaultBufferLength));
975 bool streamEnd = false;
976 auto buf = cursor.peekBytes();
977 while (!buf.empty()) {
978 stream.next_in = const_cast<uint8_t*>(buf.data());
979 stream.avail_in = buf.size();
981 while (stream.avail_in != 0) {
983 throw std::runtime_error(to<std::string>(
984 "LZMA2Codec: junk after end of data"));
987 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
990 cursor.skip(buf.size());
991 buf = cursor.peekBytes();
995 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
998 out->prev()->trimEnd(stream.avail_out);
1000 if (actualUncompressedLength != stream.total_out) {
1001 throw std::runtime_error(to<std::string>(
1002 "LZMA2Codec: invalid uncompressed length"));
1008 #endif // FOLLY_HAVE_LIBLZMA
1010 #ifdef FOLLY_HAVE_LIBZSTD
1015 class ZSTDCodec final : public Codec {
1017 static std::unique_ptr<Codec> create(int level, CodecType);
1018 explicit ZSTDCodec(int level, CodecType type);
1021 bool doNeedsUncompressedLength() const override;
1022 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
1023 std::unique_ptr<IOBuf> doUncompress(
1025 uint64_t uncompressedLength) override;
1030 std::unique_ptr<Codec> ZSTDCodec::create(int level, CodecType type) {
1031 return make_unique<ZSTDCodec>(level, type);
1034 ZSTDCodec::ZSTDCodec(int level, CodecType type) : Codec(type) {
1035 DCHECK(type == CodecType::ZSTD);
1037 case COMPRESSION_LEVEL_FASTEST:
1040 case COMPRESSION_LEVEL_DEFAULT:
1043 case COMPRESSION_LEVEL_BEST:
1047 if (level < 1 || level > ZSTD_maxCLevel()) {
1048 throw std::invalid_argument(
1049 to<std::string>("ZSTD: invalid level: ", level));
1054 bool ZSTDCodec::doNeedsUncompressedLength() const {
1058 void zstdThrowIfError(size_t rc) {
1059 if (!ZSTD_isError(rc)) {
1062 throw std::runtime_error(
1063 to<std::string>("ZSTD returned an error: ", ZSTD_getErrorName(rc)));
1066 std::unique_ptr<IOBuf> ZSTDCodec::doCompress(const IOBuf* data) {
1067 // Support earlier versions of the codec (working with a single IOBuf,
1068 // and using ZSTD_decompress which requires ZSTD frame to contain size,
1069 // which isn't populated by streaming API).
1070 if (!data->isChained()) {
1071 auto out = IOBuf::createCombined(ZSTD_compressBound(data->length()));
1072 const auto rc = ZSTD_compress(
1073 out->writableData(),
1078 zstdThrowIfError(rc);
1083 auto zcs = ZSTD_createCStream();
1085 ZSTD_freeCStream(zcs);
1088 auto rc = ZSTD_initCStream(zcs, level_);
1089 zstdThrowIfError(rc);
1091 Cursor cursor(data);
1092 auto result = IOBuf::createCombined(ZSTD_compressBound(cursor.totalLength()));
1095 out.dst = result->writableTail();
1096 out.size = result->capacity();
1099 for (auto buffer = cursor.peekBytes(); !buffer.empty();) {
1101 in.src = buffer.data();
1102 in.size = buffer.size();
1103 for (in.pos = 0; in.pos != in.size;) {
1104 rc = ZSTD_compressStream(zcs, &out, &in);
1105 zstdThrowIfError(rc);
1107 cursor.skip(in.size);
1108 buffer = cursor.peekBytes();
1111 rc = ZSTD_endStream(zcs, &out);
1112 zstdThrowIfError(rc);
1115 result->append(out.pos);
1119 std::unique_ptr<IOBuf> ZSTDCodec::doUncompress(
1121 uint64_t uncompressedLength) {
1122 auto zds = ZSTD_createDStream();
1124 ZSTD_freeDStream(zds);
1127 auto rc = ZSTD_initDStream(zds);
1128 zstdThrowIfError(rc);
1130 ZSTD_outBuffer out{};
1133 auto outputSize = ZSTD_DStreamOutSize();
1134 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH) {
1135 outputSize = uncompressedLength;
1137 auto decompressedSize =
1138 ZSTD_getDecompressedSize(data->data(), data->length());
1139 if (decompressedSize != 0 && decompressedSize < outputSize) {
1140 outputSize = decompressedSize;
1144 IOBufQueue queue(IOBufQueue::cacheChainLength());
1146 Cursor cursor(data);
1148 if (in.pos == in.size) {
1149 auto buffer = cursor.peekBytes();
1150 in.src = buffer.data();
1151 in.size = buffer.size();
1153 cursor.skip(in.size);
1154 if (rc > 1 && in.size == 0) {
1155 throw std::runtime_error(to<std::string>("ZSTD: incomplete input"));
1158 if (out.pos == out.size) {
1160 queue.postallocate(out.pos);
1162 auto buffer = queue.preallocate(outputSize, outputSize);
1163 out.dst = buffer.first;
1164 out.size = buffer.second;
1166 outputSize = ZSTD_DStreamOutSize();
1168 rc = ZSTD_decompressStream(zds, &out, &in);
1169 zstdThrowIfError(rc);
1175 queue.postallocate(out.pos);
1177 if (in.pos != in.size || !cursor.isAtEnd()) {
1178 throw std::runtime_error("ZSTD: junk after end of data");
1180 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
1181 queue.chainLength() != uncompressedLength) {
1182 throw std::runtime_error("ZSTD: invalid uncompressed length");
1185 return queue.move();
1188 #endif // FOLLY_HAVE_LIBZSTD
1192 typedef std::unique_ptr<Codec> (*CodecFactory)(int, CodecType);
1193 static constexpr CodecFactory
1194 codecFactories[static_cast<size_t>(CodecType::NUM_CODEC_TYPES)] = {
1195 nullptr, // USER_DEFINED
1196 NoCompressionCodec::create,
1198 #if FOLLY_HAVE_LIBLZ4
1204 #if FOLLY_HAVE_LIBSNAPPY
1205 SnappyCodec::create,
1216 #if FOLLY_HAVE_LIBLZ4
1222 #if FOLLY_HAVE_LIBLZMA
1230 #if FOLLY_HAVE_LIBZSTD
1243 bool hasCodec(CodecType type) {
1244 size_t idx = static_cast<size_t>(type);
1245 if (idx >= static_cast<size_t>(CodecType::NUM_CODEC_TYPES)) {
1246 throw std::invalid_argument(
1247 to<std::string>("Compression type ", idx, " invalid"));
1249 return codecFactories[idx] != nullptr;
1252 std::unique_ptr<Codec> getCodec(CodecType type, int level) {
1253 size_t idx = static_cast<size_t>(type);
1254 if (idx >= static_cast<size_t>(CodecType::NUM_CODEC_TYPES)) {
1255 throw std::invalid_argument(
1256 to<std::string>("Compression type ", idx, " invalid"));
1258 auto factory = codecFactories[idx];
1260 throw std::invalid_argument(to<std::string>(
1261 "Compression type ", idx, " not supported"));
1263 auto codec = (*factory)(level, type);
1264 DCHECK_EQ(static_cast<size_t>(codec->type()), idx);