-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbase.hpp
71 lines (59 loc) · 1.62 KB
/
base.hpp
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
#pragma once
#include <chrono>
#include <stdexcept>
#include <cstring>
#include <coroutine>
#include <tuple>
#include <iostream>
#include <time.h>
namespace NNet {
using TClock = std::chrono::steady_clock;
using TTime = TClock::time_point;
using THandle = std::coroutine_handle<>;
struct TTimer {
TTime Deadline;
int Fd;
THandle Handle;
bool operator<(const TTimer& e) const {
return std::tuple(Deadline, Fd, !static_cast<bool>(Handle)) < std::tuple(e.Deadline, e.Fd, !static_cast<bool>(e.Handle));
}
};
struct THandlePair {
THandle Read;
THandle Write;
};
struct TEvent {
int Fd;
enum {
READ = 1,
WRITE = 2
};
int Type;
THandle Handle;
bool Match(const TEvent& other) const {
return Fd == other.Fd && (Type & other.Type);
}
};
template<typename T1, typename T2>
inline std::tuple<T1, T2>
GetDurationPair(TTime now, TTime deadline, std::chrono::milliseconds maxDuration)
{
if (now > deadline) {
return std::make_tuple(T1(0), T2(0));
} else {
auto duration = (deadline - now);
if (duration > maxDuration) {
duration = maxDuration;
}
auto part1 = std::chrono::duration_cast<T1>(duration);
duration -= part1;
auto part2 = std::chrono::duration_cast<T2>(duration);
return std::make_tuple(part1,part2);
}
}
inline timespec GetTimespec(TTime now, TTime deadline, std::chrono::milliseconds maxDuration)
{
auto [p1, p2] = GetDurationPair<std::chrono::seconds, std::chrono::nanoseconds>(now, deadline, maxDuration);
return {p1.count(), p2.count()};
}
} // namespace NNet