1 // Copyright 2018 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_TASK_COMMON_LAZY_NOW_H_ 6 #define BASE_TASK_COMMON_LAZY_NOW_H_ 7 8 #include <optional> 9 10 #include "base/base_export.h" 11 #include "base/memory/raw_ptr_exclusion.h" 12 #include "base/time/time.h" 13 14 namespace base { 15 16 class TickClock; 17 18 // Now() is somewhat expensive so it makes sense not to call Now() unless we 19 // really need to and to avoid subsequent calls if already called once. 20 // LazyNow objects are expected to be short-living to represent accurate time. 21 class BASE_EXPORT LazyNow { 22 public: 23 explicit LazyNow(TimeTicks now); 24 explicit LazyNow(std::optional<TimeTicks> now, const TickClock* tick_clock); 25 explicit LazyNow(const TickClock* tick_clock); 26 LazyNow(const LazyNow&) = delete; 27 LazyNow& operator=(const LazyNow&) = delete; 28 29 LazyNow(LazyNow&& move_from) noexcept; 30 31 // Result will not be updated on any subsesequent calls. 32 TimeTicks Now(); 33 has_value()34 bool has_value() const { return !!now_; } 35 36 private: 37 std::optional<TimeTicks> now_; 38 // RAW_PTR_EXCLUSION: The pointee doesn't need UaF protection (it has the same 39 // lifetime as the thread/sequence). 40 RAW_PTR_EXCLUSION const TickClock* tick_clock_; // Not owned. 41 }; 42 43 } // namespace base 44 45 #endif // BASE_TASK_COMMON_LAZY_NOW_H_ 46