-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontrol_unit.cpp
80 lines (73 loc) · 2.43 KB
/
control_unit.cpp
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
#include <stdexcept>
#include "control_unit.h"
ControlUnit::ControlUnit(size_t static_bulk_size)
:m_static_bulk_size(static_bulk_size)
{
m_state = State::Empty;
CreateTransition(State::Empty, Event::CommandAdded, [this]()
{
m_commands_count++;
m_state = m_commands_count < m_static_bulk_size ? State::GatheringStatic : State::BulkReady;
});
CreateTransition(State::GatheringStatic, Event::CommandAdded, [this]()
{
m_commands_count++;
if (m_commands_count == m_static_bulk_size)
{
m_state = State::BulkReady;
}
});
CreateTransition(State::GatheringStatic, Event::EndOfFile, [this](){ m_state = State::BulkReady; });
CreateTransition(State::BulkReady, Event::BulkProcessed, [this]()
{
m_commands_count = 0;
m_state = State::Empty;
});
CreateTransition(State::Empty, Event::BlockOpened, [this](){ m_state = State::GatheringDynamic; });
CreateTransition(State::GatheringStatic, Event::BlockOpened, [this](){ m_state = State::ProcessUnfinished; });
CreateTransition(State::ProcessUnfinished, Event::BulkProcessed, [this]()
{
m_commands_count = 0;
m_state = State::GatheringDynamic;
});
CreateTransition(State::GatheringDynamic, Event::CommandAdded, [](){});
CreateTransition(State::GatheringDynamic, Event::BlockOpened, [this]()
{
m_blocks_nesting++;
});
CreateTransition(State::GatheringDynamic, Event::BlockClosed, [this]()
{
if (m_blocks_nesting == 0)
{
m_state = State::BulkReady;
}
else
{
m_blocks_nesting--;
}
});
CreateTransition(State::GatheringDynamic, Event::EndOfFile, [this](){ m_state = State::Discard; });
}
void ControlUnit::CreateTransition(State from, Event onEvent, std::function<void(void)> transition)
{
auto key = std::make_pair(from, onEvent);
m_state_machine[key] = transition;
}
bool ControlUnit::ShouldProcessBulk() const
{
return (m_state == State::BulkReady) || (m_state == State::ProcessUnfinished);
}
void ControlUnit::HandleEvent(Event evnt)
{
auto transition_key = std::make_pair(m_state, evnt);
auto transition = m_state_machine.find(transition_key);
if (transition != m_state_machine.end())
{
auto action = transition->second;
action();
}
else
{
throw std::logic_error("Invalid event for current state!");
}
}