2 * Copyright 2016 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);
59 } else if (len > maxUncompressedLength()) {
60 throw std::runtime_error("Codec: uncompressed length too large");
63 return doCompress(data);
66 std::unique_ptr<IOBuf> Codec::uncompress(const IOBuf* data,
67 uint64_t uncompressedLength) {
68 if (uncompressedLength == UNKNOWN_UNCOMPRESSED_LENGTH) {
69 if (needsUncompressedLength()) {
70 throw std::invalid_argument("Codec: uncompressed length required");
72 } else if (uncompressedLength > maxUncompressedLength()) {
73 throw std::runtime_error("Codec: uncompressed length too large");
77 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
78 uncompressedLength != 0) {
79 throw std::runtime_error("Codec: invalid uncompressed length");
81 return IOBuf::create(0);
84 return doUncompress(data, uncompressedLength);
87 bool Codec::needsUncompressedLength() const {
88 return doNeedsUncompressedLength();
91 uint64_t Codec::maxUncompressedLength() const {
92 return doMaxUncompressedLength();
95 bool Codec::doNeedsUncompressedLength() const {
99 uint64_t Codec::doMaxUncompressedLength() const {
100 return UNLIMITED_UNCOMPRESSED_LENGTH;
108 class NoCompressionCodec final : public Codec {
110 static std::unique_ptr<Codec> create(int level, CodecType type);
111 explicit NoCompressionCodec(int level, CodecType type);
114 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
115 std::unique_ptr<IOBuf> doUncompress(
117 uint64_t uncompressedLength) override;
120 std::unique_ptr<Codec> NoCompressionCodec::create(int level, CodecType type) {
121 return make_unique<NoCompressionCodec>(level, type);
124 NoCompressionCodec::NoCompressionCodec(int level, CodecType type)
126 DCHECK(type == CodecType::NO_COMPRESSION);
128 case COMPRESSION_LEVEL_DEFAULT:
129 case COMPRESSION_LEVEL_FASTEST:
130 case COMPRESSION_LEVEL_BEST:
134 throw std::invalid_argument(to<std::string>(
135 "NoCompressionCodec: invalid level ", level));
139 std::unique_ptr<IOBuf> NoCompressionCodec::doCompress(
141 return data->clone();
144 std::unique_ptr<IOBuf> NoCompressionCodec::doUncompress(
146 uint64_t uncompressedLength) {
147 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
148 data->computeChainDataLength() != uncompressedLength) {
149 throw std::runtime_error(to<std::string>(
150 "NoCompressionCodec: invalid uncompressed length"));
152 return data->clone();
155 #if (FOLLY_HAVE_LIBLZ4 || FOLLY_HAVE_LIBLZMA)
159 void encodeVarintToIOBuf(uint64_t val, folly::IOBuf* out) {
160 DCHECK_GE(out->tailroom(), kMaxVarintLength64);
161 out->append(encodeVarint(val, out->writableTail()));
164 inline uint64_t decodeVarintFromCursor(folly::io::Cursor& cursor) {
167 for (int shift = 0; shift <= 63; shift += 7) {
168 b = cursor.read<int8_t>();
169 val |= static_cast<uint64_t>(b & 0x7f) << shift;
175 throw std::invalid_argument("Invalid varint value. Too big.");
182 #endif // FOLLY_HAVE_LIBLZ4 || FOLLY_HAVE_LIBLZMA
184 #if FOLLY_HAVE_LIBLZ4
189 class LZ4Codec final : public Codec {
191 static std::unique_ptr<Codec> create(int level, CodecType type);
192 explicit LZ4Codec(int level, CodecType type);
195 bool doNeedsUncompressedLength() const override;
196 uint64_t doMaxUncompressedLength() const override;
198 bool encodeSize() const { return type() == CodecType::LZ4_VARINT_SIZE; }
200 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
201 std::unique_ptr<IOBuf> doUncompress(
203 uint64_t uncompressedLength) override;
205 bool highCompression_;
208 std::unique_ptr<Codec> LZ4Codec::create(int level, CodecType type) {
209 return make_unique<LZ4Codec>(level, type);
212 LZ4Codec::LZ4Codec(int level, CodecType type) : Codec(type) {
213 DCHECK(type == CodecType::LZ4 || type == CodecType::LZ4_VARINT_SIZE);
216 case COMPRESSION_LEVEL_FASTEST:
217 case COMPRESSION_LEVEL_DEFAULT:
220 case COMPRESSION_LEVEL_BEST:
224 if (level < 1 || level > 2) {
225 throw std::invalid_argument(to<std::string>(
226 "LZ4Codec: invalid level: ", level));
228 highCompression_ = (level > 1);
231 bool LZ4Codec::doNeedsUncompressedLength() const {
232 return !encodeSize();
235 // The value comes from lz4.h in lz4-r117, but older versions of lz4 don't
236 // define LZ4_MAX_INPUT_SIZE (even though the max size is the same), so do it
238 #ifndef LZ4_MAX_INPUT_SIZE
239 # define LZ4_MAX_INPUT_SIZE 0x7E000000
242 uint64_t LZ4Codec::doMaxUncompressedLength() const {
243 return LZ4_MAX_INPUT_SIZE;
246 std::unique_ptr<IOBuf> LZ4Codec::doCompress(const IOBuf* data) {
247 std::unique_ptr<IOBuf> clone;
248 if (data->isChained()) {
249 // LZ4 doesn't support streaming, so we have to coalesce
250 clone = data->clone();
255 uint32_t extraSize = encodeSize() ? kMaxVarintLength64 : 0;
256 auto out = IOBuf::create(extraSize + LZ4_compressBound(data->length()));
258 encodeVarintToIOBuf(data->length(), out.get());
262 if (highCompression_) {
263 n = LZ4_compressHC(reinterpret_cast<const char*>(data->data()),
264 reinterpret_cast<char*>(out->writableTail()),
267 n = LZ4_compress(reinterpret_cast<const char*>(data->data()),
268 reinterpret_cast<char*>(out->writableTail()),
273 CHECK_LE(n, out->capacity());
279 std::unique_ptr<IOBuf> LZ4Codec::doUncompress(
281 uint64_t uncompressedLength) {
282 std::unique_ptr<IOBuf> clone;
283 if (data->isChained()) {
284 // LZ4 doesn't support streaming, so we have to coalesce
285 clone = data->clone();
290 folly::io::Cursor cursor(data);
291 uint64_t actualUncompressedLength;
293 actualUncompressedLength = decodeVarintFromCursor(cursor);
294 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
295 uncompressedLength != actualUncompressedLength) {
296 throw std::runtime_error("LZ4Codec: invalid uncompressed length");
299 actualUncompressedLength = uncompressedLength;
300 if (actualUncompressedLength == UNKNOWN_UNCOMPRESSED_LENGTH ||
301 actualUncompressedLength > maxUncompressedLength()) {
302 throw std::runtime_error("LZ4Codec: invalid uncompressed length");
306 auto sp = StringPiece{cursor.peekBytes()};
307 auto out = IOBuf::create(actualUncompressedLength);
308 int n = LZ4_decompress_safe(
310 reinterpret_cast<char*>(out->writableTail()),
312 actualUncompressedLength);
314 if (n < 0 || uint64_t(n) != actualUncompressedLength) {
315 throw std::runtime_error(to<std::string>(
316 "LZ4 decompression returned invalid value ", n));
318 out->append(actualUncompressedLength);
322 #endif // FOLLY_HAVE_LIBLZ4
324 #if FOLLY_HAVE_LIBSNAPPY
331 * Implementation of snappy::Source that reads from a IOBuf chain.
333 class IOBufSnappySource final : public snappy::Source {
335 explicit IOBufSnappySource(const IOBuf* data);
336 size_t Available() const override;
337 const char* Peek(size_t* len) override;
338 void Skip(size_t n) override;
344 IOBufSnappySource::IOBufSnappySource(const IOBuf* data)
345 : available_(data->computeChainDataLength()),
349 size_t IOBufSnappySource::Available() const {
353 const char* IOBufSnappySource::Peek(size_t* len) {
354 auto sp = StringPiece{cursor_.peekBytes()};
359 void IOBufSnappySource::Skip(size_t n) {
360 CHECK_LE(n, available_);
365 class SnappyCodec final : public Codec {
367 static std::unique_ptr<Codec> create(int level, CodecType type);
368 explicit SnappyCodec(int level, CodecType type);
371 uint64_t doMaxUncompressedLength() const override;
372 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
373 std::unique_ptr<IOBuf> doUncompress(
375 uint64_t uncompressedLength) override;
378 std::unique_ptr<Codec> SnappyCodec::create(int level, CodecType type) {
379 return make_unique<SnappyCodec>(level, type);
382 SnappyCodec::SnappyCodec(int level, CodecType type) : Codec(type) {
383 DCHECK(type == CodecType::SNAPPY);
385 case COMPRESSION_LEVEL_FASTEST:
386 case COMPRESSION_LEVEL_DEFAULT:
387 case COMPRESSION_LEVEL_BEST:
391 throw std::invalid_argument(to<std::string>(
392 "SnappyCodec: invalid level: ", level));
396 uint64_t SnappyCodec::doMaxUncompressedLength() const {
397 // snappy.h uses uint32_t for lengths, so there's that.
398 return std::numeric_limits<uint32_t>::max();
401 std::unique_ptr<IOBuf> SnappyCodec::doCompress(const IOBuf* data) {
402 IOBufSnappySource source(data);
404 IOBuf::create(snappy::MaxCompressedLength(source.Available()));
406 snappy::UncheckedByteArraySink sink(reinterpret_cast<char*>(
407 out->writableTail()));
409 size_t n = snappy::Compress(&source, &sink);
411 CHECK_LE(n, out->capacity());
416 std::unique_ptr<IOBuf> SnappyCodec::doUncompress(const IOBuf* data,
417 uint64_t uncompressedLength) {
418 uint32_t actualUncompressedLength = 0;
421 IOBufSnappySource source(data);
422 if (!snappy::GetUncompressedLength(&source, &actualUncompressedLength)) {
423 throw std::runtime_error("snappy::GetUncompressedLength failed");
425 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
426 uncompressedLength != actualUncompressedLength) {
427 throw std::runtime_error("snappy: invalid uncompressed length");
431 auto out = IOBuf::create(actualUncompressedLength);
434 IOBufSnappySource source(data);
435 if (!snappy::RawUncompress(&source,
436 reinterpret_cast<char*>(out->writableTail()))) {
437 throw std::runtime_error("snappy::RawUncompress failed");
441 out->append(actualUncompressedLength);
445 #endif // FOLLY_HAVE_LIBSNAPPY
451 class ZlibCodec final : public Codec {
453 static std::unique_ptr<Codec> create(int level, CodecType type);
454 explicit ZlibCodec(int level, CodecType type);
457 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
458 std::unique_ptr<IOBuf> doUncompress(
460 uint64_t uncompressedLength) override;
462 std::unique_ptr<IOBuf> addOutputBuffer(z_stream* stream, uint32_t length);
463 bool doInflate(z_stream* stream, IOBuf* head, uint32_t bufferLength);
468 std::unique_ptr<Codec> ZlibCodec::create(int level, CodecType type) {
469 return make_unique<ZlibCodec>(level, type);
472 ZlibCodec::ZlibCodec(int level, CodecType type) : Codec(type) {
473 DCHECK(type == CodecType::ZLIB || type == CodecType::GZIP);
475 case COMPRESSION_LEVEL_FASTEST:
478 case COMPRESSION_LEVEL_DEFAULT:
479 level = Z_DEFAULT_COMPRESSION;
481 case COMPRESSION_LEVEL_BEST:
485 if (level != Z_DEFAULT_COMPRESSION && (level < 0 || level > 9)) {
486 throw std::invalid_argument(to<std::string>(
487 "ZlibCodec: invalid level: ", level));
492 std::unique_ptr<IOBuf> ZlibCodec::addOutputBuffer(z_stream* stream,
494 CHECK_EQ(stream->avail_out, 0);
496 auto buf = IOBuf::create(length);
499 stream->next_out = buf->writableData();
500 stream->avail_out = buf->length();
505 bool ZlibCodec::doInflate(z_stream* stream,
507 uint32_t bufferLength) {
508 if (stream->avail_out == 0) {
509 head->prependChain(addOutputBuffer(stream, bufferLength));
512 int rc = inflate(stream, Z_NO_FLUSH);
523 throw std::runtime_error(to<std::string>(
524 "ZlibCodec: inflate error: ", rc, ": ", stream->msg));
526 CHECK(false) << rc << ": " << stream->msg;
532 std::unique_ptr<IOBuf> ZlibCodec::doCompress(const IOBuf* data) {
534 stream.zalloc = nullptr;
535 stream.zfree = nullptr;
536 stream.opaque = nullptr;
538 // Using deflateInit2() to support gzip. "The windowBits parameter is the
539 // base two logarithm of the maximum window size (...) The default value is
540 // 15 (...) Add 16 to windowBits to write a simple gzip header and trailer
541 // around the compressed data instead of a zlib wrapper. The gzip header
542 // will have no file name, no extra data, no comment, no modification time
543 // (set to zero), no header crc, and the operating system will be set to 255
545 int windowBits = 15 + (type() == CodecType::GZIP ? 16 : 0);
546 // All other parameters (method, memLevel, strategy) get default values from
548 int rc = deflateInit2(&stream,
555 throw std::runtime_error(to<std::string>(
556 "ZlibCodec: deflateInit error: ", rc, ": ", stream.msg));
559 stream.next_in = stream.next_out = nullptr;
560 stream.avail_in = stream.avail_out = 0;
561 stream.total_in = stream.total_out = 0;
563 bool success = false;
566 int rc = deflateEnd(&stream);
567 // If we're here because of an exception, it's okay if some data
569 CHECK(rc == Z_OK || (!success && rc == Z_DATA_ERROR))
570 << rc << ": " << stream.msg;
573 uint64_t uncompressedLength = data->computeChainDataLength();
574 uint64_t maxCompressedLength = deflateBound(&stream, uncompressedLength);
576 // Max 64MiB in one go
577 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
578 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
580 auto out = addOutputBuffer(
582 (maxCompressedLength <= maxSingleStepLength ?
583 maxCompressedLength :
584 defaultBufferLength));
586 for (auto& range : *data) {
587 uint64_t remaining = range.size();
588 uint64_t written = 0;
590 uint32_t step = (remaining > maxSingleStepLength ?
591 maxSingleStepLength : remaining);
592 stream.next_in = const_cast<uint8_t*>(range.data() + written);
593 stream.avail_in = step;
597 while (stream.avail_in != 0) {
598 if (stream.avail_out == 0) {
599 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
602 rc = deflate(&stream, Z_NO_FLUSH);
604 CHECK_EQ(rc, Z_OK) << stream.msg;
610 if (stream.avail_out == 0) {
611 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
614 rc = deflate(&stream, Z_FINISH);
615 } while (rc == Z_OK);
617 CHECK_EQ(rc, Z_STREAM_END) << stream.msg;
619 out->prev()->trimEnd(stream.avail_out);
621 success = true; // we survived
626 std::unique_ptr<IOBuf> ZlibCodec::doUncompress(const IOBuf* data,
627 uint64_t uncompressedLength) {
629 stream.zalloc = nullptr;
630 stream.zfree = nullptr;
631 stream.opaque = nullptr;
633 // "The windowBits parameter is the base two logarithm of the maximum window
634 // size (...) The default value is 15 (...) add 16 to decode only the gzip
635 // format (the zlib format will return a Z_DATA_ERROR)."
636 int windowBits = 15 + (type() == CodecType::GZIP ? 16 : 0);
637 int rc = inflateInit2(&stream, windowBits);
639 throw std::runtime_error(to<std::string>(
640 "ZlibCodec: inflateInit error: ", rc, ": ", stream.msg));
643 stream.next_in = stream.next_out = nullptr;
644 stream.avail_in = stream.avail_out = 0;
645 stream.total_in = stream.total_out = 0;
647 bool success = false;
650 int rc = inflateEnd(&stream);
651 // If we're here because of an exception, it's okay if some data
653 CHECK(rc == Z_OK || (!success && rc == Z_DATA_ERROR))
654 << rc << ": " << stream.msg;
657 // Max 64MiB in one go
658 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
659 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
661 auto out = addOutputBuffer(
663 ((uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
664 uncompressedLength <= maxSingleStepLength) ?
666 defaultBufferLength));
668 bool streamEnd = false;
669 for (auto& range : *data) {
674 stream.next_in = const_cast<uint8_t*>(range.data());
675 stream.avail_in = range.size();
677 while (stream.avail_in != 0) {
679 throw std::runtime_error(to<std::string>(
680 "ZlibCodec: junk after end of data"));
683 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
688 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
691 out->prev()->trimEnd(stream.avail_out);
693 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
694 uncompressedLength != stream.total_out) {
695 throw std::runtime_error(to<std::string>(
696 "ZlibCodec: invalid uncompressed length"));
699 success = true; // we survived
704 #endif // FOLLY_HAVE_LIBZ
706 #if FOLLY_HAVE_LIBLZMA
711 class LZMA2Codec final : public Codec {
713 static std::unique_ptr<Codec> create(int level, CodecType type);
714 explicit LZMA2Codec(int level, CodecType type);
717 bool doNeedsUncompressedLength() const override;
718 uint64_t doMaxUncompressedLength() const override;
720 bool encodeSize() const { return type() == CodecType::LZMA2_VARINT_SIZE; }
722 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
723 std::unique_ptr<IOBuf> doUncompress(
725 uint64_t uncompressedLength) override;
727 std::unique_ptr<IOBuf> addOutputBuffer(lzma_stream* stream, size_t length);
728 bool doInflate(lzma_stream* stream, IOBuf* head, size_t bufferLength);
733 std::unique_ptr<Codec> LZMA2Codec::create(int level, CodecType type) {
734 return make_unique<LZMA2Codec>(level, type);
737 LZMA2Codec::LZMA2Codec(int level, CodecType type) : Codec(type) {
738 DCHECK(type == CodecType::LZMA2 || type == CodecType::LZMA2_VARINT_SIZE);
740 case COMPRESSION_LEVEL_FASTEST:
743 case COMPRESSION_LEVEL_DEFAULT:
744 level = LZMA_PRESET_DEFAULT;
746 case COMPRESSION_LEVEL_BEST:
750 if (level < 0 || level > 9) {
751 throw std::invalid_argument(to<std::string>(
752 "LZMA2Codec: invalid level: ", level));
757 bool LZMA2Codec::doNeedsUncompressedLength() const {
758 return !encodeSize();
761 uint64_t LZMA2Codec::doMaxUncompressedLength() const {
762 // From lzma/base.h: "Stream is roughly 8 EiB (2^63 bytes)"
763 return uint64_t(1) << 63;
766 std::unique_ptr<IOBuf> LZMA2Codec::addOutputBuffer(
770 CHECK_EQ(stream->avail_out, 0);
772 auto buf = IOBuf::create(length);
775 stream->next_out = buf->writableData();
776 stream->avail_out = buf->length();
781 std::unique_ptr<IOBuf> LZMA2Codec::doCompress(const IOBuf* data) {
783 lzma_stream stream = LZMA_STREAM_INIT;
785 rc = lzma_easy_encoder(&stream, level_, LZMA_CHECK_NONE);
787 throw std::runtime_error(folly::to<std::string>(
788 "LZMA2Codec: lzma_easy_encoder error: ", rc));
791 SCOPE_EXIT { lzma_end(&stream); };
793 uint64_t uncompressedLength = data->computeChainDataLength();
794 uint64_t maxCompressedLength = lzma_stream_buffer_bound(uncompressedLength);
796 // Max 64MiB in one go
797 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
798 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
800 auto out = addOutputBuffer(
802 (maxCompressedLength <= maxSingleStepLength ?
803 maxCompressedLength :
804 defaultBufferLength));
807 auto size = IOBuf::createCombined(kMaxVarintLength64);
808 encodeVarintToIOBuf(uncompressedLength, size.get());
809 size->appendChain(std::move(out));
810 out = std::move(size);
813 for (auto& range : *data) {
818 stream.next_in = const_cast<uint8_t*>(range.data());
819 stream.avail_in = range.size();
821 while (stream.avail_in != 0) {
822 if (stream.avail_out == 0) {
823 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
826 rc = lzma_code(&stream, LZMA_RUN);
829 throw std::runtime_error(folly::to<std::string>(
830 "LZMA2Codec: lzma_code error: ", rc));
836 if (stream.avail_out == 0) {
837 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
840 rc = lzma_code(&stream, LZMA_FINISH);
841 } while (rc == LZMA_OK);
843 if (rc != LZMA_STREAM_END) {
844 throw std::runtime_error(folly::to<std::string>(
845 "LZMA2Codec: lzma_code ended with error: ", rc));
848 out->prev()->trimEnd(stream.avail_out);
853 bool LZMA2Codec::doInflate(lzma_stream* stream,
855 size_t bufferLength) {
856 if (stream->avail_out == 0) {
857 head->prependChain(addOutputBuffer(stream, bufferLength));
860 lzma_ret rc = lzma_code(stream, LZMA_RUN);
865 case LZMA_STREAM_END:
868 throw std::runtime_error(to<std::string>(
869 "LZMA2Codec: lzma_code error: ", rc));
875 std::unique_ptr<IOBuf> LZMA2Codec::doUncompress(const IOBuf* data,
876 uint64_t uncompressedLength) {
878 lzma_stream stream = LZMA_STREAM_INIT;
880 rc = lzma_auto_decoder(&stream, std::numeric_limits<uint64_t>::max(), 0);
882 throw std::runtime_error(folly::to<std::string>(
883 "LZMA2Codec: lzma_auto_decoder error: ", rc));
886 SCOPE_EXIT { lzma_end(&stream); };
888 // Max 64MiB in one go
889 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
890 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
892 folly::io::Cursor cursor(data);
893 uint64_t actualUncompressedLength;
895 actualUncompressedLength = decodeVarintFromCursor(cursor);
896 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
897 uncompressedLength != actualUncompressedLength) {
898 throw std::runtime_error("LZMA2Codec: invalid uncompressed length");
901 actualUncompressedLength = uncompressedLength;
902 DCHECK_NE(actualUncompressedLength, UNKNOWN_UNCOMPRESSED_LENGTH);
905 auto out = addOutputBuffer(
907 (actualUncompressedLength <= maxSingleStepLength ?
908 actualUncompressedLength :
909 defaultBufferLength));
911 bool streamEnd = false;
912 auto buf = cursor.peekBytes();
913 while (!buf.empty()) {
914 stream.next_in = const_cast<uint8_t*>(buf.data());
915 stream.avail_in = buf.size();
917 while (stream.avail_in != 0) {
919 throw std::runtime_error(to<std::string>(
920 "LZMA2Codec: junk after end of data"));
923 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
926 cursor.skip(buf.size());
927 buf = cursor.peekBytes();
931 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
934 out->prev()->trimEnd(stream.avail_out);
936 if (actualUncompressedLength != stream.total_out) {
937 throw std::runtime_error(to<std::string>(
938 "LZMA2Codec: invalid uncompressed length"));
944 #endif // FOLLY_HAVE_LIBLZMA
946 #ifdef FOLLY_HAVE_LIBZSTD
949 * ZSTD_BETA compression
951 class ZSTDCodec final : public Codec {
953 static std::unique_ptr<Codec> create(int level, CodecType);
954 explicit ZSTDCodec(int level, CodecType type);
957 bool doNeedsUncompressedLength() const override;
958 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
959 std::unique_ptr<IOBuf> doUncompress(
961 uint64_t uncompressedLength) override;
966 std::unique_ptr<Codec> ZSTDCodec::create(int level, CodecType type) {
967 return make_unique<ZSTDCodec>(level, type);
970 ZSTDCodec::ZSTDCodec(int level, CodecType type) : Codec(type) {
971 DCHECK(type == CodecType::ZSTD_BETA);
973 case COMPRESSION_LEVEL_FASTEST:
976 case COMPRESSION_LEVEL_DEFAULT:
979 case COMPRESSION_LEVEL_BEST:
985 bool ZSTDCodec::doNeedsUncompressedLength() const {
989 std::unique_ptr<IOBuf> ZSTDCodec::doCompress(const IOBuf* data) {
991 size_t maxCompressedLength = ZSTD_compressBound(data->length());
992 auto out = IOBuf::createCombined(maxCompressedLength);
994 CHECK_EQ(out->length(), 0);
996 rc = ZSTD_compress(out->writableTail(),
1002 if (ZSTD_isError(rc)) {
1003 throw std::runtime_error(to<std::string>(
1004 "ZSTD compression returned an error: ",
1005 ZSTD_getErrorName(rc)));
1009 CHECK_EQ(out->length(), rc);
1014 std::unique_ptr<IOBuf> ZSTDCodec::doUncompress(const IOBuf* data,
1015 uint64_t uncompressedLength) {
1017 auto out = IOBuf::createCombined(uncompressedLength);
1019 CHECK_GE(out->capacity(), uncompressedLength);
1020 CHECK_EQ(out->length(), 0);
1022 rc = ZSTD_decompress(
1023 out->writableTail(), out->capacity(), data->data(), data->length());
1025 if (ZSTD_isError(rc)) {
1026 throw std::runtime_error(to<std::string>(
1027 "ZSTD decompression returned an error: ",
1028 ZSTD_getErrorName(rc)));
1032 CHECK_EQ(out->length(), rc);
1037 #endif // FOLLY_HAVE_LIBZSTD
1041 std::unique_ptr<Codec> getCodec(CodecType type, int level) {
1042 typedef std::unique_ptr<Codec> (*CodecFactory)(int, CodecType);
1044 static CodecFactory codecFactories[
1045 static_cast<size_t>(CodecType::NUM_CODEC_TYPES)] = {
1046 nullptr, // USER_DEFINED
1047 NoCompressionCodec::create,
1049 #if FOLLY_HAVE_LIBLZ4
1055 #if FOLLY_HAVE_LIBSNAPPY
1056 SnappyCodec::create,
1067 #if FOLLY_HAVE_LIBLZ4
1073 #if FOLLY_HAVE_LIBLZMA
1081 #if FOLLY_HAVE_LIBZSTD
1094 size_t idx = static_cast<size_t>(type);
1095 if (idx >= static_cast<size_t>(CodecType::NUM_CODEC_TYPES)) {
1096 throw std::invalid_argument(to<std::string>(
1097 "Compression type ", idx, " not supported"));
1099 auto factory = codecFactories[idx];
1101 throw std::invalid_argument(to<std::string>(
1102 "Compression type ", idx, " not supported"));
1104 auto codec = (*factory)(level, type);
1105 DCHECK_EQ(static_cast<size_t>(codec->type()), idx);