• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "utils/zlib/zlib_regex.h"
18 
19 #include <memory>
20 
21 #include "utils/base/logging.h"
22 #include "utils/flatbuffers.h"
23 
24 namespace libtextclassifier3 {
25 
UncompressMakeRegexPattern(const UniLib & unilib,const flatbuffers::String * uncompressed_pattern,const CompressedBuffer * compressed_pattern,bool lazy_compile_regex,ZlibDecompressor * decompressor,std::string * result_pattern_text)26 std::unique_ptr<UniLib::RegexPattern> UncompressMakeRegexPattern(
27     const UniLib& unilib, const flatbuffers::String* uncompressed_pattern,
28     const CompressedBuffer* compressed_pattern, bool lazy_compile_regex,
29     ZlibDecompressor* decompressor, std::string* result_pattern_text) {
30   UnicodeText unicode_regex_pattern;
31   std::string decompressed_pattern;
32   if (compressed_pattern != nullptr &&
33       compressed_pattern->buffer() != nullptr) {
34     if (decompressor == nullptr ||
35         !decompressor->MaybeDecompress(compressed_pattern,
36                                        &decompressed_pattern)) {
37       TC3_LOG(ERROR) << "Cannot decompress pattern.";
38       return nullptr;
39     }
40     unicode_regex_pattern =
41         UTF8ToUnicodeText(decompressed_pattern.data(),
42                           decompressed_pattern.size(), /*do_copy=*/false);
43   } else {
44     if (uncompressed_pattern == nullptr) {
45       TC3_LOG(ERROR) << "Cannot load uncompressed pattern.";
46       return nullptr;
47     }
48     unicode_regex_pattern =
49         UTF8ToUnicodeText(uncompressed_pattern->c_str(),
50                           uncompressed_pattern->Length(), /*do_copy=*/false);
51   }
52 
53   if (result_pattern_text != nullptr) {
54     *result_pattern_text = unicode_regex_pattern.ToUTF8String();
55   }
56 
57   std::unique_ptr<UniLib::RegexPattern> regex_pattern;
58   if (lazy_compile_regex) {
59     regex_pattern = unilib.CreateLazyRegexPattern(unicode_regex_pattern);
60   } else {
61     regex_pattern = unilib.CreateRegexPattern(unicode_regex_pattern);
62   }
63 
64   if (!regex_pattern) {
65     TC3_LOG(ERROR) << "Could not create pattern: "
66                    << unicode_regex_pattern.ToUTF8String();
67   }
68   return regex_pattern;
69 }
70 
71 }  // namespace libtextclassifier3
72