109 lines
2.7 KiB
C++

#include "quota_tree.h"
#include <map>
#include <set>
#include <utility>
namespace quotatree {
namespace {
bool identifier(const std::string &value)
{
return !value.empty() && value.size() <= 128;
}
bool collect_nodes(const std::vector<NodeInput> &input,
std::map<std::string, Node> &nodes)
{
if (input.size() > 256) {
return false;
}
for (const NodeInput &raw : input) {
if (!identifier(raw.id)) {
return false;
}
if (raw.parent.has_value() && !identifier(*raw.parent)) {
return false;
}
Node node;
node.id = raw.id;
node.parent = raw.parent;
if (parse_cpu_max(raw.cpu_max, node.limit) != Error::none) {
return false;
}
if (!nodes.emplace(node.id, std::move(node)).second) {
return false;
}
}
return true;
}
bool parent_links(const std::map<std::string, Node> &nodes)
{
for (const auto &entry : nodes) {
const auto &parent = entry.second.parent;
if (parent.has_value() && nodes.count(*parent) == 0) {
return false;
}
}
return true;
}
bool acyclic(const std::map<std::string, Node> &nodes)
{
enum class Color {
unvisited,
visiting,
complete
};
std::map<std::string, Color> colors;
for (const auto &node : nodes) {
colors.emplace(node.first, Color::unvisited);
}
for (const auto &node : nodes) {
if (node.second.parent.has_value()) {
continue;
}
if (colors.at(node.first) == Color::complete) {
continue;
}
std::vector<std::string> chain;
std::optional<std::string> current = node.first;
while (current.has_value()) {
Color &color = colors.at(*current);
if (color == Color::visiting) {
return false;
}
if (color == Color::complete) {
break;
}
color = Color::visiting;
chain.push_back(*current);
current = nodes.at(*current).parent;
}
for (const std::string &name : chain) {
colors.at(name) = Color::complete;
}
}
return true;
}
}
Error compile_tree(const std::vector<NodeInput> &input, Tree &output)
{
output = Tree{};
std::map<std::string, Node> nodes;
if (!collect_nodes(input, nodes) || !parent_links(nodes) || !acyclic(nodes)) {
return Error::invalid;
}
Tree assembled;
assembled.nodes.reserve(nodes.size());
for (const auto &entry : nodes) {
assembled.nodes.push_back(entry.second);
}
output = std::move(assembled);
return Error::none;
}
}