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 DISTRIBUTEDDATAMGR_PASTEBOARD_DEDUPLICATE_MEMORY_H 17 #define DISTRIBUTEDDATAMGR_PASTEBOARD_DEDUPLICATE_MEMORY_H 18 19 #include <cstdint> 20 #include <list> 21 22 namespace OHOS { 23 namespace MiscServices { 24 25 template <typename T> 26 class DeduplicateMemory { 27 public: 28 explicit DeduplicateMemory(int64_t expirationMilliSeconds); 29 ~DeduplicateMemory(); 30 bool IsDuplicate(const T &data); 31 32 private: 33 int64_t GetTimestamp(); 34 void ClearExpiration(); 35 bool FindExist(const T &data); 36 37 struct MemoryIdentity { 38 int64_t timestamp; 39 const T data; 40 }; 41 42 std::list<MemoryIdentity> memory_; 43 int64_t expirationMS_; 44 }; 45 46 template <typename T> DeduplicateMemory(int64_t expirationMilliSeconds)47DeduplicateMemory<T>::DeduplicateMemory(int64_t expirationMilliSeconds) : expirationMS_(expirationMilliSeconds) 48 { 49 } 50 51 template <typename T> ~DeduplicateMemory()52DeduplicateMemory<T>::~DeduplicateMemory() 53 { 54 memory_.clear(); 55 } 56 57 template <typename T> IsDuplicate(const T &data)58bool DeduplicateMemory<T>::IsDuplicate(const T &data) 59 { 60 ClearExpiration(); 61 if (FindExist(data)) { 62 return true; 63 } 64 int64_t timestamp = GetTimestamp(); 65 memory_.push_back(MemoryIdentity({.timestamp = timestamp, .data = data})); 66 return false; 67 } 68 69 template <typename T> FindExist(const T &data)70bool DeduplicateMemory<T>::FindExist(const T &data) 71 { 72 for (const MemoryIdentity &item : memory_) { 73 if (item.data == data) { 74 return true; 75 } 76 } 77 return false; 78 } 79 80 template <typename T> GetTimestamp()81int64_t DeduplicateMemory<T>::GetTimestamp() 82 { 83 return std::chrono::duration_cast<std::chrono::milliseconds>( 84 std::chrono::steady_clock::now().time_since_epoch()).count(); 85 } 86 87 template <typename T> ClearExpiration()88void DeduplicateMemory<T>::ClearExpiration() 89 { 90 int64_t timestamp = GetTimestamp(); 91 if (timestamp < expirationMS_) { 92 return; 93 } 94 int64_t expirationTimestamp = timestamp - expirationMS_; 95 memory_.remove_if([expirationTimestamp](const MemoryIdentity &identity) { 96 return expirationTimestamp > identity.timestamp; 97 }); 98 } 99 } // namespace MiscServices 100 } // namespace OHOS 101 102 #endif // DISTRIBUTEDDATAMGR_PASTEBOARD_DEDUPLICATE_MEMORY_H 103