1 /* 2 * Copyright (c) Facebook, Inc. and its affiliates. 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17 #pragma once 18 19 #include <memory.h> 20 21 #include <folly/Memory.h> 22 #include <folly/Portability.h> 23 #include <folly/compression/Compression.h> 24 25 #if FOLLY_HAVE_LIBZSTD 26 27 #ifndef ZSTD_STATIC_LINKING_ONLY 28 #define ZSTD_STATIC_LINKING_ONLY 29 #endif 30 #include <zstd.h> 31 32 namespace folly { 33 namespace io { 34 namespace zstd { 35 36 /** 37 * Interface for zstd-specific codec initialization. 38 */ 39 class Options { 40 public: 41 /* Create an Options struct with the default options for the given `level`. 42 * NOTE: This is the zstd level, COMPRESSION_LEVEL_DEFAULT and such aren't 43 * supported, since zstd supports negative compression levels. 44 */ 45 explicit Options(int level); 46 47 /** 48 * Set the compression `param` to `value`. 49 * See the zstd documentation for ZSTD_CCtx_setParameter() for details, this 50 * is just a thin wrapper. 51 */ 52 void set(ZSTD_cParameter param, unsigned value); 53 54 /** 55 * Set the maximum allowed window size during decompression. 56 * `maxWindowSize == 0` means don't set the maximum window size. 57 * zstd's current default limit is 2^27. 58 * See the zstd documentation for ZSTD_DCtx_setMaxWindowSize() for details. 59 */ setMaxWindowSize(size_t maxWindowSize)60 void setMaxWindowSize(size_t maxWindowSize) { 61 maxWindowSize_ = maxWindowSize; 62 } 63 64 /// Get a reference to the ZSTD_CCtx_params. params()65 ZSTD_CCtx_params const* params() const { return params_.get(); } 66 67 /// Get the compression level. level()68 int level() const { return level_; } 69 70 /// Get the maximum window size. maxWindowSize()71 size_t maxWindowSize() const { return maxWindowSize_; } 72 73 private: 74 static void freeCCtxParams(ZSTD_CCtx_params* params); 75 std::unique_ptr< 76 ZSTD_CCtx_params, 77 folly::static_function_deleter<ZSTD_CCtx_params, &freeCCtxParams>> 78 params_; 79 size_t maxWindowSize_{0}; 80 int level_; 81 }; 82 83 /// Get a zstd Codec with the given options. 84 std::unique_ptr<Codec> getCodec(Options options); 85 /// Get a zstd StreamCodec with the given options. 86 std::unique_ptr<StreamCodec> getStreamCodec(Options options); 87 88 } // namespace zstd 89 } // namespace io 90 } // namespace folly 91 92 #endif 93