OXYGENHUB
◆ main openmsx / src / EmuTime.hh
2.2 KiB · C++ · last changed chore(): initial commit 1 month ago source blame history raw
1
#ifndef EMUTIME_HH
2
#define EMUTIME_HH
3
4
#include "EmuDuration.hh"
5
6
#include "serialize.hh"
7
8
#include <cassert>
9
#include <iosfwd>
10
#include <limits>
11
12
namespace openmsx {
13
14
class EmuTime
15
{
16
public:
17
	static EmuTime dummy() { return {}; }
18
19
	// Note: default copy constructor and assignment operator are ok.
20
21
	[[nodiscard]] static constexpr EmuTime fromDouble(double d) {
22
		return EmuTime::zero() + EmuDuration::sec(d);
23
	}
24
	[[nodiscard]] static constexpr EmuTime fromUint64(uint64_t t) {
25
		return EmuTime(t);
26
	}
27
28
	[[nodiscard]] constexpr uint64_t toUint64() const { return time; }
29
	[[nodiscard]] constexpr double toDouble() const { return EmuDuration(time).toDouble(); }
30
31
	// comparison operators
32
	[[nodiscard]] constexpr auto operator<=>(const EmuTime&) const = default;
33
34
	// arithmetic operators
35
	[[nodiscard]] constexpr friend EmuTime operator+(EmuTime l, EmuDuration r)
36
		{ return EmuTime(l.toUint64() + r.toUint64()); }
37
	[[nodiscard]] constexpr friend EmuTime operator-(EmuTime l, EmuDuration r)
38
		{ assert(l.toUint64() >= r.toUint64());
39
		  return EmuTime(l.toUint64() - r.toUint64()); }
40
	[[nodiscard]] constexpr EmuTime saturateSubtract(EmuDuration r) const
41
		{ return EmuTime((time >= r.time) ? time - r.time : 0); }
42
	constexpr EmuTime& operator+=(EmuDuration d)
43
		{ time += d.time; return *this; }
44
	constexpr EmuTime& operator-=(EmuDuration d)
45
		{ assert(time >= d.time);
46
		  time -= d.time; return *this; }
47
	[[nodiscard]] constexpr friend EmuDuration operator-(EmuTime l, EmuTime r)
48
		{ assert(l.time >= r.time);
49
		  return EmuDuration(l.time - r.time); }
50
51
	[[nodiscard]] static constexpr EmuTime zero()
52
	{
53
		return EmuTime(uint64_t(0));
54
	}
55
	[[nodiscard]] static constexpr EmuTime infinity()
56
	{
57
		return EmuTime(std::numeric_limits<uint64_t>::max());
58
	}
59
60
	template<typename Archive>
61
	void serialize(Archive& ar, unsigned /*version*/)
62
	{
63
		ar.serialize("time", time);
64
	}
65
66
private:
67
	EmuTime() = default; // uninitialized
68
	constexpr explicit EmuTime(uint64_t n) : time(n) {}
69
70
private:
71
	uint64_t time;
72
73
	// friends
74
	friend std::ostream& operator<<(std::ostream& os, EmuTime time);
75
	friend class DynamicClock;
76
	template<unsigned, unsigned> friend class Clock;
77
};
78
79
template<> struct SerializeAsMemcpy<EmuTime> : std::true_type {};
80
81
} // namespace openmsx
82
83
#endif