1 /** 2 * Copyright (c) 2024 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 16 #ifndef PANDA_PLUGINS_ETS_STDLIB_NATIVE_CORE_INTLFORMATTERSCACHE_H 17 #define PANDA_PLUGINS_ETS_STDLIB_NATIVE_CORE_INTLFORMATTERSCACHE_H 18 19 #include "libpandabase/macros.h" 20 #include "libpandabase/os/mutex.h" 21 #include "unicode/numberformatter.h" 22 #include "unicode/numberrangeformatter.h" 23 #include "unicode/locid.h" 24 #include "unicode/coll.h" 25 #include "unicode/unistr.h" 26 27 #include <string> 28 #include <unordered_map> 29 #include <memory> 30 #include <iterator> 31 #include <random> 32 33 namespace ark::ets::stdlib { 34 35 /// Contains information about cache with LocalizedNumberFormatter and LocalizedNumberRangeFormatter 36 class IntlFormattersCache final { 37 public: 38 NO_COPY_SEMANTIC(IntlFormattersCache); 39 NO_MOVE_SEMANTIC(IntlFormattersCache); 40 41 IntlFormattersCache(); 42 ~IntlFormattersCache() = default; 43 44 icu::number::LocalizedNumberFormatter &NumFmtsCacheInvalidation(const std::string &locTag, const icu::Locale &loc); 45 46 icu::number::LocalizedNumberRangeFormatter &NumRangeFmtsCacheInvalidation(const std::string &locTag, 47 const icu::Locale &loc); 48 49 private: 50 using LocNumFmt = icu::number::LocalizedNumberFormatter; 51 using LocNumRangeFmt = icu::number::LocalizedNumberRangeFormatter; 52 53 struct NumberFormatters { 54 std::unique_ptr<LocNumFmt> numFmt; 55 std::unique_ptr<LocNumRangeFmt> numRangeFmt; 56 }; 57 58 using CacheUMap = std::unordered_map<std::string, NumberFormatters>; 59 using CacheUMapIterator = CacheUMap::iterator; 60 61 os::memory::RecursiveMutex mtx_; 62 CacheUMap cache_ GUARDED_BY(mtx_); 63 static constexpr uint32_t MAX_SIZE_CACHE = 512U; 64 static constexpr double ERASE_RATIO = 0.1; // Erase 10% of MAX_SIZE_CACHE 65 static constexpr uint32_t ERASE_AMOUNT = std::max(1U, static_cast<uint32_t>(MAX_SIZE_CACHE *ERASE_RATIO)); 66 67 void EraseRandFmtsGroupByEraseRatio(); 68 }; 69 70 } // namespace ark::ets::stdlib 71 72 #endif // PANDA_PLUGINS_ETS_STDLIB_NATIVE_CORE_INTLFORMATTERSCACHE_H 73