proxygen
ZstdStreamDecompressor.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2015-present, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree. An additional grant
7  * of patent rights can be found in the PATENTS file in the same directory.
8  *
9  */
10 
11 #include "ZstdStreamDecompressor.h"
12 
13 #include <folly/Range.h>
14 #include <folly/io/Cursor.h>
15 #include <folly/io/IOBuf.h>
16 
17 using folly::IOBuf;
18 using std::unique_ptr;
19 using namespace proxygen;
20 
22  : totalLen_(totalLen) {
23  dStream_ = ZSTD_createDStream();
24  if (dictStr != "") {
25  dDict_ = ZSTD_createDDict(&dictStr, dictStr.length());
26  if (dStream_ == nullptr || dDict_ == nullptr ||
27  ZSTD_isError(ZSTD_initDStream_usingDDict(dStream_, dDict_))) {
29  }
30  } else {
31  if (dStream_ == nullptr ||
32  ZSTD_isError(ZSTD_initDStream(dStream_))) {
34  }
35  }
36 }
37 
39  if (dStream_) {
40  ZSTD_freeDStream(dStream_);
41  }
42  if (dDict_) {
43  ZSTD_freeDDict(dDict_);
44  }
45 }
46 
47 std::unique_ptr<folly::IOBuf> ZstdStreamDecompressor::decompress(
48  const folly::IOBuf* in) {
49  if (dStream_ == nullptr) {
51  return nullptr;
52  }
53 
54  auto out = folly::IOBuf::create(ZSTD_DStreamOutSize());
55 
56  size_t buffOutSize = ZSTD_DStreamOutSize();
57  std::unique_ptr<unsigned char[]> buffOut(new unsigned char[buffOutSize]);
58  auto appender = folly::io::Appender(out.get(), buffOutSize);
59 
60  for (const folly::ByteRange range : *in) {
61  ZSTD_inBuffer input = {range.data(), range.size(), 0};
62  while (input.pos < input.size) {
63  ZSTD_outBuffer output = {buffOut.get(), buffOutSize, 0};
64  size_t toRead = ZSTD_decompressStream(dStream_, &output, &input);
65 
66  if (ZSTD_isError(toRead)) {
68  return nullptr;
69  }
70 
71  if (toRead == 0) {
72  ZSTD_resetDStream(dStream_);
73  }
74 
75  if (output.pos > 0) {
76  size_t copied =
77  appender.pushAtMost((const uint8_t*)output.dst, output.pos);
78  CHECK(copied == output.pos);
79  }
80  totalDec_ += input.size;
81 
82  if (totalDec_ < totalLen_) {
84  } else if (totalDec_ > totalLen_) {
86  } else {
88  }
89  }
90  }
91 
92  return out;
93 }
std::unique_ptr< folly::IOBuf > decompress(const folly::IOBuf *in)
static std::unique_ptr< IOBuf > create(std::size_t capacity)
Definition: IOBuf.cpp:229
Gen range(Value begin, Value end)
Definition: Base.h:467
const char * string
Definition: Conv.cpp:212