120 lines
2.7 KiB
C++
120 lines
2.7 KiB
C++
#include "quota_tree.h"
|
|
#include <utility>
|
|
|
|
namespace quotatree {
|
|
namespace {
|
|
|
|
bool whitespace(unsigned char value)
|
|
{
|
|
switch (value) {
|
|
case ' ':
|
|
case '\t':
|
|
case '\n':
|
|
case '\r':
|
|
case '\v':
|
|
case '\f':
|
|
return true;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
bool decimal(const std::string &token, std::uint64_t &output)
|
|
{
|
|
if (token.empty()) {
|
|
return false;
|
|
}
|
|
std::uint64_t accumulated = 0;
|
|
for (unsigned char value : token) {
|
|
if (value < '0' || value > '9') {
|
|
return false;
|
|
}
|
|
const std::uint64_t digit = value - '0';
|
|
if (accumulated > (maximum_value - digit) / 10) {
|
|
return false;
|
|
}
|
|
accumulated = accumulated * 10 + digit;
|
|
}
|
|
if (accumulated == 0) {
|
|
return false;
|
|
}
|
|
output = accumulated;
|
|
return true;
|
|
}
|
|
|
|
bool tokens(const std::string &text, std::vector<std::string> &output)
|
|
{
|
|
if (text.size() > 4096) {
|
|
return false;
|
|
}
|
|
for (unsigned char value : text) {
|
|
if (value > 127) {
|
|
return false;
|
|
}
|
|
}
|
|
std::size_t cursor = 0;
|
|
while (cursor < text.size()) {
|
|
while (cursor < text.size() && whitespace(text[cursor])) {
|
|
++cursor;
|
|
}
|
|
if (cursor == text.size()) {
|
|
break;
|
|
}
|
|
const std::size_t start = cursor;
|
|
while (cursor < text.size() && !whitespace(text[cursor])) {
|
|
++cursor;
|
|
}
|
|
output.push_back(text.substr(start, cursor - start));
|
|
if (output.size() > 2) {
|
|
return false;
|
|
}
|
|
}
|
|
return output.size() == 2;
|
|
}
|
|
|
|
}
|
|
|
|
Error parse_cpu_max(const std::string &text, Limit &output)
|
|
{
|
|
output = Limit{};
|
|
std::vector<std::string> fields;
|
|
if (!tokens(text, fields)) {
|
|
return Error::invalid;
|
|
}
|
|
Limit result;
|
|
if (!decimal(fields[1], result.period)) {
|
|
return Error::invalid;
|
|
}
|
|
if (fields[0] == "max") {
|
|
result.unlimited = true;
|
|
} else if (!decimal(fields[0], result.quota)) {
|
|
return Error::invalid;
|
|
}
|
|
output = result;
|
|
return Error::none;
|
|
}
|
|
|
|
Fraction reduced(Fraction input)
|
|
{
|
|
std::uint64_t left = input.numerator;
|
|
std::uint64_t right = input.denominator;
|
|
while (right != 0) {
|
|
const std::uint64_t remainder = left % right;
|
|
left = right;
|
|
right = remainder;
|
|
}
|
|
Fraction result;
|
|
result.numerator = input.numerator / left;
|
|
result.denominator = input.denominator / left;
|
|
return result;
|
|
}
|
|
|
|
int compare_fraction(Fraction left, Fraction right)
|
|
{
|
|
const std::uint64_t lproduct = left.numerator * right.denominator;
|
|
const std::uint64_t rproduct = right.numerator * left.denominator;
|
|
return (lproduct > rproduct) - (lproduct < rproduct);
|
|
}
|
|
|
|
}
|