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 HIDEBUG_UTIL_H_ 17 #define HIDEBUG_UTIL_H_ 18 19 #include <cstdint> 20 #include <functional> 21 #include <optional> 22 23 namespace OHOS { 24 namespace HiviewDFX { 25 26 int64_t GetElapsedNanoSecondsSinceBoot(); 27 28 template<typename T> 29 class CachedValue { 30 public: 31 CachedValue() = default; GetOrUpdateCachedValue(int64_t effectiveTime,std::function<bool (T &)> getValue)32 std::optional<T> GetOrUpdateCachedValue(int64_t effectiveTime, std::function<bool(T &)> getValue) 33 { 34 int64_t currentTime = GetElapsedNanoSecondsSinceBoot(); 35 if (currentTime <= expirationTime_) { 36 return cachedValue_; 37 } 38 if (getValue(cachedValue_)) { 39 expirationTime_ = currentTime + effectiveTime; 40 return cachedValue_; 41 } 42 return {}; 43 }; 44 45 private: 46 T cachedValue_; 47 int64_t expirationTime_ = -1; 48 }; 49 } 50 } 51 #endif // HIDEBUG_UTIL_H_ 52