1 /** 2 * Copyright (c) 2024-2025 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 "IntlNumberFormatters.h" 22 #include "unicode/coll.h" 23 24 #include <unordered_map> 25 #include <memory> 26 #include <iterator> 27 #include <random> 28 29 namespace ark::ets::stdlib::intl { 30 31 /// Contains information about cache with LocalizedNumberFormatter and LocalizedNumberRangeFormatter 32 class IntlFormattersCache final { 33 public: 34 NO_COPY_SEMANTIC(IntlFormattersCache); 35 NO_MOVE_SEMANTIC(IntlFormattersCache); 36 37 IntlFormattersCache(); 38 ~IntlFormattersCache() = default; 39 40 LocNumFmt &NumFmtsCacheInvalidation(ani_env *env, const ParsedOptions &options, ani_status &status); 41 42 LocNumRangeFmt &NumRangeFmtsCacheInvalidation(ani_env *env, const ParsedOptions &options, ani_status &status); 43 44 private: 45 struct NumberFormatters { 46 std::unique_ptr<LocNumFmt> numFmt; 47 std::unique_ptr<LocNumRangeFmt> numRangeFmt; 48 std::unique_ptr<ParsedOptions> options; 49 }; 50 51 using CacheUMap = std::unordered_map<std::string, NumberFormatters>; 52 using CacheUMapIterator = CacheUMap::iterator; 53 54 os::memory::RecursiveMutex mtx_; 55 CacheUMap cache_ GUARDED_BY(mtx_); 56 static constexpr uint32_t MAX_SIZE_CACHE = 512U; 57 static constexpr double ERASE_RATIO = 0.1; // Erase 10% of MAX_SIZE_CACHE 58 static constexpr uint32_t ERASE_AMOUNT = std::max(1U, static_cast<uint32_t>(MAX_SIZE_CACHE *ERASE_RATIO)); 59 60 void EraseRandFmtsGroupByEraseRatio(); 61 }; 62 63 } // namespace ark::ets::stdlib::intl 64 65 #endif // PANDA_PLUGINS_ETS_STDLIB_NATIVE_CORE_INTLFORMATTERSCACHE_H 66