xref: /aosp_15_r20/external/libtextclassifier/native/utils/zlib/zlib.h (revision 993b0882672172b81d12fad7a7ac0c3e5c824a12)
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
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 // Functions to compress and decompress low entropy entries in the model.
18 
19 #ifndef LIBTEXTCLASSIFIER_UTILS_ZLIB_ZLIB_H_
20 #define LIBTEXTCLASSIFIER_UTILS_ZLIB_ZLIB_H_
21 
22 #include <vector>
23 
24 #include "utils/base/integral_types.h"
25 #include "utils/zlib/buffer_generated.h"
26 #include <zlib.h>
27 
28 namespace libtextclassifier3 {
29 
30 class ZlibDecompressor {
31  public:
32   static std::unique_ptr<ZlibDecompressor> Instance();
33   ~ZlibDecompressor();
34 
35   bool Decompress(const uint8* buffer, const int buffer_size,
36                   const int uncompressed_size, std::string* out);
37   bool MaybeDecompress(const CompressedBuffer* compressed_buffer,
38                        std::string* out);
39   bool MaybeDecompress(const CompressedBufferT* compressed_buffer,
40                        std::string* out);
41   bool MaybeDecompressOptionallyCompressedBuffer(
42       const flatbuffers::String* uncompressed_buffer,
43       const CompressedBuffer* compressed_buffer, std::string* out);
44   bool MaybeDecompressOptionallyCompressedBuffer(
45       const flatbuffers::Vector<uint8>* uncompressed_buffer,
46       const CompressedBuffer* compressed_buffer, std::string* out);
47 
48  private:
49   explicit ZlibDecompressor();
50   z_stream stream_;
51   bool initialized_;
52 };
53 
54 class ZlibCompressor {
55  public:
56   static std::unique_ptr<ZlibCompressor> Instance();
57   ~ZlibCompressor();
58 
59   void Compress(const std::string& uncompressed_content,
60                 CompressedBufferT* out);
61 
62  private:
63   explicit ZlibCompressor(const int level = Z_BEST_COMPRESSION,
64                           // Tmp. buffer size was set based on the current set
65                           // of patterns to be compressed.
66                           const int tmp_buffer_size = 64 * 1024);
67   z_stream stream_;
68   std::unique_ptr<Bytef[]> buffer_;
69   unsigned int buffer_size_;
70   bool initialized_;
71 };
72 
73 }  // namespace libtextclassifier3
74 
75 #endif  // LIBTEXTCLASSIFIER_UTILS_ZLIB_ZLIB_H_
76