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 #ifndef HILOG_COMPRESS_H
17 #define HILOG_COMPRESS_H
18 
19 #include <iostream>
20 #ifdef USING_ZSTD_COMPRESS
21 #define ZSTD_STATIC_LINKING_ONLY
22 #include "include/common.h"
23 #include "zstd.h"
24 #endif
25 #include <zlib.h>
26 
27 #include <hilog_common.h>
28 #include <log_utils.h>
29 
30 namespace OHOS {
31 namespace HiviewDFX {
32 using LogPersisterBuffer = struct {
33     char content[MAX_PERSISTER_BUFFER_SIZE];
34     uint32_t offset;
35 };
36 
37 using CompressAlg = enum {
38     COMPRESS_TYPE_NONE = 0,
39     COMPRESS_TYPE_ZSTD,
40     COMPRESS_TYPE_ZLIB,
41 };
42 
43 class LogCompress {
44 public:
45     LogCompress() = default;
46     virtual ~LogCompress() = default;
47     virtual int Compress(const LogPersisterBuffer &inBuffer, LogPersisterBuffer &compressBuffer) = 0;
48     // Compress Types&Strings Map
49     static std::string CompressType2Str(uint16_t compressType);
50     static uint16_t Str2CompressType(const std::string& str);
51 private:
52     static StringMap g_CompressTypes;
53 };
54 
55 class NoneCompress : public LogCompress {
56 public:
57     int Compress(const LogPersisterBuffer &inBuffer, LogPersisterBuffer &compressBuffer) override;
58 };
59 
60 class ZlibCompress : public LogCompress {
61 public:
62     int Compress(const LogPersisterBuffer &inBuffer, LogPersisterBuffer &compressBuffer) override;
63 private:
64     static const uint16_t CHUNK = 16384;
65     char buffIn[CHUNK] = {0};
66     char buffOut[CHUNK] = {0};
67 
68     z_stream cStream;
69 };
70 
71 class ZstdCompress : public LogCompress {
72 public:
73     int Compress(const LogPersisterBuffer &inBuffer, LogPersisterBuffer &compressBuffer) override;
74 private:
75 #ifdef USING_ZSTD_COMPRESS
76     static const uint16_t CHUNK = 16384;
77     char buffIn[CHUNK] = {0};
78     char buffOut[CHUNK] = {0};
79     ZSTD_CCtx* cctx;
80 #endif
81 };
82 } // namespace HiviewDFX
83 } // namespace OHOS
84 #endif /* HILOG_COMPRESS_H */
85