1 /* 2 * Copyright (c) 2021-2022 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 #include "index_util.h" 16 17 #include "locale_config.h" 18 #include "locid.h" 19 #include "string" 20 #include "unistr.h" 21 #include "utypes.h" 22 #include "vector" 23 24 namespace OHOS { 25 namespace Global { 26 namespace I18n { IndexUtil(const std::string & localeTag)27IndexUtil::IndexUtil(const std::string &localeTag) 28 { 29 UErrorCode status = U_ZERO_ERROR; 30 if (localeTag == "") { 31 icu::Locale locale(LocaleConfig::GetSystemLocale().c_str()); 32 index = std::make_unique<icu::AlphabeticIndex>(locale, status); 33 } else { 34 icu::Locale locale(localeTag.c_str()); 35 index = std::make_unique<icu::AlphabeticIndex>(locale, status); 36 } 37 if (U_SUCCESS(status)) { 38 createSuccess = true; 39 } 40 } 41 ~IndexUtil()42IndexUtil::~IndexUtil() 43 { 44 } 45 GetIndexList()46std::vector<std::string> IndexUtil::GetIndexList() 47 { 48 UErrorCode status = U_ZERO_ERROR; 49 std::vector<std::string> indexList; 50 if (!createSuccess) { 51 return indexList; 52 } 53 index->resetBucketIterator(status); 54 while (index->nextBucket(status)) { 55 if (U_SUCCESS(status)) { 56 icu::UnicodeString unicodeString = index->getBucketLabel(); 57 std::string label; 58 unicodeString.toUTF8String(label); 59 indexList.push_back(label); 60 } 61 } 62 return indexList; 63 } 64 AddLocale(const std::string & localeTag)65void IndexUtil::AddLocale(const std::string &localeTag) 66 { 67 UErrorCode status = U_ZERO_ERROR; 68 icu::Locale locale(localeTag.c_str()); 69 if (createSuccess) { 70 index->addLabels(locale, status); 71 } 72 } 73 GetIndex(const std::string & String)74std::string IndexUtil::GetIndex(const std::string &String) 75 { 76 if (!createSuccess) { 77 return ""; 78 } 79 UErrorCode status = U_ZERO_ERROR; 80 icu::UnicodeString unicodeString(String.c_str()); 81 int32_t bucketNumber = index->getBucketIndex(unicodeString, status); 82 if (!U_SUCCESS(status)) { 83 return ""; 84 } 85 index->resetBucketIterator(status); 86 for (int32_t i = 0; i <= bucketNumber; i++) { 87 index->nextBucket(status); 88 if (!U_SUCCESS(status)) { 89 return ""; 90 } 91 } 92 icu::UnicodeString label = index->getBucketLabel(); 93 std::string result; 94 label.toUTF8String(result); 95 return result; 96 } 97 } // namespace I18n 98 } // namespace Global 99 } // namespace OHOS