1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "zlib_compression.h"
17 #ifndef OMIT_ZLIB
18 #include <zlib.h>
19
20 #include "db_constant.h"
21 #include "db_errno.h"
22 #include "log_print.h"
23 #include "types_export.h"
24
25 namespace DistributedDB {
26 static ZlibCompression g_zlibInstance;
27
ZlibCompression()28 ZlibCompression::ZlibCompression()
29 {
30 DataCompression::Register(CompressAlgorithm::ZLIB, this);
31 }
32
Compress(const std::vector<uint8_t> & srcData,std::vector<uint8_t> & destData) const33 int ZlibCompression::Compress(const std::vector<uint8_t> &srcData, std::vector<uint8_t> &destData) const
34 {
35 auto srcLen = srcData.size();
36 auto destLen = compressBound(srcLen);
37 if (srcLen > DBConstant::MAX_SYNC_BLOCK_SIZE || destLen > DBConstant::MAX_SYNC_BLOCK_SIZE) {
38 LOGE("Too long to compress, srcLen:%zu, destLen:%lu.", srcLen, destLen);
39 return -E_INVALID_ARGS;
40 }
41
42 // Alloc memory.
43 destData.resize(destLen);
44
45 // Compress.
46 int errCode = compress(destData.data(), &destLen, srcData.data(), srcLen);
47 if (errCode != Z_OK) {
48 LOGE("Compress parcel failed, errCode = %d", errCode);
49 return -E_SYSTEM_API_FAIL;
50 }
51
52 destData.resize(destLen);
53 destData.shrink_to_fit();
54 return E_OK;
55 }
56
Uncompress(const std::vector<uint8_t> & srcData,std::vector<uint8_t> & destData,uint32_t destLen) const57 int ZlibCompression::Uncompress(const std::vector<uint8_t> &srcData, std::vector<uint8_t> &destData,
58 uint32_t destLen) const
59 {
60 auto srcLen = srcData.size();
61 if (srcLen > DBConstant::MAX_SYNC_BLOCK_SIZE || destLen > DBConstant::MAX_SYNC_BLOCK_SIZE) {
62 LOGE("Too long to uncompress, srcLen:%zu, destLen:%" PRIu32 ".", srcLen, destLen);
63 return -E_INVALID_ARGS;
64 }
65
66 // Alloc dest memory.
67 destData.resize(destLen);
68
69 // Uncompress.
70 uLongf destDataLen = destLen;
71 int errCode = uncompress(destData.data(), &destDataLen, srcData.data(), srcData.size());
72 if (errCode != Z_OK) {
73 LOGE("Uncompress failed, errCode = %d", errCode);
74 return -E_SYSTEM_API_FAIL;
75 }
76
77 destData.resize(destDataLen);
78 destData.shrink_to_fit();
79 return E_OK;
80 }
81 } // namespace DistributedDB
82 #endif // OMIT_ZLIB
83