-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEventLoop.h
106 lines (94 loc) · 2.49 KB
/
EventLoop.h
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 "EventListener.h"
#include "Event.h"
#include <istream>
#include <cassert>
namespace tplx
{
namespace details
{
constexpr char calc_median_marker = 'm';
constexpr char seq_end_marker = 'q';
constexpr char separator_marker = ' ';
inline void consumeNextAsMarker(std::istream& source)
{
char ch;
source.get(ch);
assert(not source.eof() and not source.fail());
}
template<typename T>
T consumeNextAsNewValue(std::istream& source)
{
T newValue{};
source >> newValue;
if(source.fail())
{
throw std::invalid_argument("Not-a-number");
}
return newValue;
}
} // namespace details
template<typename T>
void runEventLoop(std::istream& source, EventListener<T>& listener)
{
using namespace details;
char next;
bool separatorExpected = false;
T newValue{};
EventType type;
while(not source.eof())
{
next = source.peek();
if(source.good())
{
if(next == '\n' or next == '\r')
{
break;
}
else if(separatorExpected and next != separator_marker)
{
throw std::invalid_argument("missing separator");
}
else if(next == calc_median_marker)
{
consumeNextAsMarker(source);
separatorExpected = true;
type = EventType::calculate_median;
}
else if(next == seq_end_marker)
{
consumeNextAsMarker(source);
separatorExpected = true;
type = EventType::sequence_end;
}
else if(next >= '1' and next <= '9')
{
newValue = consumeNextAsNewValue<T>(source);
separatorExpected = true;
type = EventType::new_value;
}
else if(next == separator_marker)
{
if(not separatorExpected)
{
throw std::invalid_argument("unexpected separator");
}
consumeNextAsMarker(source);
separatorExpected = false;
}
else
{
throw std::invalid_argument("unexpected character");
}
if(separatorExpected)
{
if(not listener.newEvent(Event<T>{type, newValue}))
{
break;
}
newValue = {};
}
}
}
}
} // namespace tplx