1 /* 2 * Copyright (c) 2021 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 FOUNDATION_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_PAGE_ID_POOL_H 17 #define FOUNDATION_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_PAGE_ID_POOL_H 18 19 #include <atomic> 20 #include <cstdint> 21 22 #include "base/utils/noncopyable.h" 23 24 namespace OHOS::Ace::Framework { 25 26 inline constexpr int32_t INVALID_PAGE_ID = -1; 27 inline constexpr int32_t MAX_PAGE_ID_SIZE = sizeof(uint64_t) * 8; 28 29 class PageIdPool final : private NonCopyable { 30 public: GenerateNextPageId()31 int32_t GenerateNextPageId() 32 { 33 for (int32_t idx = 0; idx < MAX_PAGE_ID_SIZE; ++idx) { 34 uint64_t bitMask = (1ULL << idx); 35 if ((bitMask & pageIdPool_.fetch_or(bitMask, std::memory_order_relaxed)) == 0) { 36 return idx; 37 } 38 } 39 return INVALID_PAGE_ID; 40 } 41 RecyclePageId(int32_t pageId)42 void RecyclePageId(int32_t pageId) 43 { 44 if (pageId < 0 || pageId >= MAX_PAGE_ID_SIZE) { 45 return; 46 } 47 uint64_t bitMask = (1ULL << pageId); 48 pageIdPool_.fetch_and(~bitMask, std::memory_order_relaxed); 49 } 50 51 private: 52 std::atomic<uint64_t> pageIdPool_ = 0; 53 }; 54 55 } // namespace OHOS::Ace::Framework 56 57 #endif // FOUNDATION_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_PAGE_ID_POOL_H 58