1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
#pragma once
#include "compat/assert.hpp"
#include "nanosecond.hpp"
namespace floormat {
template<typename T>
requires (std::is_same_v<T, double>)
Ns operator*(const Ns& lhs, T b)
{
constexpr double max{uint64_t{1} << 53};
auto a = lhs.stamp;
fm_assert(b >= 0);
fm_assert(b <= max);
auto x = double(a) * b;
fm_assert(x >= 0);
fm_assert(x <= max);
return Ns{(uint64_t)x};
}
constexpr Ns operator+(const Ns& lhs, const Ns& rhs)
{
constexpr auto max = (uint64_t)-1;
auto a = lhs.stamp, b = rhs.stamp;
fm_assert(max - a >= b);
return Ns{a + b};
}
constexpr Ns operator-(const Ns& lhs, const Ns& rhs)
{
auto a = lhs.stamp, b = rhs.stamp;
fm_assert(a >= b);
return Ns{a - b};
}
template<typename T>
requires (std::is_integral_v<T> && std::is_unsigned_v<T>)
constexpr Ns operator*(const Ns& lhs, T rhs)
{
auto a = lhs.stamp, b = uint64_t{rhs};
auto x = a * b;
fm_assert(b == 0 || x / b == a);
return Ns{x};
}
template<typename T>
requires (std::is_integral_v<T> && std::is_signed_v<T> && sizeof(T) < sizeof(uint64_t))
constexpr Ns operator*(const Ns& lhs, T rhs)
{
fm_assert(rhs >= T{0});
auto b = uint64_t(rhs);
auto x = lhs.stamp * b;
fm_assert(b == 0 || x / b == lhs.stamp);
return Ns{x};
}
template<typename T>
constexpr Ns operator*(T lhs, const Ns& rhs)
{
return rhs * lhs;
}
constexpr uint64_t operator/(const Ns& lhs, const Ns& rhs)
{
auto a = lhs.stamp, b = rhs.stamp;
fm_assert(b != 0);
return a / b;
}
constexpr Ns operator/(const Ns& lhs, uint64_t b)
{
auto a = lhs.stamp;
fm_assert(b != 0);
return Ns{a / b};
}
constexpr uint64_t operator%(const Ns& lhs, const Ns& rhs)
{
auto a = lhs.stamp, b = rhs.stamp;
fm_assert(b != 0);
return a % b;
}
constexpr Ns operator%(const Ns& lhs, uint64_t b)
{
auto a = lhs.stamp;
fm_assert(b != 0);
return Ns{a % b};
}
constexpr Ns& operator+=(Ns& lhs, const Ns& rhs)
{
constexpr auto max = (uint64_t)-1;
auto b = rhs.stamp;
fm_assert(max - lhs.stamp >= b);
lhs.stamp += b;
return lhs;
}
constexpr std::strong_ordering operator<=>(const Ns& lhs, const Ns& rhs)
{
auto a = lhs.stamp, b = rhs.stamp;
return a <=> b;
}
} // namespace floormat
|