1 /* 2 * Copyright (c) 2024-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 #ifndef CAMERA_FRAMEWORK_FIXED_SIZE_LIST 16 #define CAMERA_FRAMEWORK_FIXED_SIZE_LIST 17 #include <vector> 18 #include <mutex> 19 #include <thread> 20 #include <functional> 21 #include <optional> 22 23 namespace OHOS { 24 namespace CameraStandard { 25 template <typename T> 26 class FixedSizeList { 27 public: FixedSizeList(size_t size)28 FixedSizeList(size_t size) : maxSize(size), currentSize(0), index(0) 29 { 30 data.resize(size); 31 } 32 add(T value)33 void add(T value) 34 { 35 std::lock_guard<std::mutex> lock(mtx); 36 data[index] = value; 37 index = (index + 1) % maxSize; 38 if (currentSize < maxSize) { 39 ++currentSize; 40 } 41 } 42 find_if(const std::function<bool (const T &)> & predicate)43 std::optional<T> find_if(const std::function<bool(const T&)>& predicate) 44 { 45 std::lock_guard<std::mutex> lock(mtx); 46 for (size_t i = 0; i < currentSize; ++i) { 47 if (predicate(data[i])) { 48 T result = data[i]; 49 remove_at(i); 50 return result; 51 } 52 } 53 return std::nullopt; 54 } 55 clear()56 void clear() 57 { 58 std::lock_guard<std::mutex> lock(mtx); 59 data.clear(); 60 data.resize(maxSize); 61 currentSize = 0; 62 index = 0; 63 } 64 65 private: remove_at(size_t position)66 void remove_at(size_t position) 67 { 68 if (position < currentSize) { 69 for (size_t i = position; i < currentSize - 1; ++i) { 70 data[i] = data[i + 1]; 71 } 72 --currentSize; 73 index = (index - 1 + maxSize) % maxSize; 74 } 75 } 76 77 std::vector<T> data; 78 size_t maxSize; 79 size_t currentSize; 80 size_t index; 81 mutable std::mutex mtx; // mutable to allow const methods to lock the mutex 82 }; 83 } // namespace CameraStandard 84 } // namespace OHOS 85 #endif //CAMERA_FRAMEWORK_FIXED_SIZE_LIST