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/grammar/rules-utils.h"
18 
19 namespace libtextclassifier3::grammar {
20 
ParseRulesLocales(const RulesSet * rules)21 std::vector<std::vector<Locale>> ParseRulesLocales(const RulesSet* rules) {
22   if (rules == nullptr || rules->rules() == nullptr) {
23     return {};
24   }
25   std::vector<std::vector<Locale>> locales(rules->rules()->size());
26   for (int i = 0; i < rules->rules()->size(); i++) {
27     const grammar::RulesSet_::Rules* rules_shard = rules->rules()->Get(i);
28     if (rules_shard->locale() == nullptr) {
29       continue;
30     }
31     for (const LanguageTag* tag : *rules_shard->locale()) {
32       locales[i].push_back(Locale::FromLanguageTag(tag));
33     }
34   }
35   return locales;
36 }
37 
SelectLocaleMatchingShards(const RulesSet * rules,const std::vector<std::vector<Locale>> & shard_locales,const std::vector<Locale> & locales)38 std::vector<const grammar::RulesSet_::Rules*> SelectLocaleMatchingShards(
39     const RulesSet* rules,
40     const std::vector<std::vector<Locale>>& shard_locales,
41     const std::vector<Locale>& locales) {
42   std::vector<const grammar::RulesSet_::Rules*> shards;
43   if (rules->rules() == nullptr) {
44     return shards;
45   }
46   for (int i = 0; i < shard_locales.size(); i++) {
47     if (shard_locales[i].empty() ||
48         Locale::IsAnyLocaleSupported(locales,
49                                      /*supported_locales=*/shard_locales[i],
50                                      /*default_value=*/false)) {
51       shards.push_back(rules->rules()->Get(i));
52     }
53   }
54   return shards;
55 }
56 
57 }  // namespace libtextclassifier3::grammar
58