COROIO: coroio/base.hpp Source File
COROIO
 
Loading...
Searching...
No Matches
base.hpp
1#pragma once
2
3#include <chrono>
4#include <stdexcept>
5#include <cstring>
6#include <coroutine>
7#include <tuple>
8#include <iostream>
9
10#include <time.h>
11
12namespace NNet {
13
14using TClock = std::chrono::steady_clock;
15using TTime = TClock::time_point;
16using THandle = std::coroutine_handle<>;
17
18struct TTimer {
19 TTime Deadline;
20 unsigned Id;
21 THandle Handle;
22 bool operator<(const TTimer& e) const {
23 return std::tuple(Deadline, Id, static_cast<bool>(Handle)) > std::tuple(e.Deadline, e.Id, static_cast<bool>(e.Handle));
24 }
25};
26
28 THandle Read = {};
29 THandle Write = {};
30 THandle RHup = {};
31
32 bool Empty() const {
33 return !Read && !Write && !RHup;
34 }
35
36 void Reset() {
37 Read = {};
38 Write = {};
39 RHup = {};
40 }
41};
42
43struct TEvent {
44 int Fd;
45 enum {
46 READ = 1,
47 WRITE = 2,
48 RHUP = 4
49 };
50 int Type;
51 THandle Handle;
52
53 bool Match(const TEvent& other) const {
54 return Fd == other.Fd && (Type & other.Type);
55 }
56};
57
58template<typename T1, typename T2>
59inline std::tuple<T1, T2>
60GetDurationPair(TTime now, TTime deadline, std::chrono::milliseconds maxDuration)
61{
62 if (now > deadline) {
63 return std::make_tuple(T1(0), T2(0));
64 } else {
65 auto duration = (deadline - now);
66 if (duration > maxDuration) {
67 duration = maxDuration;
68 }
69 auto part1 = std::chrono::duration_cast<T1>(duration);
70 duration -= part1;
71 auto part2 = std::chrono::duration_cast<T2>(duration);
72
73 return std::make_tuple(part1,part2);
74 }
75}
76
77inline timespec GetTimespec(TTime now, TTime deadline, std::chrono::milliseconds maxDuration)
78{
79 auto [p1, p2] = GetDurationPair<std::chrono::seconds, std::chrono::nanoseconds>(now, deadline, maxDuration);
80 timespec ret;
81 ret.tv_sec = p1.count();
82 ret.tv_nsec = p2.count();
83 return ret;
84}
85
86} // namespace NNet
Definition base.hpp:43
Definition base.hpp:27
Definition base.hpp:18