2 * Copyright 2015 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 p = cursor.peek();
307 auto out = IOBuf::create(actualUncompressedLength);
308 int n = LZ4_decompress_safe(reinterpret_cast<const char*>(p.first),
309 reinterpret_cast<char*>(out->writableTail()),
311 actualUncompressedLength);
313 if (n < 0 || uint64_t(n) != actualUncompressedLength) {
314 throw std::runtime_error(to<std::string>(
315 "LZ4 decompression returned invalid value ", n));
317 out->append(actualUncompressedLength);
321 #endif // FOLLY_HAVE_LIBLZ4
323 #if FOLLY_HAVE_LIBSNAPPY
330 * Implementation of snappy::Source that reads from a IOBuf chain.
332 class IOBufSnappySource final : public snappy::Source {
334 explicit IOBufSnappySource(const IOBuf* data);
335 size_t Available() const override;
336 const char* Peek(size_t* len) override;
337 void Skip(size_t n) override;
343 IOBufSnappySource::IOBufSnappySource(const IOBuf* data)
344 : available_(data->computeChainDataLength()),
348 size_t IOBufSnappySource::Available() const {
352 const char* IOBufSnappySource::Peek(size_t* len) {
353 auto p = cursor_.peek();
355 return reinterpret_cast<const char*>(p.first);
358 void IOBufSnappySource::Skip(size_t n) {
359 CHECK_LE(n, available_);
364 class SnappyCodec final : public Codec {
366 static std::unique_ptr<Codec> create(int level, CodecType type);
367 explicit SnappyCodec(int level, CodecType type);
370 uint64_t doMaxUncompressedLength() const override;
371 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
372 std::unique_ptr<IOBuf> doUncompress(
374 uint64_t uncompressedLength) override;
377 std::unique_ptr<Codec> SnappyCodec::create(int level, CodecType type) {
378 return make_unique<SnappyCodec>(level, type);
381 SnappyCodec::SnappyCodec(int level, CodecType type) : Codec(type) {
382 DCHECK(type == CodecType::SNAPPY);
384 case COMPRESSION_LEVEL_FASTEST:
385 case COMPRESSION_LEVEL_DEFAULT:
386 case COMPRESSION_LEVEL_BEST:
390 throw std::invalid_argument(to<std::string>(
391 "SnappyCodec: invalid level: ", level));
395 uint64_t SnappyCodec::doMaxUncompressedLength() const {
396 // snappy.h uses uint32_t for lengths, so there's that.
397 return std::numeric_limits<uint32_t>::max();
400 std::unique_ptr<IOBuf> SnappyCodec::doCompress(const IOBuf* data) {
401 IOBufSnappySource source(data);
403 IOBuf::create(snappy::MaxCompressedLength(source.Available()));
405 snappy::UncheckedByteArraySink sink(reinterpret_cast<char*>(
406 out->writableTail()));
408 size_t n = snappy::Compress(&source, &sink);
410 CHECK_LE(n, out->capacity());
415 std::unique_ptr<IOBuf> SnappyCodec::doUncompress(const IOBuf* data,
416 uint64_t uncompressedLength) {
417 uint32_t actualUncompressedLength = 0;
420 IOBufSnappySource source(data);
421 if (!snappy::GetUncompressedLength(&source, &actualUncompressedLength)) {
422 throw std::runtime_error("snappy::GetUncompressedLength failed");
424 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
425 uncompressedLength != actualUncompressedLength) {
426 throw std::runtime_error("snappy: invalid uncompressed length");
430 auto out = IOBuf::create(actualUncompressedLength);
433 IOBufSnappySource source(data);
434 if (!snappy::RawUncompress(&source,
435 reinterpret_cast<char*>(out->writableTail()))) {
436 throw std::runtime_error("snappy::RawUncompress failed");
440 out->append(actualUncompressedLength);
444 #endif // FOLLY_HAVE_LIBSNAPPY
450 class ZlibCodec final : public Codec {
452 static std::unique_ptr<Codec> create(int level, CodecType type);
453 explicit ZlibCodec(int level, CodecType type);
456 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
457 std::unique_ptr<IOBuf> doUncompress(
459 uint64_t uncompressedLength) override;
461 std::unique_ptr<IOBuf> addOutputBuffer(z_stream* stream, uint32_t length);
462 bool doInflate(z_stream* stream, IOBuf* head, uint32_t bufferLength);
467 std::unique_ptr<Codec> ZlibCodec::create(int level, CodecType type) {
468 return make_unique<ZlibCodec>(level, type);
471 ZlibCodec::ZlibCodec(int level, CodecType type) : Codec(type) {
472 DCHECK(type == CodecType::ZLIB);
474 case COMPRESSION_LEVEL_FASTEST:
477 case COMPRESSION_LEVEL_DEFAULT:
478 level = Z_DEFAULT_COMPRESSION;
480 case COMPRESSION_LEVEL_BEST:
484 if (level != Z_DEFAULT_COMPRESSION && (level < 0 || level > 9)) {
485 throw std::invalid_argument(to<std::string>(
486 "ZlibCodec: invalid level: ", level));
491 std::unique_ptr<IOBuf> ZlibCodec::addOutputBuffer(z_stream* stream,
493 CHECK_EQ(stream->avail_out, 0);
495 auto buf = IOBuf::create(length);
498 stream->next_out = buf->writableData();
499 stream->avail_out = buf->length();
504 bool ZlibCodec::doInflate(z_stream* stream,
506 uint32_t bufferLength) {
507 if (stream->avail_out == 0) {
508 head->prependChain(addOutputBuffer(stream, bufferLength));
511 int rc = inflate(stream, Z_NO_FLUSH);
522 throw std::runtime_error(to<std::string>(
523 "ZlibCodec: inflate error: ", rc, ": ", stream->msg));
525 CHECK(false) << rc << ": " << stream->msg;
531 std::unique_ptr<IOBuf> ZlibCodec::doCompress(const IOBuf* data) {
533 stream.zalloc = nullptr;
534 stream.zfree = nullptr;
535 stream.opaque = nullptr;
537 int rc = deflateInit(&stream, level_);
539 throw std::runtime_error(to<std::string>(
540 "ZlibCodec: deflateInit error: ", rc, ": ", stream.msg));
543 stream.next_in = stream.next_out = nullptr;
544 stream.avail_in = stream.avail_out = 0;
545 stream.total_in = stream.total_out = 0;
547 bool success = false;
550 int rc = deflateEnd(&stream);
551 // If we're here because of an exception, it's okay if some data
553 CHECK(rc == Z_OK || (!success && rc == Z_DATA_ERROR))
554 << rc << ": " << stream.msg;
557 uint64_t uncompressedLength = data->computeChainDataLength();
558 uint64_t maxCompressedLength = deflateBound(&stream, uncompressedLength);
560 // Max 64MiB in one go
561 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
562 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
564 auto out = addOutputBuffer(
566 (maxCompressedLength <= maxSingleStepLength ?
567 maxCompressedLength :
568 defaultBufferLength));
570 for (auto& range : *data) {
571 uint64_t remaining = range.size();
572 uint64_t written = 0;
574 uint32_t step = (remaining > maxSingleStepLength ?
575 maxSingleStepLength : remaining);
576 stream.next_in = const_cast<uint8_t*>(range.data() + written);
577 stream.avail_in = step;
581 while (stream.avail_in != 0) {
582 if (stream.avail_out == 0) {
583 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
586 rc = deflate(&stream, Z_NO_FLUSH);
588 CHECK_EQ(rc, Z_OK) << stream.msg;
594 if (stream.avail_out == 0) {
595 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
598 rc = deflate(&stream, Z_FINISH);
599 } while (rc == Z_OK);
601 CHECK_EQ(rc, Z_STREAM_END) << stream.msg;
603 out->prev()->trimEnd(stream.avail_out);
605 success = true; // we survived
610 std::unique_ptr<IOBuf> ZlibCodec::doUncompress(const IOBuf* data,
611 uint64_t uncompressedLength) {
613 stream.zalloc = nullptr;
614 stream.zfree = nullptr;
615 stream.opaque = nullptr;
617 int rc = inflateInit(&stream);
619 throw std::runtime_error(to<std::string>(
620 "ZlibCodec: inflateInit 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 int rc = inflateEnd(&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 // Max 64MiB in one go
638 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
639 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
641 auto out = addOutputBuffer(
643 ((uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
644 uncompressedLength <= maxSingleStepLength) ?
646 defaultBufferLength));
648 bool streamEnd = false;
649 for (auto& range : *data) {
654 stream.next_in = const_cast<uint8_t*>(range.data());
655 stream.avail_in = range.size();
657 while (stream.avail_in != 0) {
659 throw std::runtime_error(to<std::string>(
660 "ZlibCodec: junk after end of data"));
663 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
668 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
671 out->prev()->trimEnd(stream.avail_out);
673 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
674 uncompressedLength != stream.total_out) {
675 throw std::runtime_error(to<std::string>(
676 "ZlibCodec: invalid uncompressed length"));
679 success = true; // we survived
684 #endif // FOLLY_HAVE_LIBZ
686 #if FOLLY_HAVE_LIBLZMA
691 class LZMA2Codec final : public Codec {
693 static std::unique_ptr<Codec> create(int level, CodecType type);
694 explicit LZMA2Codec(int level, CodecType type);
697 bool doNeedsUncompressedLength() const override;
698 uint64_t doMaxUncompressedLength() const override;
700 bool encodeSize() const { return type() == CodecType::LZMA2_VARINT_SIZE; }
702 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
703 std::unique_ptr<IOBuf> doUncompress(
705 uint64_t uncompressedLength) override;
707 std::unique_ptr<IOBuf> addOutputBuffer(lzma_stream* stream, size_t length);
708 bool doInflate(lzma_stream* stream, IOBuf* head, size_t bufferLength);
713 std::unique_ptr<Codec> LZMA2Codec::create(int level, CodecType type) {
714 return make_unique<LZMA2Codec>(level, type);
717 LZMA2Codec::LZMA2Codec(int level, CodecType type) : Codec(type) {
718 DCHECK(type == CodecType::LZMA2 || type == CodecType::LZMA2_VARINT_SIZE);
720 case COMPRESSION_LEVEL_FASTEST:
723 case COMPRESSION_LEVEL_DEFAULT:
724 level = LZMA_PRESET_DEFAULT;
726 case COMPRESSION_LEVEL_BEST:
730 if (level < 0 || level > 9) {
731 throw std::invalid_argument(to<std::string>(
732 "LZMA2Codec: invalid level: ", level));
737 bool LZMA2Codec::doNeedsUncompressedLength() const {
738 return !encodeSize();
741 uint64_t LZMA2Codec::doMaxUncompressedLength() const {
742 // From lzma/base.h: "Stream is roughly 8 EiB (2^63 bytes)"
743 return uint64_t(1) << 63;
746 std::unique_ptr<IOBuf> LZMA2Codec::addOutputBuffer(
750 CHECK_EQ(stream->avail_out, 0);
752 auto buf = IOBuf::create(length);
755 stream->next_out = buf->writableData();
756 stream->avail_out = buf->length();
761 std::unique_ptr<IOBuf> LZMA2Codec::doCompress(const IOBuf* data) {
763 lzma_stream stream = LZMA_STREAM_INIT;
765 rc = lzma_easy_encoder(&stream, level_, LZMA_CHECK_NONE);
767 throw std::runtime_error(folly::to<std::string>(
768 "LZMA2Codec: lzma_easy_encoder error: ", rc));
771 SCOPE_EXIT { lzma_end(&stream); };
773 uint64_t uncompressedLength = data->computeChainDataLength();
774 uint64_t maxCompressedLength = lzma_stream_buffer_bound(uncompressedLength);
776 // Max 64MiB in one go
777 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
778 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
780 auto out = addOutputBuffer(
782 (maxCompressedLength <= maxSingleStepLength ?
783 maxCompressedLength :
784 defaultBufferLength));
787 auto size = IOBuf::createCombined(kMaxVarintLength64);
788 encodeVarintToIOBuf(uncompressedLength, size.get());
789 size->appendChain(std::move(out));
790 out = std::move(size);
793 for (auto& range : *data) {
798 stream.next_in = const_cast<uint8_t*>(range.data());
799 stream.avail_in = range.size();
801 while (stream.avail_in != 0) {
802 if (stream.avail_out == 0) {
803 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
806 rc = lzma_code(&stream, LZMA_RUN);
809 throw std::runtime_error(folly::to<std::string>(
810 "LZMA2Codec: lzma_code error: ", rc));
816 if (stream.avail_out == 0) {
817 out->prependChain(addOutputBuffer(&stream, defaultBufferLength));
820 rc = lzma_code(&stream, LZMA_FINISH);
821 } while (rc == LZMA_OK);
823 if (rc != LZMA_STREAM_END) {
824 throw std::runtime_error(folly::to<std::string>(
825 "LZMA2Codec: lzma_code ended with error: ", rc));
828 out->prev()->trimEnd(stream.avail_out);
833 bool LZMA2Codec::doInflate(lzma_stream* stream,
835 size_t bufferLength) {
836 if (stream->avail_out == 0) {
837 head->prependChain(addOutputBuffer(stream, bufferLength));
840 lzma_ret rc = lzma_code(stream, LZMA_RUN);
845 case LZMA_STREAM_END:
848 throw std::runtime_error(to<std::string>(
849 "LZMA2Codec: lzma_code error: ", rc));
855 std::unique_ptr<IOBuf> LZMA2Codec::doUncompress(const IOBuf* data,
856 uint64_t uncompressedLength) {
858 lzma_stream stream = LZMA_STREAM_INIT;
860 rc = lzma_auto_decoder(&stream, std::numeric_limits<uint64_t>::max(), 0);
862 throw std::runtime_error(folly::to<std::string>(
863 "LZMA2Codec: lzma_auto_decoder error: ", rc));
866 SCOPE_EXIT { lzma_end(&stream); };
868 // Max 64MiB in one go
869 constexpr uint32_t maxSingleStepLength = uint32_t(64) << 20; // 64MiB
870 constexpr uint32_t defaultBufferLength = uint32_t(4) << 20; // 4MiB
872 folly::io::Cursor cursor(data);
873 uint64_t actualUncompressedLength;
875 actualUncompressedLength = decodeVarintFromCursor(cursor);
876 if (uncompressedLength != UNKNOWN_UNCOMPRESSED_LENGTH &&
877 uncompressedLength != actualUncompressedLength) {
878 throw std::runtime_error("LZMA2Codec: invalid uncompressed length");
881 actualUncompressedLength = uncompressedLength;
882 DCHECK_NE(actualUncompressedLength, UNKNOWN_UNCOMPRESSED_LENGTH);
885 auto out = addOutputBuffer(
887 (actualUncompressedLength <= maxSingleStepLength ?
888 actualUncompressedLength :
889 defaultBufferLength));
891 bool streamEnd = false;
892 auto buf = cursor.peek();
893 while (buf.second != 0) {
894 stream.next_in = const_cast<uint8_t*>(buf.first);
895 stream.avail_in = buf.second;
897 while (stream.avail_in != 0) {
899 throw std::runtime_error(to<std::string>(
900 "LZMA2Codec: junk after end of data"));
903 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
906 cursor.skip(buf.second);
911 streamEnd = doInflate(&stream, out.get(), defaultBufferLength);
914 out->prev()->trimEnd(stream.avail_out);
916 if (actualUncompressedLength != stream.total_out) {
917 throw std::runtime_error(to<std::string>(
918 "LZMA2Codec: invalid uncompressed length"));
924 #endif // FOLLY_HAVE_LIBLZMA
926 #ifdef FOLLY_HAVE_LIBZSTD
929 * ZSTD_BETA compression
931 class ZSTDCodec final : public Codec {
933 static std::unique_ptr<Codec> create(int level, CodecType);
934 explicit ZSTDCodec(int level, CodecType type);
937 bool doNeedsUncompressedLength() const override;
938 std::unique_ptr<IOBuf> doCompress(const IOBuf* data) override;
939 std::unique_ptr<IOBuf> doUncompress(
941 uint64_t uncompressedLength) override;
946 std::unique_ptr<Codec> ZSTDCodec::create(int level, CodecType type) {
947 return make_unique<ZSTDCodec>(level, type);
950 ZSTDCodec::ZSTDCodec(int level, CodecType type) : Codec(type) {
951 DCHECK(type == CodecType::ZSTD_BETA);
953 case COMPRESSION_LEVEL_FASTEST:
956 case COMPRESSION_LEVEL_DEFAULT:
959 case COMPRESSION_LEVEL_BEST:
965 bool ZSTDCodec::doNeedsUncompressedLength() const {
969 std::unique_ptr<IOBuf> ZSTDCodec::doCompress(const IOBuf* data) {
971 size_t maxCompressedLength = ZSTD_compressBound(data->length());
972 auto out = IOBuf::createCombined(maxCompressedLength);
974 CHECK_EQ(out->length(), 0);
976 rc = ZSTD_compress(out->writableTail(),
982 if (ZSTD_isError(rc)) {
983 throw std::runtime_error(to<std::string>(
984 "ZSTD compression returned an error: ",
985 ZSTD_getErrorName(rc)));
989 CHECK_EQ(out->length(), rc);
994 std::unique_ptr<IOBuf> ZSTDCodec::doUncompress(const IOBuf* data,
995 uint64_t uncompressedLength) {
997 auto out = IOBuf::createCombined(uncompressedLength);
999 CHECK_GE(out->capacity(), uncompressedLength);
1000 CHECK_EQ(out->length(), 0);
1002 rc = ZSTD_decompress(
1003 out->writableTail(), out->capacity(), data->data(), data->length());
1005 if (ZSTD_isError(rc)) {
1006 throw std::runtime_error(to<std::string>(
1007 "ZSTD decompression returned an error: ",
1008 ZSTD_getErrorName(rc)));
1012 CHECK_EQ(out->length(), rc);
1017 #endif // FOLLY_HAVE_LIBZSTD
1021 std::unique_ptr<Codec> getCodec(CodecType type, int level) {
1022 typedef std::unique_ptr<Codec> (*CodecFactory)(int, CodecType);
1024 static CodecFactory codecFactories[
1025 static_cast<size_t>(CodecType::NUM_CODEC_TYPES)] = {
1026 nullptr, // USER_DEFINED
1027 NoCompressionCodec::create,
1029 #if FOLLY_HAVE_LIBLZ4
1035 #if FOLLY_HAVE_LIBSNAPPY
1036 SnappyCodec::create,
1047 #if FOLLY_HAVE_LIBLZ4
1053 #if FOLLY_HAVE_LIBLZMA
1061 #if FOLLY_HAVE_LIBZSTD
1068 size_t idx = static_cast<size_t>(type);
1069 if (idx >= static_cast<size_t>(CodecType::NUM_CODEC_TYPES)) {
1070 throw std::invalid_argument(to<std::string>(
1071 "Compression type ", idx, " not supported"));
1073 auto factory = codecFactories[idx];
1075 throw std::invalid_argument(to<std::string>(
1076 "Compression type ", idx, " not supported"));
1078 auto codec = (*factory)(level, type);
1079 DCHECK_EQ(static_cast<size_t>(codec->type()), idx);