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_) {
264 reinterpret_cast<const char*>(data->data()),
265 reinterpret_cast<char*>(out->writableTail()),
270 n = LZ4_compress_default(
271 reinterpret_cast<const char*>(data->data()),
272 reinterpret_cast<char*>(out->writableTail()),
278 CHECK_LE(n, out->capacity());
284 std::unique_ptr<IOBuf> LZ4Codec::doUncompress(
286 uint64_t uncompressedLength) {
287 std::unique_ptr<IOBuf> clone;
288 if (data->isChained()) {
289 // LZ4 doesn't support streaming, so we have to coalesce
290 clone = data->clone();
295 folly::io::Cursor cursor(data);
296 uint64_t actualUncompressedLength;
298 actualUncompressedLength = decodeVarintFromCursor(cursor);
299 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
300 uncompressedLength != actualUncompressedLength) {
301 throw std::runtime_error("LZ4Codec: invalid uncompressed length");
304 actualUncompressedLength = uncompressedLength;
305 if (actualUncompressedLength == UNKNOWN_UNCOMPRESSED_LENGTH ||
306 actualUncompressedLength > maxUncompressedLength()) {
307 throw std::runtime_error("LZ4Codec: invalid uncompressed length");
311 auto sp = StringPiece{cursor.peekBytes()};
312 auto out = IOBuf::create(actualUncompressedLength);
313 int n = LZ4_decompress_safe(
315 reinterpret_cast<char*>(out->writableTail()),
317 actualUncompressedLength);
319 if (n < 0 || uint64_t(n) != actualUncompressedLength) {
320 throw std::runtime_error(to<std::string>(
321 "LZ4 decompression returned invalid value ", n));
323 out->append(actualUncompressedLength);
327 #endif // FOLLY_HAVE_LIBLZ4
329 #if FOLLY_HAVE_LIBSNAPPY
336 * Implementation of snappy::Source that reads from a IOBuf chain.
338 class IOBufSnappySource final : public snappy::Source {
340 explicit IOBufSnappySource(const IOBuf* data);
341 size_t Available() const override;
342 const char* Peek(size_t* len) override;
343 void Skip(size_t n) override;
349 IOBufSnappySource::IOBufSnappySource(const IOBuf* data)
350 : available_(data->computeChainDataLength()),
354 size_t IOBufSnappySource::Available() const {
358 const char* IOBufSnappySource::Peek(size_t* len) {
359 auto sp = StringPiece{cursor_.peekBytes()};
364 void IOBufSnappySource::Skip(size_t n) {
365 CHECK_LE(n, available_);
370 class SnappyCodec final : public Codec {
372 static std::unique_ptr<Codec> create(int level, CodecType type);
373 explicit SnappyCodec(int level, CodecType type);
376 uint64_t doMaxUncompressedLength() const override;
377 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
378 std::unique_ptr<IOBuf> doUncompress(
380 uint64_t uncompressedLength) override;
383 std::unique_ptr<Codec> SnappyCodec::create(int level, CodecType type) {
384 return make_unique<SnappyCodec>(level, type);
387 SnappyCodec::SnappyCodec(int level, CodecType type) : Codec(type) {
388 DCHECK(type == CodecType::SNAPPY);
390 case COMPRESSION_LEVEL_FASTEST:
391 case COMPRESSION_LEVEL_DEFAULT:
392 case COMPRESSION_LEVEL_BEST:
396 throw std::invalid_argument(to<std::string>(
397 "SnappyCodec: invalid level: ", level));
401 uint64_t SnappyCodec::doMaxUncompressedLength() const {
402 // snappy.h uses uint32_t for lengths, so there's that.
403 return std::numeric_limits<uint32_t>::max();
406 std::unique_ptr<IOBuf> SnappyCodec::doCompress(const IOBuf* data) {
407 IOBufSnappySource source(data);
409 IOBuf::create(snappy::MaxCompressedLength(source.Available()));
411 snappy::UncheckedByteArraySink sink(reinterpret_cast<char*>(
412 out->writableTail()));
414 size_t n = snappy::Compress(&source, &sink);
416 CHECK_LE(n, out->capacity());
421 std::unique_ptr<IOBuf> SnappyCodec::doUncompress(const IOBuf* data,
422 uint64_t uncompressedLength) {
423 uint32_t actualUncompressedLength = 0;
426 IOBufSnappySource source(data);
427 if (!snappy::GetUncompressedLength(&source, &actualUncompressedLength)) {
428 throw std::runtime_error("snappy::GetUncompressedLength failed");
430 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
431 uncompressedLength != actualUncompressedLength) {
432 throw std::runtime_error("snappy: invalid uncompressed length");
436 auto out = IOBuf::create(actualUncompressedLength);
439 IOBufSnappySource source(data);
440 if (!snappy::RawUncompress(&source,
441 reinterpret_cast<char*>(out->writableTail()))) {
442 throw std::runtime_error("snappy::RawUncompress failed");
446 out->append(actualUncompressedLength);
450 #endif // FOLLY_HAVE_LIBSNAPPY
456 class ZlibCodec final : public Codec {
458 static std::unique_ptr<Codec> create(int level, CodecType type);
459 explicit ZlibCodec(int level, CodecType type);
462 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
463 std::unique_ptr<IOBuf> doUncompress(
465 uint64_t uncompressedLength) override;
467 std::unique_ptr<IOBuf> addOutputBuffer(z_stream* stream, uint32_t length);
468 bool doInflate(z_stream* stream, IOBuf* head, uint32_t bufferLength);
473 std::unique_ptr<Codec> ZlibCodec::create(int level, CodecType type) {
474 return make_unique<ZlibCodec>(level, type);
477 ZlibCodec::ZlibCodec(int level, CodecType type) : Codec(type) {
478 DCHECK(type == CodecType::ZLIB || type == CodecType::GZIP);
480 case COMPRESSION_LEVEL_FASTEST:
483 case COMPRESSION_LEVEL_DEFAULT:
484 level = Z_DEFAULT_COMPRESSION;
486 case COMPRESSION_LEVEL_BEST:
490 if (level != Z_DEFAULT_COMPRESSION && (level < 0 || level > 9)) {
491 throw std::invalid_argument(to<std::string>(
492 "ZlibCodec: invalid level: ", level));
497 std::unique_ptr<IOBuf> ZlibCodec::addOutputBuffer(z_stream* stream,
499 CHECK_EQ(stream->avail_out, 0);
501 auto buf = IOBuf::create(length);
504 stream->next_out = buf->writableData();
505 stream->avail_out = buf->length();
510 bool ZlibCodec::doInflate(z_stream* stream,
512 uint32_t bufferLength) {
513 if (stream->avail_out == 0) {
514 head->prependChain(addOutputBuffer(stream, bufferLength));
517 int rc = inflate(stream, Z_NO_FLUSH);
528 throw std::runtime_error(to<std::string>(
529 "ZlibCodec: inflate error: ", rc, ": ", stream->msg));
531 CHECK(false) << rc << ": " << stream->msg;
537 std::unique_ptr<IOBuf> ZlibCodec::doCompress(const IOBuf* data) {
539 stream.zalloc = nullptr;
540 stream.zfree = nullptr;
541 stream.opaque = nullptr;
543 // Using deflateInit2() to support gzip. "The windowBits parameter is the
544 // base two logarithm of the maximum window size (...) The default value is
545 // 15 (...) Add 16 to windowBits to write a simple gzip header and trailer
546 // around the compressed data instead of a zlib wrapper. The gzip header
547 // will have no file name, no extra data, no comment, no modification time
548 // (set to zero), no header crc, and the operating system will be set to 255
550 int windowBits = 15 + (type() == CodecType::GZIP ? 16 : 0);
551 // All other parameters (method, memLevel, strategy) get default values from
553 int rc = deflateInit2(&stream,
560 throw std::runtime_error(to<std::string>(
561 "ZlibCodec: deflateInit error: ", rc, ": ", stream.msg));
564 stream.next_in = stream.next_out = nullptr;
565 stream.avail_in = stream.avail_out = 0;
566 stream.total_in = stream.total_out = 0;
568 bool success = false;
571 rc = deflateEnd(&stream);
572 // If we're here because of an exception, it's okay if some data
574 CHECK(rc == Z_OK || (!success && rc == Z_DATA_ERROR))
575 << rc << ": " << stream.msg;
578 uint64_t uncompressedLength = data->computeChainDataLength();
579 uint64_t maxCompressedLength = deflateBound(&stream, uncompressedLength);
581 // Max 64MiB in one go
582 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
583 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
585 auto out = addOutputBuffer(
587 (maxCompressedLength <= maxSingleStepLength ?
588 maxCompressedLength :
589 defaultBufferLength));
591 for (auto& range : *data) {
592 uint64_t remaining = range.size();
593 uint64_t written = 0;
595 uint32_t step = (remaining > maxSingleStepLength ?
596 maxSingleStepLength : remaining);
597 stream.next_in = const_cast<uint8_t*>(range.data() + written);
598 stream.avail_in = step;
602 while (stream.avail_in != 0) {
603 if (stream.avail_out == 0) {
604 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
607 rc = deflate(&stream, Z_NO_FLUSH);
609 CHECK_EQ(rc, Z_OK) << stream.msg;
615 if (stream.avail_out == 0) {
616 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
619 rc = deflate(&stream, Z_FINISH);
620 } while (rc == Z_OK);
622 CHECK_EQ(rc, Z_STREAM_END) << stream.msg;
624 out->prev()->trimEnd(stream.avail_out);
626 success = true; // we survived
631 std::unique_ptr<IOBuf> ZlibCodec::doUncompress(const IOBuf* data,
632 uint64_t uncompressedLength) {
634 stream.zalloc = nullptr;
635 stream.zfree = nullptr;
636 stream.opaque = nullptr;
638 // "The windowBits parameter is the base two logarithm of the maximum window
639 // size (...) The default value is 15 (...) add 16 to decode only the gzip
640 // format (the zlib format will return a Z_DATA_ERROR)."
641 int windowBits = 15 + (type() == CodecType::GZIP ? 16 : 0);
642 int rc = inflateInit2(&stream, windowBits);
644 throw std::runtime_error(to<std::string>(
645 "ZlibCodec: inflateInit error: ", rc, ": ", stream.msg));
648 stream.next_in = stream.next_out = nullptr;
649 stream.avail_in = stream.avail_out = 0;
650 stream.total_in = stream.total_out = 0;
652 bool success = false;
655 rc = inflateEnd(&stream);
656 // If we're here because of an exception, it's okay if some data
658 CHECK(rc == Z_OK || (!success && rc == Z_DATA_ERROR))
659 << rc << ": " << stream.msg;
662 // Max 64MiB in one go
663 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
664 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
666 auto out = addOutputBuffer(
668 ((uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
669 uncompressedLength <= maxSingleStepLength) ?
671 defaultBufferLength));
673 bool streamEnd = false;
674 for (auto& range : *data) {
679 stream.next_in = const_cast<uint8_t*>(range.data());
680 stream.avail_in = range.size();
682 while (stream.avail_in != 0) {
684 throw std::runtime_error(to<std::string>(
685 "ZlibCodec: junk after end of data"));
688 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
693 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
696 out->prev()->trimEnd(stream.avail_out);
698 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
699 uncompressedLength != stream.total_out) {
700 throw std::runtime_error(to<std::string>(
701 "ZlibCodec: invalid uncompressed length"));
704 success = true; // we survived
709 #endif // FOLLY_HAVE_LIBZ
711 #if FOLLY_HAVE_LIBLZMA
716 class LZMA2Codec final : public Codec {
718 static std::unique_ptr<Codec> create(int level, CodecType type);
719 explicit LZMA2Codec(int level, CodecType type);
722 bool doNeedsUncompressedLength() const override;
723 uint64_t doMaxUncompressedLength() const override;
725 bool encodeSize() const { return type() == CodecType::LZMA2_VARINT_SIZE; }
727 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
728 std::unique_ptr<IOBuf> doUncompress(
730 uint64_t uncompressedLength) override;
732 std::unique_ptr<IOBuf> addOutputBuffer(lzma_stream* stream, size_t length);
733 bool doInflate(lzma_stream* stream, IOBuf* head, size_t bufferLength);
738 std::unique_ptr<Codec> LZMA2Codec::create(int level, CodecType type) {
739 return make_unique<LZMA2Codec>(level, type);
742 LZMA2Codec::LZMA2Codec(int level, CodecType type) : Codec(type) {
743 DCHECK(type == CodecType::LZMA2 || type == CodecType::LZMA2_VARINT_SIZE);
745 case COMPRESSION_LEVEL_FASTEST:
748 case COMPRESSION_LEVEL_DEFAULT:
749 level = LZMA_PRESET_DEFAULT;
751 case COMPRESSION_LEVEL_BEST:
755 if (level < 0 || level > 9) {
756 throw std::invalid_argument(to<std::string>(
757 "LZMA2Codec: invalid level: ", level));
762 bool LZMA2Codec::doNeedsUncompressedLength() const {
763 return !encodeSize();
766 uint64_t LZMA2Codec::doMaxUncompressedLength() const {
767 // From lzma/base.h: "Stream is roughly 8 EiB (2^63 bytes)"
768 return uint64_t(1) << 63;
771 std::unique_ptr<IOBuf> LZMA2Codec::addOutputBuffer(
775 CHECK_EQ(stream->avail_out, 0);
777 auto buf = IOBuf::create(length);
780 stream->next_out = buf->writableData();
781 stream->avail_out = buf->length();
786 std::unique_ptr<IOBuf> LZMA2Codec::doCompress(const IOBuf* data) {
788 lzma_stream stream = LZMA_STREAM_INIT;
790 rc = lzma_easy_encoder(&stream, level_, LZMA_CHECK_NONE);
792 throw std::runtime_error(folly::to<std::string>(
793 "LZMA2Codec: lzma_easy_encoder error: ", rc));
796 SCOPE_EXIT { lzma_end(&stream); };
798 uint64_t uncompressedLength = data->computeChainDataLength();
799 uint64_t maxCompressedLength = lzma_stream_buffer_bound(uncompressedLength);
801 // Max 64MiB in one go
802 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
803 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
805 auto out = addOutputBuffer(
807 (maxCompressedLength <= maxSingleStepLength ?
808 maxCompressedLength :
809 defaultBufferLength));
812 auto size = IOBuf::createCombined(kMaxVarintLength64);
813 encodeVarintToIOBuf(uncompressedLength, size.get());
814 size->appendChain(std::move(out));
815 out = std::move(size);
818 for (auto& range : *data) {
823 stream.next_in = const_cast<uint8_t*>(range.data());
824 stream.avail_in = range.size();
826 while (stream.avail_in != 0) {
827 if (stream.avail_out == 0) {
828 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
831 rc = lzma_code(&stream, LZMA_RUN);
834 throw std::runtime_error(folly::to<std::string>(
835 "LZMA2Codec: lzma_code error: ", rc));
841 if (stream.avail_out == 0) {
842 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
845 rc = lzma_code(&stream, LZMA_FINISH);
846 } while (rc == LZMA_OK);
848 if (rc != LZMA_STREAM_END) {
849 throw std::runtime_error(folly::to<std::string>(
850 "LZMA2Codec: lzma_code ended with error: ", rc));
853 out->prev()->trimEnd(stream.avail_out);
858 bool LZMA2Codec::doInflate(lzma_stream* stream,
860 size_t bufferLength) {
861 if (stream->avail_out == 0) {
862 head->prependChain(addOutputBuffer(stream, bufferLength));
865 lzma_ret rc = lzma_code(stream, LZMA_RUN);
870 case LZMA_STREAM_END:
873 throw std::runtime_error(to<std::string>(
874 "LZMA2Codec: lzma_code error: ", rc));
880 std::unique_ptr<IOBuf> LZMA2Codec::doUncompress(const IOBuf* data,
881 uint64_t uncompressedLength) {
883 lzma_stream stream = LZMA_STREAM_INIT;
885 rc = lzma_auto_decoder(&stream, std::numeric_limits<uint64_t>::max(), 0);
887 throw std::runtime_error(folly::to<std::string>(
888 "LZMA2Codec: lzma_auto_decoder error: ", rc));
891 SCOPE_EXIT { lzma_end(&stream); };
893 // Max 64MiB in one go
894 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
895 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
897 folly::io::Cursor cursor(data);
898 uint64_t actualUncompressedLength;
900 actualUncompressedLength = decodeVarintFromCursor(cursor);
901 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
902 uncompressedLength != actualUncompressedLength) {
903 throw std::runtime_error("LZMA2Codec: invalid uncompressed length");
906 actualUncompressedLength = uncompressedLength;
907 DCHECK_NE(actualUncompressedLength, UNKNOWN_UNCOMPRESSED_LENGTH);
910 auto out = addOutputBuffer(
912 (actualUncompressedLength <= maxSingleStepLength ?
913 actualUncompressedLength :
914 defaultBufferLength));
916 bool streamEnd = false;
917 auto buf = cursor.peekBytes();
918 while (!buf.empty()) {
919 stream.next_in = const_cast<uint8_t*>(buf.data());
920 stream.avail_in = buf.size();
922 while (stream.avail_in != 0) {
924 throw std::runtime_error(to<std::string>(
925 "LZMA2Codec: junk after end of data"));
928 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
931 cursor.skip(buf.size());
932 buf = cursor.peekBytes();
936 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
939 out->prev()->trimEnd(stream.avail_out);
941 if (actualUncompressedLength != stream.total_out) {
942 throw std::runtime_error(to<std::string>(
943 "LZMA2Codec: invalid uncompressed length"));
949 #endif // FOLLY_HAVE_LIBLZMA
951 #ifdef FOLLY_HAVE_LIBZSTD
956 class ZSTDCodec final : public Codec {
958 static std::unique_ptr<Codec> create(int level, CodecType);
959 explicit ZSTDCodec(int level, CodecType type);
962 bool doNeedsUncompressedLength() const override;
963 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
964 std::unique_ptr<IOBuf> doUncompress(
966 uint64_t uncompressedLength) override;
971 std::unique_ptr<Codec> ZSTDCodec::create(int level, CodecType type) {
972 return make_unique<ZSTDCodec>(level, type);
975 ZSTDCodec::ZSTDCodec(int level, CodecType type) : Codec(type) {
976 DCHECK(type == CodecType::ZSTD);
978 case COMPRESSION_LEVEL_FASTEST:
981 case COMPRESSION_LEVEL_DEFAULT:
984 case COMPRESSION_LEVEL_BEST:
988 if (level < 1 || level > ZSTD_maxCLevel()) {
989 throw std::invalid_argument(
990 to<std::string>("ZSTD: invalid level: ", level));
995 bool ZSTDCodec::doNeedsUncompressedLength() const {
999 void zstdThrowIfError(size_t rc) {
1000 if (!ZSTD_isError(rc)) {
1003 throw std::runtime_error(
1004 to<std::string>("ZSTD returned an error: ", ZSTD_getErrorName(rc)));
1007 std::unique_ptr<IOBuf> ZSTDCodec::doCompress(const IOBuf* data) {
1008 // Support earlier versions of the codec (working with a single IOBuf,
1009 // and using ZSTD_decompress which requires ZSTD frame to contain size,
1010 // which isn't populated by streaming API).
1011 if (!data->isChained()) {
1012 auto out = IOBuf::createCombined(ZSTD_compressBound(data->length()));
1013 const auto rc = ZSTD_compress(
1014 out->writableData(),
1019 zstdThrowIfError(rc);
1024 auto zcs = ZSTD_createCStream();
1026 ZSTD_freeCStream(zcs);
1029 auto rc = ZSTD_initCStream(zcs, level_);
1030 zstdThrowIfError(rc);
1032 Cursor cursor(data);
1033 auto result = IOBuf::createCombined(ZSTD_compressBound(cursor.totalLength()));
1036 out.dst = result->writableTail();
1037 out.size = result->capacity();
1040 for (auto buffer = cursor.peekBytes(); !buffer.empty();) {
1042 in.src = buffer.data();
1043 in.size = buffer.size();
1044 for (in.pos = 0; in.pos != in.size;) {
1045 rc = ZSTD_compressStream(zcs, &out, &in);
1046 zstdThrowIfError(rc);
1048 cursor.skip(in.size);
1049 buffer = cursor.peekBytes();
1052 rc = ZSTD_endStream(zcs, &out);
1053 zstdThrowIfError(rc);
1056 result->append(out.pos);
1060 std::unique_ptr<IOBuf> ZSTDCodec::doUncompress(
1062 uint64_t uncompressedLength) {
1063 auto zds = ZSTD_createDStream();
1065 ZSTD_freeDStream(zds);
1068 auto rc = ZSTD_initDStream(zds);
1069 zstdThrowIfError(rc);
1071 ZSTD_outBuffer out{};
1074 auto outputSize = ZSTD_DStreamOutSize();
1075 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH) {
1076 outputSize = uncompressedLength;
1078 auto decompressedSize =
1079 ZSTD_getDecompressedSize(data->data(), data->length());
1080 if (decompressedSize != 0 && decompressedSize < outputSize) {
1081 outputSize = decompressedSize;
1085 IOBufQueue queue(IOBufQueue::cacheChainLength());
1087 Cursor cursor(data);
1089 if (in.pos == in.size) {
1090 auto buffer = cursor.peekBytes();
1091 in.src = buffer.data();
1092 in.size = buffer.size();
1094 cursor.skip(in.size);
1095 if (rc > 1 && in.size == 0) {
1096 throw std::runtime_error(to<std::string>("ZSTD: incomplete input"));
1099 if (out.pos == out.size) {
1101 queue.postallocate(out.pos);
1103 auto buffer = queue.preallocate(outputSize, outputSize);
1104 out.dst = buffer.first;
1105 out.size = buffer.second;
1107 outputSize = ZSTD_DStreamOutSize();
1109 rc = ZSTD_decompressStream(zds, &out, &in);
1110 zstdThrowIfError(rc);
1116 queue.postallocate(out.pos);
1118 if (in.pos != in.size || !cursor.isAtEnd()) {
1119 throw std::runtime_error("ZSTD: junk after end of data");
1121 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
1122 queue.chainLength() != uncompressedLength) {
1123 throw std::runtime_error("ZSTD: invalid uncompressed length");
1126 return queue.move();
1129 #endif // FOLLY_HAVE_LIBZSTD
1133 std::unique_ptr<Codec> getCodec(CodecType type, int level) {
1134 typedef std::unique_ptr<Codec> (*CodecFactory)(int, CodecType);
1136 static CodecFactory codecFactories[
1137 static_cast<size_t>(CodecType::NUM_CODEC_TYPES)] = {
1138 nullptr, // USER_DEFINED
1139 NoCompressionCodec::create,
1141 #if FOLLY_HAVE_LIBLZ4
1147 #if FOLLY_HAVE_LIBSNAPPY
1148 SnappyCodec::create,
1159 #if FOLLY_HAVE_LIBLZ4
1165 #if FOLLY_HAVE_LIBLZMA
1173 #if FOLLY_HAVE_LIBZSTD
1186 size_t idx = static_cast<size_t>(type);
1187 if (idx >= static_cast<size_t>(CodecType::NUM_CODEC_TYPES)) {
1188 throw std::invalid_argument(to<std::string>(
1189 "Compression type ", idx, " not supported"));
1191 auto factory = codecFactories[idx];
1193 throw std::invalid_argument(to<std::string>(
1194 "Compression type ", idx, " not supported"));
1196 auto codec = (*factory)(level, type);
1197 DCHECK_EQ(static_cast<size_t>(codec->type()), idx);