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 #ifndef LIBTEXTCLASSIFIER_UTILS_I18N_LOCALE_H_ 18 #define LIBTEXTCLASSIFIER_UTILS_I18N_LOCALE_H_ 19 20 #include <string> 21 #include <vector> 22 23 #include "utils/base/integral_types.h" 24 #include "utils/base/logging.h" 25 #include "utils/strings/stringpiece.h" 26 27 namespace libtextclassifier3 { 28 29 class Locale { 30 public: 31 // Constructs the object from a valid BCP47 tag. If the tag is invalid, 32 // an object is created that gives false when IsInvalid() is called. 33 static Locale FromBCP47(const std::string& locale_tag); 34 35 // Creates a prototypical invalid locale object. Invalid()36 static Locale Invalid() { 37 Locale locale(/*language=*/"", /*script=*/"", /*region=*/""); 38 locale.is_valid_ = false; 39 return locale; 40 } 41 Language()42 std::string Language() const { return language_; } 43 Script()44 std::string Script() const { return script_; } 45 Region()46 std::string Region() const { return region_; } 47 IsValid()48 bool IsValid() const { return is_valid_; } 49 bool IsUnknown() const; 50 51 // Returns whether any of the given locales is supported by any of the 52 // supported locales. Returns default value if the given 'locales' list, or 53 // 'supported_locales' list is empty or an unknown locale is found. 54 // Locale::FromBCP47("*") means any locale. 55 static bool IsAnyLocaleSupported(const std::vector<Locale>& locales, 56 const std::vector<Locale>& supported_locales, 57 bool default_value); 58 59 private: Locale(const std::string & language,const std::string & script,const std::string & region)60 Locale(const std::string& language, const std::string& script, 61 const std::string& region) 62 : language_(language), 63 script_(script), 64 region_(region), 65 is_valid_(true) {} 66 67 static bool IsLocaleSupported(const Locale& locale, 68 const std::vector<Locale>& supported_locales, 69 bool default_value); 70 71 std::string language_; 72 std::string script_; 73 std::string region_; 74 bool is_valid_; 75 }; 76 77 // Pretty-printing function for Locale. 78 logging::LoggingStringStream& operator<<(logging::LoggingStringStream& stream, 79 const Locale& locale); 80 81 // Parses a comma-separated list of BCP47 tags. 82 bool ParseLocales(StringPiece locales_list, std::vector<Locale>* locales); 83 84 } // namespace libtextclassifier3 85 86 #endif // LIBTEXTCLASSIFIER_UTILS_I18N_LOCALE_H_ 87