104 lines
2.4 KiB
C++
104 lines
2.4 KiB
C++
#include "quota_tree.h"
|
|
#include <algorithm>
|
|
#include <map>
|
|
#include <utility>
|
|
|
|
namespace quotatree {
|
|
namespace {
|
|
|
|
Query invalid_query()
|
|
{
|
|
Query result;
|
|
result.error = Error::invalid;
|
|
return result;
|
|
}
|
|
|
|
std::map<std::string, const Node *> index_nodes(const Tree &tree)
|
|
{
|
|
std::map<std::string, const Node *> index;
|
|
for (const Node &node : tree.nodes) {
|
|
index.emplace(node.id, &node);
|
|
}
|
|
return index;
|
|
}
|
|
|
|
Fraction ratio(const Node &node)
|
|
{
|
|
Fraction result;
|
|
result.numerator = node.limit.quota;
|
|
result.denominator = node.limit.period;
|
|
return result;
|
|
}
|
|
|
|
std::vector<const Node *> ancestor_chain(
|
|
const std::map<std::string, const Node *> &index,
|
|
const std::string &target)
|
|
{
|
|
std::vector<const Node *> chain;
|
|
const Node *current = index.at(target);
|
|
for (;;) {
|
|
chain.push_back(current);
|
|
if (!current->parent.has_value()) {
|
|
break;
|
|
}
|
|
current = index.at(*current->parent);
|
|
}
|
|
return chain;
|
|
}
|
|
|
|
bool smallest_limit(const std::vector<const Node *> &chain,
|
|
Fraction &minimum)
|
|
{
|
|
bool found = false;
|
|
for (const Node *node : chain) {
|
|
if (node->limit.unlimited) {
|
|
continue;
|
|
}
|
|
const Fraction candidate = ratio(*node);
|
|
if (!found || compare_fraction(candidate, minimum) < 0) {
|
|
minimum = candidate;
|
|
found = true;
|
|
}
|
|
}
|
|
return found;
|
|
}
|
|
|
|
}
|
|
|
|
Query evaluate(const Tree &tree, const std::string &target)
|
|
{
|
|
const auto index = index_nodes(tree);
|
|
if (index.count(target) == 0) {
|
|
return invalid_query();
|
|
}
|
|
const auto chain = ancestor_chain(index, target);
|
|
Query result;
|
|
for (const Node *node : chain) {
|
|
result.path.push_back(node->id);
|
|
}
|
|
Fraction minimum;
|
|
if (!smallest_limit(chain, minimum)) {
|
|
return result;
|
|
}
|
|
result.finite = true;
|
|
result.cores = reduced(minimum);
|
|
for (const Node *node : chain) {
|
|
if (!node->limit.unlimited && compare_fraction(ratio(*node), minimum) == 0) {
|
|
result.limiting.push_back(node->id);
|
|
}
|
|
}
|
|
std::sort(result.limiting.begin(), result.limiting.end());
|
|
return result;
|
|
}
|
|
|
|
Query analyze(const std::vector<NodeInput> &input, const std::string &target)
|
|
{
|
|
Tree tree;
|
|
if (compile_tree(input, tree) != Error::none) {
|
|
return invalid_query();
|
|
}
|
|
return evaluate(tree, target);
|
|
}
|
|
|
|
}
|