summaryrefslogtreecommitdiff
path: root/starts/meaning-vm/level-0/memorystore.cpp
blob: 0a4f0cc818f25c6cfad20258128b6eb9380d877d (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
#include "memorystore.hpp"
#include "concept.hpp"
#include "errors.hpp"

#include <unordered_set>

namespace intellect {
namespace level0 {

static auto & concepts()
{
	static std::unordered_set<ref, std::hash<concept*>> concepts;
	return concepts;
}

ref alloc(concept * moved) {
	ref r = moved ? moved : new concept();
	concepts().insert(r);
	return r;
}

static concept* referenced(ref r) {
	for (ref r2 : concepts()) {
		if (r2 == r) {
			continue;
		}
		for (auto & l : r2->links) {
			if (ref(l.first) == r) {
				return r2.ptr;
			}
			if (ref(l.second) == r) {
				return r2.ptr;
			}
		}
	}
	return 0;
}

void dealloc(ref r) {
	concept * referenced = intellect::level0::referenced(r);
	if (referenced) {
		throw still_referenced_by(r, referenced);
	}
	for (
		auto it = concepts().begin();
		it != concepts().end();
		++ it)
	{
		if (ref(*it) == r) {
			concepts().erase(it);
			delete r.ptr;
			return;
		}
	}
	throw no_such_concept(r);
}

std::size_t allocated()
{
	return concepts().size();
}

}
}