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
33struct TEvent {
34 int Fd;
35 enum {
36 READ = 1,
37 WRITE = 2,
38 RHUP = 4
39 };
40 int Type;
41 THandle Handle;
42
43 bool Match(const TEvent& other) const {
44 return Fd == other.Fd && (Type & other.Type);
45 }
46};
47
48template<typename T1, typename T2>
49inline std::tuple<T1, T2>
50GetDurationPair(TTime now, TTime deadline, std::chrono::milliseconds maxDuration)
51{
52 if (now > deadline) {
53 return std::make_tuple(T1(0), T2(0));
54 } else {
55 auto duration = (deadline - now);
56 if (duration > maxDuration) {
57 duration = maxDuration;
58 }
59 auto part1 = std::chrono::duration_cast<T1>(duration);
60 duration -= part1;
61 auto part2 = std::chrono::duration_cast<T2>(duration);
62
63 return std::make_tuple(part1,part2);
64 }
65}
66
67inline timespec GetTimespec(TTime now, TTime deadline, std::chrono::milliseconds maxDuration)
68{
69 auto [p1, p2] = GetDurationPair<std::chrono::seconds, std::chrono::nanoseconds>(now, deadline, maxDuration);
70 timespec ret;
71 ret.tv_sec = p1.count();
72 ret.tv_nsec = p2.count();
73 return ret;
74}
75
76} // namespace NNet
Definition base.hpp:33
Definition base.hpp:27
Definition base.hpp:18