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 #ifndef PKG_ALGORITHM_DEFLATE_H
16 #define PKG_ALGORITHM_DEFLATE_H
17 
18 #include "pkg_algorithm.h"
19 #include "pkg_stream.h"
20 #include "pkg_utils.h"
21 #include "zlib.h"
22 
23 namespace Hpackage {
24 class PkgAlgoDeflate : public PkgAlgorithm {
25 public:
PkgAlgoDeflate(const ZipFileInfo & info)26     explicit PkgAlgoDeflate(const ZipFileInfo &info)
27     {
28         level_ = info.level;
29         method_ = info.method;
30         windowBits_ = info.windowBits;
31         memLevel_ = info.memLevel;
32         strategy_ = info.strategy;
33     }
34 
~PkgAlgoDeflate()35     ~PkgAlgoDeflate() override {}
36 
37     int32_t Pack(const PkgStreamPtr inStream, const PkgStreamPtr outStream,
38         PkgAlgorithmContext &context) override;
39 
40     int32_t Unpack(const PkgStreamPtr inStream,
41         const PkgStreamPtr outStream, PkgAlgorithmContext &context) override;
42 
43 private:
44     int32_t PackCalculate(PkgAlgorithmContext &context, const PkgStreamPtr inStream,
45         const PkgStreamPtr outStream, const DigestAlgorithm::DigestAlgorithmPtr algorithm);
46 
47     int32_t ReadUnpackData(const PkgStreamPtr inStream, PkgBuffer &inBuffer,
48         z_stream &zstream, PkgAlgorithmContext &context, size_t &readLen);
49 
50     int32_t CalculateUnpackData(z_stream &zstream, uint32_t &crc, int32_t &ret,
51         PkgAlgorithmContext &context, PkgAlgorithmContext &unpackContext);
52 
53     int32_t UnpackCalculate(PkgAlgorithmContext &context, const PkgStreamPtr inStream,
54         const PkgStreamPtr outStream, DigestAlgorithm::DigestAlgorithmPtr algorithm);
55 
56     int32_t InitStream(z_stream &zstream, bool zip, PkgBuffer &inBuffer, PkgBuffer &outBuffer);
57 
58     void ReleaseStream(z_stream &zstream, bool zip) const;
59 
60     int32_t DeflateData(const PkgStreamPtr outStream,
61         z_stream &zstream, int32_t flush, PkgBuffer &outBuffer, size_t &destOffset) const;
62 
63 private:
64     int32_t level_ {0};
65     int32_t method_ {0};
66     int32_t windowBits_ {0};
67     int32_t memLevel_ {0};
68     int32_t strategy_ {0};
69 };
70 } // namespace Hpackage
71 #endif
72