-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlogic.cpp
More file actions
107 lines (78 loc) · 1.48 KB
/
logic.cpp
File metadata and controls
107 lines (78 loc) · 1.48 KB
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
107
#include <stdexcept>
#include "logic.h"
namespace Logic {
ElemInput::operator bool () const
{
if (elem)
return inv ? !*elem : *elem;
else
return inv;
}
void Element::set (bool value)
{
if (inverted_out)
value = !value;
if (out != value)
{
out = value;
if (cb)
cb(*this);
for (auto elem : outputs)
elem->calc();
}
}
Element& operator>> (Element& lhs, Operation& rhs)
{
check_loop(rhs, lhs);
rhs.inputs.push_back(ElemInput{lhs, false});
lhs.outputs.push_back(&rhs);
rhs.calc();
return rhs;
}
Element& operator>> (Element& lhs, Connection rhs)
{
check_loop(rhs.oper_elem, lhs);
rhs.oper_elem.inputs.push_back(ElemInput{lhs, rhs.inverted});
lhs.outputs.push_back(&rhs.oper_elem);
rhs.oper_elem.calc();
return rhs.oper_elem;
}
void check_loop (const Element& loop, const Element& elem)
{
// checking if elem is the loop
if (&loop == &elem)
throw std::runtime_error{"loop detected in connections of logic elements"};
for (const auto& output : loop.get_outputs())
check_loop(*output, elem);
}
void Source::calc ()
{
// nothing to do here
}
void And::calc ()
{
bool res{ get_inputs().size() != 0 };
for (const auto& input : get_inputs())
{
if (!input)
{
res = false;
break;
}
}
set(res);
}
void Or::calc ()
{
bool res{ false };
for (const auto& input : get_inputs())
{
if (input)
{
res = true;
break;
}
}
set(res);
}
} // namespace Logic