summaryrefslogtreecommitdiff
path: root/src/frp.cpp
blob: a16950c46037d8b3e4504b84ac6bd40e4e5f4757 (plain)
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include <erebos/frp.h>

#include <condition_variable>
#include <mutex>

using namespace erebos;

using std::condition_variable;
using std::move;
using std::mutex;
using std::nullopt;
using std::unique_lock;

mutex bhvTimeMutex;
condition_variable bhvTimeCond;
bool bhvTimeRunning = false;
uint64_t bhvTimeLast = 0;

BhvTime::BhvTime(const BhvCurTime & ct):
	BhvTime(ct.time())
{}

BhvCurTime::BhvCurTime()
{
	unique_lock lock(bhvTimeMutex);
	bhvTimeCond.wait(lock, []{ return !bhvTimeRunning; });

	bhvTimeRunning = true;
	t = BhvTime(++bhvTimeLast);
}

BhvCurTime::~BhvCurTime()
{
	if (t) {
		unique_lock lock(bhvTimeMutex);
		bhvTimeRunning = false;
		lock.unlock();
		bhvTimeCond.notify_one();
	}
}

BhvCurTime::BhvCurTime(BhvCurTime && other)
{
	t = other.t;
	other.t = nullopt;
}

BhvCurTime & BhvCurTime::operator=(BhvCurTime && other)
{
	t = other.t;
	other.t = nullopt;
	return *this;
}


BhvImplBase::~BhvImplBase() = default;

void BhvImplBase::dependsOn(shared_ptr<BhvImplBase> other)
{
	depends.push_back(other);
	other->rdepends.push_back(shared_from_this());
}

void BhvImplBase::updated(const BhvCurTime & ctime)
{
	vector<shared_ptr<BhvImplBase>> toUpdate;
	markDirty(ctime, toUpdate);

	for (auto & bhv : toUpdate)
		bhv->updateDirty(ctime);
}

void BhvImplBase::markDirty(const BhvCurTime & ctime, vector<shared_ptr<BhvImplBase>> & toUpdate)
{
	if (dirty)
		return;

	if (!needsUpdate(ctime))
		return;

	dirty = true;
	toUpdate.push_back(shared_from_this());

	bool prune = false;
	for (const auto & w : rdepends) {
		if (auto b = w.lock())
			b->markDirty(ctime, toUpdate);
		else
			prune = true;
	}

	if (prune) {
		decltype(rdepends) pruned;
		for (const auto & w : rdepends)
			if (!w.expired())
				pruned.push_back(move(w));
		rdepends = move(pruned);
	}
}

void BhvImplBase::updateDirty(const BhvCurTime & ctime)
{
	if (!dirty)
		return;

	for (auto & d : depends)
		d->updateDirty(ctime);

	doUpdate(ctime);
	dirty = false;

	bool prune = false;
	for (const auto & wcb : watchers) {
		if (auto cb = wcb.lock())
			(*cb)(ctime);
		else
			prune = true;
	}

	if (prune) {
		decltype(watchers) pruned;
		for (const auto & w : watchers)
			if (!w.expired())
				pruned.push_back(move(w));
		watchers = move(pruned);
	}
}

bool BhvImplBase::needsUpdate(const BhvCurTime &) const
{
	return true;
}

void BhvImplBase::doUpdate(const BhvCurTime &)
{
}