From 59e20b10438a4cb95c193bff34437dd7338fb017 Mon Sep 17 00:00:00 2001 From: Martchus Date: Mon, 1 May 2017 03:13:11 +0200 Subject: [PATCH] Apply clang-format --- application/argumentparser.cpp | 499 +++++++++++++------------- application/argumentparser.h | 98 +++-- application/argumentparserprivate.h | 4 +- application/commandlineutils.cpp | 24 +- application/commandlineutils.h | 42 +-- application/failure.cpp | 20 +- application/failure.h | 4 +- application/fakeqtconfigarguments.cpp | 12 +- application/fakeqtconfigarguments.h | 5 +- application/global.h | 100 +++--- chrono/datetime.cpp | 156 ++++---- chrono/datetime.h | 103 +++--- chrono/format.h | 4 +- chrono/period.cpp | 3 - chrono/period.h | 5 +- chrono/timespan.cpp | 32 +- chrono/timespan.h | 52 +-- conversion/binaryconversion.h | 128 +++---- conversion/binaryconversionprivate.h | 146 +++----- conversion/conversionexception.cpp | 16 +- conversion/conversionexception.h | 4 +- conversion/stringbuilder.h | 101 +++--- conversion/stringconversion.cpp | 116 +++--- conversion/stringconversion.h | 160 ++++----- conversion/types.h | 4 +- conversion/widen.h | 30 +- io/ansiescapecodes.h | 47 +-- io/binaryreader.cpp | 124 +++---- io/binaryreader.h | 27 +- io/binarywriter.cpp | 32 +- io/binarywriter.h | 17 +- io/bitreader.cpp | 5 +- io/bitreader.h | 51 ++- io/catchiofailure.cpp | 4 +- io/catchiofailure.h | 1 - io/copy.h | 35 +- io/inifile.cpp | 40 +-- io/inifile.h | 8 +- io/misc.cpp | 3 +- io/misc.h | 1 - io/nativefilestream.cpp | 32 +- io/nativefilestream.h | 15 +- io/path.cpp | 95 +++-- io/path.h | 31 +- math/math.cpp | 17 +- math/math.h | 3 +- misc/memory.h | 46 ++- misc/random.cpp | 65 ++-- misc/random.h | 8 +- misc/traits.h | 50 ++- tests/cppunit.h | 10 +- tests/testutils.cpp | 117 +++--- tests/testutils.h | 22 +- 53 files changed, 1309 insertions(+), 1465 deletions(-) diff --git a/application/argumentparser.cpp b/application/argumentparser.cpp index 3310ee3..40aa722 100644 --- a/application/argumentparser.cpp +++ b/application/argumentparser.cpp @@ -3,17 +3,17 @@ #include "./commandlineutils.h" #include "./failure.h" -#include "../conversion/stringconversion.h" #include "../conversion/stringbuilder.h" -#include "../io/path.h" +#include "../conversion/stringconversion.h" #include "../io/ansiescapecodes.h" +#include "../io/path.h" #include -#include -#include -#include -#include #include +#include +#include +#include +#include using namespace std; using namespace std::placeholders; @@ -41,16 +41,17 @@ enum ArgumentDenotationType : unsigned char { * - For meaning of parameter see documentation of corresponding member variables. * - Results are stored in specified \a args and assigned sub arguments. */ -ArgumentReader::ArgumentReader(ArgumentParser &parser, const char * const *argv, const char * const *end, bool completionMode) : - parser(parser), - args(parser.m_mainArgs), - index(0), - argv(argv), - end(end), - lastArg(nullptr), - argDenotation(nullptr), - completionMode(completionMode) -{} +ArgumentReader::ArgumentReader(ArgumentParser &parser, const char *const *argv, const char *const *end, bool completionMode) + : parser(parser) + , args(parser.m_mainArgs) + , index(0) + , argv(argv) + , end(end) + , lastArg(nullptr) + , argDenotation(nullptr) + , completionMode(completionMode) +{ +} /*! * \brief Resets the ArgumentReader to continue reading new \a argv. @@ -89,70 +90,71 @@ void ArgumentReader::read(ArgumentVector &args) vector *values = nullptr; // iterate through all argument denotations; loop might exit earlier when an denotation is unknown - while(argv != end) { - if(values && lastArgInLevel->requiredValueCount() != static_cast(-1) && values->size() < lastArgInLevel->requiredValueCount()) { + while (argv != end) { + if (values && lastArgInLevel->requiredValueCount() != static_cast(-1) && values->size() < lastArgInLevel->requiredValueCount()) { // there are still values to read values->emplace_back(argDenotation ? argDenotation : *argv); ++index, ++argv, argDenotation = nullptr; } else { // determine how denotation must be processed bool abbreviationFound = false; - if(argDenotation) { + if (argDenotation) { // continue reading childs for abbreviation denotation already detected abbreviationFound = false; argDenotationType = Abbreviation; } else { // determine denotation type argDenotation = *argv; - if(!*argDenotation && (!lastArgInLevel || values->size() >= lastArgInLevel->requiredValueCount())) { + if (!*argDenotation && (!lastArgInLevel || values->size() >= lastArgInLevel->requiredValueCount())) { // skip empty arguments ++index, ++argv, argDenotation = nullptr; continue; } abbreviationFound = false; argDenotationType = Value; - *argDenotation == '-' && (++argDenotation, ++argDenotationType) - && *argDenotation == '-' && (++argDenotation, ++argDenotationType); + *argDenotation == '-' && (++argDenotation, ++argDenotationType) && *argDenotation == '-' && (++argDenotation, ++argDenotationType); } // try to find matching Argument instance Argument *matchingArg = nullptr; size_t argDenotationLength; - if(argDenotationType != Value) { + if (argDenotationType != Value) { const char *const equationPos = strchr(argDenotation, '='); - for(argDenotationLength = equationPos ? static_cast(equationPos - argDenotation) : strlen(argDenotation); argDenotationLength; matchingArg = nullptr) { + for (argDenotationLength = equationPos ? static_cast(equationPos - argDenotation) : strlen(argDenotation); + argDenotationLength; matchingArg = nullptr) { // search for arguments by abbreviation or name depending on the previously determined denotation type - if(argDenotationType == Abbreviation) { - for(Argument *arg : args) { - if(arg->abbreviation() && arg->abbreviation() == *argDenotation) { + if (argDenotationType == Abbreviation) { + for (Argument *arg : args) { + if (arg->abbreviation() && arg->abbreviation() == *argDenotation) { matchingArg = arg; abbreviationFound = true; break; } } } else { - for(Argument *arg : args) { - if(arg->name() && !strncmp(arg->name(), argDenotation, argDenotationLength) && *(arg->name() + argDenotationLength) == '\0') { + for (Argument *arg : args) { + if (arg->name() && !strncmp(arg->name(), argDenotation, argDenotationLength) + && *(arg->name() + argDenotationLength) == '\0') { matchingArg = arg; break; } } } - if(matchingArg) { + if (matchingArg) { // an argument matched the specified denotation so add an occurrence matchingArg->m_occurrences.emplace_back(index, parentPath, parentArg); // prepare reading parameter values values = &matchingArg->m_occurrences.back().values; - if(equationPos) { + if (equationPos) { values->push_back(equationPos + 1); } // read sub arguments ++index, ++parser.m_actualArgc, lastArg = lastArgInLevel = matchingArg, lastArgDenotation = argv; - if(argDenotationType != Abbreviation || (++argDenotation != equationPos)) { - if(argDenotationType != Abbreviation || !*argDenotation) { + if (argDenotationType != Abbreviation || (++argDenotation != equationPos)) { + if (argDenotationType != Abbreviation || !*argDenotation) { // no further abbreviations follow -> read sub args for next argv ++argv, argDenotation = nullptr; read(lastArg->m_subArgs); @@ -169,34 +171,34 @@ void ArgumentReader::read(ArgumentVector &args) } } - if(!matchingArg) { + if (!matchingArg) { // unknown argument might be a sibling of the parent element - if(argDenotationType != Value) { - for(auto parentArgument = parentPath.crbegin(), pathEnd = parentPath.crend(); ; ++parentArgument) { - for(Argument *sibling : (parentArgument != pathEnd ? (*parentArgument)->subArguments() : parser.m_mainArgs)) { - if(sibling->occurrences() < sibling->maxOccurrences()) { - if((argDenotationType == Abbreviation && (sibling->abbreviation() && sibling->abbreviation() == *argDenotation)) - || (sibling->name() && !strncmp(sibling->name(), argDenotation, argDenotationLength))) { + if (argDenotationType != Value) { + for (auto parentArgument = parentPath.crbegin(), pathEnd = parentPath.crend();; ++parentArgument) { + for (Argument *sibling : (parentArgument != pathEnd ? (*parentArgument)->subArguments() : parser.m_mainArgs)) { + if (sibling->occurrences() < sibling->maxOccurrences()) { + if ((argDenotationType == Abbreviation && (sibling->abbreviation() && sibling->abbreviation() == *argDenotation)) + || (sibling->name() && !strncmp(sibling->name(), argDenotation, argDenotationLength))) { return; } } } - if(parentArgument == pathEnd) { + if (parentArgument == pathEnd) { break; } }; } // unknown argument might just be a parameter value of the last argument - if(lastArgInLevel && values->size() < lastArgInLevel->requiredValueCount()) { + if (lastArgInLevel && values->size() < lastArgInLevel->requiredValueCount()) { values->emplace_back(abbreviationFound ? argDenotation : *argv); ++index, ++argv, argDenotation = nullptr; continue; } // first value might denote "operation" - for(Argument *arg : args) { - if(arg->denotesOperation() && arg->name() && !strcmp(arg->name(), *argv)) { + for (Argument *arg : args) { + if (arg->denotesOperation() && arg->name() && !strcmp(arg->name(), *argv)) { (matchingArg = arg)->m_occurrences.emplace_back(index, parentPath, parentArg); lastArgDenotation = argv; ++index, ++argv; @@ -205,19 +207,20 @@ void ArgumentReader::read(ArgumentVector &args) } // use the first default argument which is not already present if there is still no match - if(!matchingArg && (!completionMode || (argv + 1 != end))) { + if (!matchingArg && (!completionMode || (argv + 1 != end))) { const bool uncombinableMainArgPresent = parentArg ? false : parser.isUncombinableMainArgPresent(); - for(Argument *arg : args) { - if(arg->isImplicit() && !arg->isPresent() && !arg->wouldConflictWithArgument() && (!uncombinableMainArgPresent || !arg->isMainArgument())) { + for (Argument *arg : args) { + if (arg->isImplicit() && !arg->isPresent() && !arg->wouldConflictWithArgument() + && (!uncombinableMainArgPresent || !arg->isMainArgument())) { (matchingArg = arg)->m_occurrences.emplace_back(index, parentPath, parentArg); break; } } } - if(matchingArg) { + if (matchingArg) { // an argument matched the specified denotation - if(lastArgInLevel == matchingArg) { + if (lastArgInLevel == matchingArg) { break; // break required? -> TODO: add test for this condition } @@ -232,15 +235,15 @@ void ArgumentReader::read(ArgumentVector &args) } // argument denotation is unknown -> handle error - if(parentArg) { + if (parentArg) { // continue with parent level return; } - if(completionMode) { + if (completionMode) { // ignore unknown denotation ++index, ++argv, argDenotation = nullptr; } else { - switch(parser.m_unknownArgBehavior) { + switch (parser.m_unknownArgBehavior) { case UnknownArgumentBehavior::Warn: cerr << "The specified argument \"" << *argv << "\" is unknown and will be ignored." << endl; FALLTHROUGH; @@ -272,7 +275,7 @@ std::initializer_list dependencyVersions; * \brief Specifies a function quit the application. * \remarks Currently only used after printing Bash completion. Default is std::exit(). */ -void(*exitFunction)(int) = &exit; +void (*exitFunction)(int) = &exit; /// \cond @@ -299,28 +302,31 @@ inline bool notEmpty(const char *str) * The \a name and the abbreviation mustn't contain any whitespaces. * The \a name mustn't be empty. The \a abbreviation and the \a description might be empty. */ -Argument::Argument(const char *name, char abbreviation, const char *description, const char *example) : - m_name(name), - m_abbreviation(abbreviation), - m_environmentVar(nullptr), - m_description(description), - m_example(example), - m_minOccurrences(0), - m_maxOccurrences(1), - m_combinable(false), - m_denotesOperation(false), - m_requiredValueCount(0), - m_implicit(false), - m_isMainArg(false), - m_valueCompletionBehavior(ValueCompletionBehavior::PreDefinedValues | ValueCompletionBehavior::Files | ValueCompletionBehavior::Directories | ValueCompletionBehavior::FileSystemIfNoPreDefinedValues), - m_preDefinedCompletionValues(nullptr) -{} +Argument::Argument(const char *name, char abbreviation, const char *description, const char *example) + : m_name(name) + , m_abbreviation(abbreviation) + , m_environmentVar(nullptr) + , m_description(description) + , m_example(example) + , m_minOccurrences(0) + , m_maxOccurrences(1) + , m_combinable(false) + , m_denotesOperation(false) + , m_requiredValueCount(0) + , m_implicit(false) + , m_isMainArg(false) + , m_valueCompletionBehavior(ValueCompletionBehavior::PreDefinedValues | ValueCompletionBehavior::Files | ValueCompletionBehavior::Directories + | ValueCompletionBehavior::FileSystemIfNoPreDefinedValues) + , m_preDefinedCompletionValues(nullptr) +{ +} /*! * \brief Destroys the Argument. */ Argument::~Argument() -{} +{ +} /*! * \brief Returns the first parameter value of the first occurrence of the argument. @@ -331,9 +337,9 @@ Argument::~Argument() */ const char *Argument::firstValue() const { - if(!m_occurrences.empty() && !m_occurrences.front().values.empty()) { + if (!m_occurrences.empty() && !m_occurrences.front().values.empty()) { return m_occurrences.front().values.front(); - } else if(m_environmentVar) { + } else if (m_environmentVar) { return getenv(m_environmentVar); } else { return nullptr; @@ -347,48 +353,48 @@ void Argument::printInfo(ostream &os, unsigned char indentation) const { os << Indentation(indentation); EscapeCodes::setStyle(os, EscapeCodes::TextAttribute::Bold); - if(notEmpty(name())) { + if (notEmpty(name())) { os << '-' << '-' << name(); } - if(notEmpty(name()) && abbreviation()) { + if (notEmpty(name()) && abbreviation()) { os << ',' << ' '; } - if(abbreviation()) { + if (abbreviation()) { os << '-' << abbreviation(); } EscapeCodes::setStyle(os); - if(requiredValueCount()) { + if (requiredValueCount()) { unsigned int valueNamesPrint = 0; - for(auto i = valueNames().cbegin(), end = valueNames().cend(); i != end && valueNamesPrint < requiredValueCount(); ++i) { + for (auto i = valueNames().cbegin(), end = valueNames().cend(); i != end && valueNamesPrint < requiredValueCount(); ++i) { os << ' ' << '[' << *i << ']'; ++valueNamesPrint; } - if(requiredValueCount() == static_cast(-1)) { + if (requiredValueCount() == static_cast(-1)) { os << " ..."; } else { - for(; valueNamesPrint < requiredValueCount(); ++valueNamesPrint) { + for (; valueNamesPrint < requiredValueCount(); ++valueNamesPrint) { os << " [value " << (valueNamesPrint + 1) << ']'; } } } indentation += 2; - if(notEmpty(description())) { + if (notEmpty(description())) { os << '\n' << Indentation(indentation) << description(); } - if(isRequired()) { + if (isRequired()) { os << '\n' << Indentation(indentation) << "particularities: mandatory"; - if(!isMainArgument()) { + if (!isMainArgument()) { os << " if parent argument is present"; } } - if(environmentVariable()) { + if (environmentVariable()) { os << '\n' << Indentation(indentation) << "default environment variable: " << environmentVariable(); } - if(notEmpty(example())) { + if (notEmpty(example())) { os << '\n' << Indentation(indentation) << "\nusage: " << example(); } os << '\n'; - for(const auto *arg : subArguments()) { + for (const auto *arg : subArguments()) { arg->printInfo(os, indentation); } } @@ -400,8 +406,8 @@ void Argument::printInfo(ostream &os, unsigned char indentation) const */ Argument *firstPresentUncombinableArg(const ArgumentVector &args, const Argument *except) { - for(Argument *arg : args) { - if(arg != except && arg->isPresent() && !arg->isCombinable()) { + for (Argument *arg : args) { + if (arg != except && arg->isPresent() && !arg->isCombinable()) { return arg; } } @@ -425,15 +431,15 @@ Argument *firstPresentUncombinableArg(const ArgumentVector &args, const Argument void Argument::setSubArguments(const ArgumentInitializerList &secondaryArguments) { // remove this argument from the parents list of the previous secondary arguments - for(Argument *arg : m_subArgs) { + for (Argument *arg : m_subArgs) { arg->m_parents.erase(remove(arg->m_parents.begin(), arg->m_parents.end(), this), arg->m_parents.end()); } // assign secondary arguments m_subArgs.assign(secondaryArguments); // add this argument to the parents list of the assigned secondary arguments // and set the parser - for(Argument *arg : m_subArgs) { - if(find(arg->m_parents.cbegin(), arg->m_parents.cend(), this) == arg->m_parents.cend()) { + for (Argument *arg : m_subArgs) { + if (find(arg->m_parents.cbegin(), arg->m_parents.cend(), this) == arg->m_parents.cend()) { arg->m_parents.push_back(this); } } @@ -448,9 +454,9 @@ void Argument::setSubArguments(const ArgumentInitializerList &secondaryArguments */ void Argument::addSubArgument(Argument *arg) { - if(find(m_subArgs.cbegin(), m_subArgs.cend(), arg) == m_subArgs.cend()) { + if (find(m_subArgs.cbegin(), m_subArgs.cend(), arg) == m_subArgs.cend()) { m_subArgs.push_back(arg); - if(find(arg->m_parents.cbegin(), arg->m_parents.cend(), this) == arg->m_parents.cend()) { + if (find(arg->m_parents.cbegin(), arg->m_parents.cend(), this) == arg->m_parents.cend()) { arg->m_parents.push_back(this); } } @@ -462,11 +468,11 @@ void Argument::addSubArgument(Argument *arg) */ bool Argument::isParentPresent() const { - if(isMainArgument()) { + if (isMainArgument()) { return true; } - for(const Argument *parent : m_parents) { - if(parent->isPresent()) { + for (const Argument *parent : m_parents) { + if (parent->isPresent()) { return true; } } @@ -496,10 +502,10 @@ Argument *Argument::conflictsWithArgument() const */ Argument *Argument::wouldConflictWithArgument() const { - if(!isCombinable()) { - for(Argument *parent : m_parents) { - for(Argument *sibling : parent->subArguments()) { - if(sibling != this && sibling->isPresent() && !sibling->isCombinable()) { + if (!isCombinable()) { + for (Argument *parent : m_parents) { + for (Argument *sibling : parent->subArguments()) { + if (sibling != this && sibling->isPresent() && !sibling->isCombinable()) { return sibling; } } @@ -514,7 +520,7 @@ Argument *Argument::wouldConflictWithArgument() const */ void Argument::resetRecursively() { - for(Argument *arg : m_subArgs) { + for (Argument *arg : m_subArgs) { arg->resetRecursively(); } reset(); @@ -536,12 +542,13 @@ void Argument::resetRecursively() /*! * \brief Constructs a new ArgumentParser. */ -ArgumentParser::ArgumentParser() : - m_actualArgc(0), - m_executable(nullptr), - m_unknownArgBehavior(UnknownArgumentBehavior::Fail), - m_defaultArg(nullptr) -{} +ArgumentParser::ArgumentParser() + : m_actualArgc(0) + , m_executable(nullptr) + , m_unknownArgBehavior(UnknownArgumentBehavior::Fail) + , m_defaultArg(nullptr) +{ +} /*! * \brief Sets the main arguments for the parser. The parser will use these argument definitions @@ -554,21 +561,21 @@ ArgumentParser::ArgumentParser() : */ void ArgumentParser::setMainArguments(const ArgumentInitializerList &mainArguments) { - if(mainArguments.size()) { - for(Argument *arg : mainArguments) { + if (mainArguments.size()) { + for (Argument *arg : mainArguments) { arg->m_isMainArg = true; } m_mainArgs.assign(mainArguments); - if(!m_defaultArg) { - if(!(*mainArguments.begin())->requiredValueCount()) { + if (!m_defaultArg) { + if (!(*mainArguments.begin())->requiredValueCount()) { bool subArgsRequired = false; - for(const Argument *subArg : (*mainArguments.begin())->subArguments()) { - if(subArg->isRequired()) { + for (const Argument *subArg : (*mainArguments.begin())->subArguments()) { + if (subArg->isRequired()) { subArgsRequired = true; break; } } - if(!subArgsRequired) { + if (!subArgsRequired) { m_defaultArg = *mainArguments.begin(); } } @@ -596,38 +603,38 @@ void ArgumentParser::addMainArgument(Argument *argument) void ArgumentParser::printHelp(ostream &os) const { EscapeCodes::setStyle(os, EscapeCodes::TextAttribute::Bold); - if(applicationName && *applicationName) { + if (applicationName && *applicationName) { os << applicationName; - if(applicationVersion && *applicationVersion) { + if (applicationVersion && *applicationVersion) { os << ',' << ' '; } } - if(applicationVersion && *applicationVersion) { + if (applicationVersion && *applicationVersion) { os << "version " << applicationVersion; } - if(dependencyVersions.size()) { - if((applicationName && *applicationName) || (applicationVersion && *applicationVersion)) { + if (dependencyVersions.size()) { + if ((applicationName && *applicationName) || (applicationVersion && *applicationVersion)) { os << '\n'; EscapeCodes::setStyle(os); } auto i = dependencyVersions.begin(), end = dependencyVersions.end(); os << "Linked against: " << *i; - for(++i; i != end; ++i) { + for (++i; i != end; ++i) { os << ',' << ' ' << *i; } } - if((applicationName && *applicationName) || (applicationVersion && *applicationVersion) || dependencyVersions.size()) { + if ((applicationName && *applicationName) || (applicationVersion && *applicationVersion) || dependencyVersions.size()) { os << '\n' << '\n'; } EscapeCodes::setStyle(os); - if(!m_mainArgs.empty()) { + if (!m_mainArgs.empty()) { os << "Available arguments:"; - for(const Argument *arg : m_mainArgs) { + for (const Argument *arg : m_mainArgs) { os << '\n'; arg->printInfo(os); } } - if(applicationUrl && *applicationUrl) { + if (applicationUrl && *applicationUrl) { os << "\nProject website: " << applicationUrl << endl; } } @@ -644,7 +651,7 @@ void ArgumentParser::printHelp(ostream &os) const void ArgumentParser::parseArgs(int argc, const char *const *argv) { readArgs(argc, argv); - if(argc) { + if (argc) { checkConstraints(m_mainArgs); invokeCallbacks(m_mainArgs); } @@ -659,48 +666,50 @@ void ArgumentParser::parseArgs(int argc, const char *const *argv) * \throws Throws Failure if the specified arguments are invalid. * \sa readArgs() */ -void ArgumentParser::readArgs(int argc, const char * const *argv) +void ArgumentParser::readArgs(int argc, const char *const *argv) { IF_DEBUG_BUILD(verifyArgs(m_mainArgs, std::vector(), std::vector());) m_actualArgc = 0; - if(argc) { + if (argc) { // the first argument is the executable name m_executable = *argv; // check for further arguments - if(--argc) { + if (--argc) { // if the first argument (after executable name) is "--bash-completion-for" bash completion for the following arguments is requested bool completionMode = !strcmp(*++argv, "--bash-completion-for"); unsigned int currentWordIndex; - if(completionMode) { + if (completionMode) { // the first argument after "--bash-completion-for" is the index of the current word try { currentWordIndex = (--argc ? stringToNumber(*(++argv)) : 0); - } catch(const ConversionException &) { + } catch (const ConversionException &) { currentWordIndex = static_cast(argc); } - if(argc) { + if (argc) { ++argv, --argc; } } // read specified arguments - ArgumentReader reader(*this, argv, argv + (completionMode ? min(static_cast(argc), currentWordIndex + 1) : static_cast(argc)), completionMode); + ArgumentReader reader(*this, argv, + argv + (completionMode ? min(static_cast(argc), currentWordIndex + 1) : static_cast(argc)), + completionMode); try { reader.read(); - } catch(const Failure &) { - if(!completionMode) { + } catch (const Failure &) { + if (!completionMode) { throw; } } - if(completionMode) { + if (completionMode) { printBashCompletion(argc, argv, currentWordIndex, reader); exitFunction(0); // prevent the applicaton to continue with the regular execution } } else { // no arguments specified -> flag default argument as present if one is assigned - if(m_defaultArg) { + if (m_defaultArg) { m_defaultArg->m_occurrences.emplace_back(0); } } @@ -715,7 +724,7 @@ void ArgumentParser::readArgs(int argc, const char * const *argv) */ void ArgumentParser::resetArgs() { - for(Argument *arg : m_mainArgs) { + for (Argument *arg : m_mainArgs) { arg->resetRecursively(); } m_actualArgc = 0; @@ -726,8 +735,8 @@ void ArgumentParser::resetArgs() */ bool ArgumentParser::isUncombinableMainArgPresent() const { - for(const Argument *arg : m_mainArgs) { - if(!arg->isCombinable() && arg->isPresent()) { + for (const Argument *arg : m_mainArgs) { + if (!arg->isCombinable() && arg->isPresent()) { return true; } } @@ -760,18 +769,18 @@ void ApplicationUtilities::ArgumentParser::verifyArgs(const ArgumentVector &args vector names; names.reserve(names.size() + args.size()); bool hasImplicit = false; - for(const Argument *arg : args) { + for (const Argument *arg : args) { assert(find(verifiedArgs.cbegin(), verifiedArgs.cend(), arg) == verifiedArgs.cend()); verifiedArgs.push_back(arg); assert(!arg->isImplicit() || !hasImplicit); hasImplicit |= arg->isImplicit(); assert(!arg->abbreviation() || find(abbreviations.cbegin(), abbreviations.cend(), arg->abbreviation()) == abbreviations.cend()); abbreviations.push_back(arg->abbreviation()); - assert(!arg->name() || find_if(names.cbegin(), names.cend(), [arg] (const char *name) { return !strcmp(arg->name(), name); }) == names.cend()); + assert(!arg->name() || find_if(names.cbegin(), names.cend(), [arg](const char *name) { return !strcmp(arg->name(), name); }) == names.cend()); assert(arg->requiredValueCount() == 0 || arg->subArguments().size() == 0); names.emplace_back(arg->name()); } - for(const Argument *arg : args) { + for (const Argument *arg : args) { verifyArgs(arg->subArguments(), vector(), vector()); } } @@ -786,9 +795,9 @@ void ApplicationUtilities::ArgumentParser::verifyArgs(const ArgumentVector &args */ bool compareArgs(const Argument *arg1, const Argument *arg2) { - if(arg1->denotesOperation() && !arg2->denotesOperation()) { + if (arg1->denotesOperation() && !arg2->denotesOperation()) { return true; - } else if(!arg1->denotesOperation() && arg2->denotesOperation()) { + } else if (!arg1->denotesOperation() && arg2->denotesOperation()) { return false; } else { return strcmp(arg1->name(), arg2->name()) < 0; @@ -802,14 +811,14 @@ bool compareArgs(const Argument *arg1, const Argument *arg2) void insertSiblings(const ArgumentVector &siblings, list &target) { bool onlyCombinable = false; - for(const Argument *sibling : siblings) { - if(sibling->isPresent() && !sibling->isCombinable()) { + for (const Argument *sibling : siblings) { + if (sibling->isPresent() && !sibling->isCombinable()) { onlyCombinable = true; break; } } - for(const Argument *sibling : siblings) { - if((!onlyCombinable || sibling->isCombinable()) && sibling->occurrences() < sibling->maxOccurrences()) { + for (const Argument *sibling : siblings) { + if ((!onlyCombinable || sibling->isCombinable()) && sibling->occurrences() < sibling->maxOccurrences()) { target.push_back(sibling); } } @@ -830,7 +839,7 @@ void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsi const Argument *const lastDetectedArg = reader.lastArg; size_t lastDetectedArgIndex; vector lastDetectedArgPath; - if(lastDetectedArg) { + if (lastDetectedArg) { lastDetectedArgIndex = reader.lastArgDenotation - argv; lastDetectedArgPath = lastDetectedArg->path(lastDetectedArg->occurrences() - 1); } @@ -838,43 +847,46 @@ void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsi // determine last arg, omitting trailing empty args const char *const *lastSpecifiedArg; unsigned int lastSpecifiedArgIndex; - if(argc) { + if (argc) { lastSpecifiedArgIndex = static_cast(argc) - 1; lastSpecifiedArg = argv + lastSpecifiedArgIndex; - for(; lastSpecifiedArg >= argv && **lastSpecifiedArg == '\0'; --lastSpecifiedArg, --lastSpecifiedArgIndex); + for (; lastSpecifiedArg >= argv && **lastSpecifiedArg == '\0'; --lastSpecifiedArg, --lastSpecifiedArgIndex) + ; } // determine arguments relevant for completion bool nextArgumentOrValue; - if(lastDetectedArg && lastDetectedArg->isPresent()) { - if((nextArgumentOrValue = (currentWordIndex > lastDetectedArgIndex))) { + if (lastDetectedArg && lastDetectedArg->isPresent()) { + if ((nextArgumentOrValue = (currentWordIndex > lastDetectedArgIndex))) { // parameter values of the last arg are possible completions auto currentValueCount = lastDetectedArg->values(lastDetectedArg->occurrences() - 1).size(); - if(currentValueCount) { + if (currentValueCount) { currentValueCount -= (currentWordIndex - lastDetectedArgIndex); } - if(lastDetectedArg->requiredValueCount() == static_cast(-1) || (currentValueCount < lastDetectedArg->requiredValueCount())) { - if(lastDetectedArg->valueCompletionBehaviour() & ValueCompletionBehavior::PreDefinedValues) { + if (lastDetectedArg->requiredValueCount() == static_cast(-1) || (currentValueCount < lastDetectedArg->requiredValueCount())) { + if (lastDetectedArg->valueCompletionBehaviour() & ValueCompletionBehavior::PreDefinedValues) { relevantPreDefinedValues.push_back(lastDetectedArg); } - if(!(lastDetectedArg->valueCompletionBehaviour() & ValueCompletionBehavior::FileSystemIfNoPreDefinedValues) || !lastDetectedArg->preDefinedCompletionValues()) { + if (!(lastDetectedArg->valueCompletionBehaviour() & ValueCompletionBehavior::FileSystemIfNoPreDefinedValues) + || !lastDetectedArg->preDefinedCompletionValues()) { completeFiles = completeFiles || lastDetectedArg->valueCompletionBehaviour() & ValueCompletionBehavior::Files; completeDirs = completeDirs || lastDetectedArg->valueCompletionBehaviour() & ValueCompletionBehavior::Directories; } } - if(lastDetectedArg->requiredValueCount() == static_cast(-1) || lastDetectedArg->values(lastDetectedArg->occurrences() - 1).size() >= lastDetectedArg->requiredValueCount()) { + if (lastDetectedArg->requiredValueCount() == static_cast(-1) + || lastDetectedArg->values(lastDetectedArg->occurrences() - 1).size() >= lastDetectedArg->requiredValueCount()) { // sub arguments of the last arg are possible completions - for(const Argument *subArg : lastDetectedArg->subArguments()) { - if(subArg->occurrences() < subArg->maxOccurrences()) { + for (const Argument *subArg : lastDetectedArg->subArguments()) { + if (subArg->occurrences() < subArg->maxOccurrences()) { relevantArgs.push_back(subArg); } } // siblings of parents are possible completions as well - for(auto parentArgument = lastDetectedArgPath.crbegin(), end = lastDetectedArgPath.crend(); ; ++parentArgument) { + for (auto parentArgument = lastDetectedArgPath.crbegin(), end = lastDetectedArgPath.crend();; ++parentArgument) { insertSiblings(parentArgument != end ? (*parentArgument)->subArguments() : m_mainArgs, relevantArgs); - if(parentArgument == end) { + if (parentArgument == end) { break; } } @@ -895,8 +907,8 @@ void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsi string compoundOpening; size_t openingLen, compoundOpeningStartLen = 0; unsigned char openingDenotationType = Value; - if(argc && nextArgumentOrValue) { - if(currentWordIndex < static_cast(argc)) { + if (argc && nextArgumentOrValue) { + if (currentWordIndex < static_cast(argc)) { opening = argv[currentWordIndex]; // For some reason completions for eg. "set --values disk=1 tag=a" are splitted so the // equation sign is an own argument ("set --values disk = 1 tag = a"). @@ -904,24 +916,23 @@ void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsi // must be joined again. In this case only the part after the equation sign needs to be // provided for completion so compoundOpeningStartLen is set to number of characters to skip. size_t minCurrentWordIndex = (lastDetectedArg ? lastDetectedArgIndex : 0); - if(currentWordIndex > minCurrentWordIndex && !strcmp(opening, "=")) { + if (currentWordIndex > minCurrentWordIndex && !strcmp(opening, "=")) { compoundOpening.reserve(compoundOpeningStartLen = strlen(argv[--currentWordIndex]) + 1); compoundOpening = argv[currentWordIndex]; compoundOpening += '='; - } else if(currentWordIndex > (minCurrentWordIndex + 1) && !strcmp(argv[currentWordIndex - 1], "=")) { + } else if (currentWordIndex > (minCurrentWordIndex + 1) && !strcmp(argv[currentWordIndex - 1], "=")) { compoundOpening.reserve((compoundOpeningStartLen = strlen(argv[currentWordIndex -= 2]) + 1) + strlen(opening)); compoundOpening = argv[currentWordIndex]; compoundOpening += '='; compoundOpening += opening; } - if(!compoundOpening.empty()) { + if (!compoundOpening.empty()) { opening = compoundOpening.data(); } } else { opening = *lastSpecifiedArg; } - *opening == '-' && (++opening, ++openingDenotationType) - && *opening == '-' && (++opening, ++openingDenotationType); + *opening == '-' && (++opening, ++openingDenotationType) && *opening == '-' && (++opening, ++openingDenotationType); openingLen = strlen(opening); } @@ -930,49 +941,52 @@ void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsi // print "COMPREPLY" bash array cout << "COMPREPLY=("; // -> completions for parameter values - for(const Argument *arg : relevantPreDefinedValues) { - if(arg->preDefinedCompletionValues()) { + for (const Argument *arg : relevantPreDefinedValues) { + if (arg->preDefinedCompletionValues()) { bool appendEquationSign = arg->valueCompletionBehaviour() & ValueCompletionBehavior::AppendEquationSign; - if(argc && currentWordIndex <= lastSpecifiedArgIndex && opening) { - if(openingDenotationType == Value) { + if (argc && currentWordIndex <= lastSpecifiedArgIndex && opening) { + if (openingDenotationType == Value) { bool wordStart = true, ok = false, equationSignAlreadyPresent = false; size_t wordIndex = 0; - for(const char *i = arg->preDefinedCompletionValues(), *end = opening + openingLen; *i;) { - if(wordStart) { + for (const char *i = arg->preDefinedCompletionValues(), *end = opening + openingLen; *i;) { + if (wordStart) { const char *i1 = i, *i2 = opening; - for(; *i1 && i2 != end && *i1 == *i2; ++i1, ++i2); - if((ok = (i2 == end))) { + for (; *i1 && i2 != end && *i1 == *i2; ++i1, ++i2) + ; + if ((ok = (i2 == end))) { cout << '\''; } wordStart = false; wordIndex = 0; - } else if((wordStart = (*i == ' ') || (*i == '\n'))) { + } else if ((wordStart = (*i == ' ') || (*i == '\n'))) { equationSignAlreadyPresent = false; - if(ok) { + if (ok) { cout << '\'' << ' '; } ++i; continue; - } else if(*i == '=') { + } else if (*i == '=') { equationSignAlreadyPresent = true; } - if(ok) { - if(!compoundOpeningStartLen || wordIndex >= compoundOpeningStartLen) { - if(*i == '\'') { + if (ok) { + if (!compoundOpeningStartLen || wordIndex >= compoundOpeningStartLen) { + if (*i == '\'') { cout << "'\"'\"'"; } else { cout << *i; } } ++i, ++wordIndex; - switch(*i) { - case ' ': case '\n': case '\0': - if(appendEquationSign && !equationSignAlreadyPresent) { + switch (*i) { + case ' ': + case '\n': + case '\0': + if (appendEquationSign && !equationSignAlreadyPresent) { cout << '='; noWhitespace = true; equationSignAlreadyPresent = false; } - if(*i == '\0') { + if (*i == '\0') { cout << '\''; } } @@ -982,27 +996,29 @@ void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsi } cout << ' '; } - } else if(const char *i = arg->preDefinedCompletionValues()) { + } else if (const char *i = arg->preDefinedCompletionValues()) { bool equationSignAlreadyPresent = false; cout << '\''; - while(*i) { - if(*i == '\'') { + while (*i) { + if (*i == '\'') { cout << "'\"'\"'"; } else { cout << *i; } - switch(*(++i)) { + switch (*(++i)) { case '=': equationSignAlreadyPresent = true; break; - case ' ': case '\n': case '\0': - if(appendEquationSign && !equationSignAlreadyPresent) { + case ' ': + case '\n': + case '\0': + if (appendEquationSign && !equationSignAlreadyPresent) { cout << '='; equationSignAlreadyPresent = false; } - if(*i != '\0') { + if (*i != '\0') { cout << '\''; - if(*(++i)) { + if (*(++i)) { cout << ' ' << '\''; } } @@ -1013,30 +1029,30 @@ void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsi } } // -> completions for further arguments - for(const Argument *arg : relevantArgs) { - if(argc && currentWordIndex <= lastSpecifiedArgIndex && opening) { - switch(openingDenotationType) { + for (const Argument *arg : relevantArgs) { + if (argc && currentWordIndex <= lastSpecifiedArgIndex && opening) { + switch (openingDenotationType) { case Value: - if(!arg->denotesOperation() || strncmp(arg->name(), opening, openingLen)) { + if (!arg->denotesOperation() || strncmp(arg->name(), opening, openingLen)) { continue; } break; case Abbreviation: break; case FullName: - if(strncmp(arg->name(), opening, openingLen)) { + if (strncmp(arg->name(), opening, openingLen)) { continue; } } } - if(opening && openingDenotationType == Abbreviation && !nextArgumentOrValue) { + if (opening && openingDenotationType == Abbreviation && !nextArgumentOrValue) { cout << '\'' << '-' << opening << arg->abbreviation() << '\'' << ' '; - } else if(lastDetectedArg && reader.argDenotationType == Abbreviation && !nextArgumentOrValue) { - if(reader.argv == reader.end) { + } else if (lastDetectedArg && reader.argDenotationType == Abbreviation && !nextArgumentOrValue) { + if (reader.argv == reader.end) { cout << '\'' << *(reader.argv - 1) << '\'' << ' '; } - } else if(arg->denotesOperation()) { + } else if (arg->denotesOperation()) { cout << '\'' << arg->name() << '\'' << ' '; } else { cout << '\'' << '-' << '-' << arg->name() << '\'' << ' '; @@ -1046,7 +1062,7 @@ void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsi // -> if there's already an "opening", determine the dir part and the file part string actualDir, actualFile; bool haveFileOrDirCompletions = false; - if(argc && currentWordIndex == lastSpecifiedArgIndex && opening) { + if (argc && currentWordIndex == lastSpecifiedArgIndex && opening) { // the "opening" might contain escaped characters which need to be unescaped first (let's hope this covers all possible escapings) string unescapedOpening(opening); findAndReplace(unescapedOpening, "\\ ", " "); @@ -1061,23 +1077,23 @@ void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsi findAndReplace(unescapedOpening, "\\\\", "\\"); // determine the "directory" part string dir = directory(unescapedOpening); - if(dir.empty()) { + if (dir.empty()) { actualDir = "."; } else { - if(dir[0] == '\"' || dir[0] == '\'') { + if (dir[0] == '\"' || dir[0] == '\'') { dir.erase(0, 1); } - if(dir.size() > 1 && (dir[dir.size() - 2] == '\"' || dir[dir.size() - 2] == '\'')) { + if (dir.size() > 1 && (dir[dir.size() - 2] == '\"' || dir[dir.size() - 2] == '\'')) { dir.erase(dir.size() - 2, 1); } actualDir = move(dir); } // determine the "file" part string file = fileName(unescapedOpening); - if(file[0] == '\"' || file[0] == '\'') { + if (file[0] == '\"' || file[0] == '\'') { file.erase(0, 1); } - if(file.size() > 1 && (file[dir.size() - 2] == '\"' || dir[file.size() - 2] == '\'')) { + if (file.size() > 1 && (file[dir.size() - 2] == '\"' || dir[file.size() - 2] == '\'')) { file.erase(file.size() - 2, 1); } actualFile = move(file); @@ -1085,21 +1101,21 @@ void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsi // -> completion for files and dirs DirectoryEntryType entryTypes = DirectoryEntryType::None; - if(completeFiles) { + if (completeFiles) { entryTypes |= DirectoryEntryType::File; } - if(completeDirs) { + if (completeDirs) { entryTypes |= DirectoryEntryType::Directory; } - if(entryTypes != DirectoryEntryType::None) { + if (entryTypes != DirectoryEntryType::None) { const string replace("'"), with("'\"'\"'"); - if(argc && currentWordIndex <= lastSpecifiedArgIndex && opening) { + if (argc && currentWordIndex <= lastSpecifiedArgIndex && opening) { list entries = directoryEntries(actualDir.c_str(), entryTypes); findAndReplace(actualDir, replace, with); - for(string &dirEntry : entries) { - if(startsWith(dirEntry, actualFile)) { + for (string &dirEntry : entries) { + if (startsWith(dirEntry, actualFile)) { cout << '\''; - if(actualDir != ".") { + if (actualDir != ".") { cout << actualDir; } findAndReplace(dirEntry, replace, with); @@ -1108,7 +1124,7 @@ void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsi } } } else { - for(string &dirEntry : directoryEntries(".", entryTypes)) { + for (string &dirEntry : directoryEntries(".", entryTypes)) { findAndReplace(dirEntry, replace, with); cout << '\'' << dirEntry << '\'' << ' '; haveFileOrDirCompletions = true; @@ -1118,12 +1134,12 @@ void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsi cout << ')'; // ensure file or dir completions are formatted appropriately - if(haveFileOrDirCompletions) { + if (haveFileOrDirCompletions) { cout << "; compopt -o filenames"; } // ensure trailing whitespace is ommitted - if(noWhitespace) { + if (noWhitespace) { cout << "; compopt -o nospace"; } @@ -1136,39 +1152,41 @@ void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsi */ void ArgumentParser::checkConstraints(const ArgumentVector &args) { - for(const Argument *arg : args) { + for (const Argument *arg : args) { const auto occurrences = arg->occurrences(); - if(arg->isParentPresent() && occurrences > arg->maxOccurrences()) { - throw Failure("The argument \""s % arg->name() % "\" mustn't be specified more than "s % arg->maxOccurrences() + (arg->maxOccurrences() == 1 ? " time."s : " times."s)); + if (arg->isParentPresent() && occurrences > arg->maxOccurrences()) { + throw Failure(argsToString("The argument \"", arg->name(), "\" mustn't be specified more than ", arg->maxOccurrences(), + (arg->maxOccurrences() == 1 ? " time." : " times."))); } - if(arg->isParentPresent() && occurrences < arg->minOccurrences()) { - throw Failure("The argument \""s % arg->name() % "\" must be specified at least "s % arg->minOccurrences() + (arg->minOccurrences() == 1 ? " time."s : " times."s)); + if (arg->isParentPresent() && occurrences < arg->minOccurrences()) { + throw Failure(argsToString("The argument \"", arg->name(), "\" must be specified at least ", arg->minOccurrences(), + (arg->minOccurrences() == 1 ? " time." : " times."))); } Argument *conflictingArgument = nullptr; - if(arg->isMainArgument()) { - if(!arg->isCombinable() && arg->isPresent()) { + if (arg->isMainArgument()) { + if (!arg->isCombinable() && arg->isPresent()) { conflictingArgument = firstPresentUncombinableArg(m_mainArgs, arg); } } else { conflictingArgument = arg->conflictsWithArgument(); } - if(conflictingArgument) { - throw Failure("The argument \""s % conflictingArgument->name() % "\" can not be combined with \""s + arg->name() + "\"."s); + if (conflictingArgument) { + throw Failure(argsToString("The argument \"", conflictingArgument->name(), "\" can not be combined with \"", arg->name(), "\".")); } - for(size_t i = 0; i != occurrences; ++i) { - if(!arg->allRequiredValuesPresent(i)) { + for (size_t i = 0; i != occurrences; ++i) { + if (!arg->allRequiredValuesPresent(i)) { stringstream ss(stringstream::in | stringstream::out); ss << "Not all parameter for argument \"" << arg->name() << "\" "; - if(i) { + if (i) { ss << " (" << (i + 1) << " occurrence) "; } ss << "provided. You have to provide the following parameter:"; size_t valueNamesPrint = 0; - for(const auto &name : arg->m_valueNames) { + for (const auto &name : arg->m_valueNames) { ss << ' ' << name, ++valueNamesPrint; } - if(arg->m_requiredValueCount != static_cast(-1)) { - while(valueNamesPrint < arg->m_requiredValueCount) { + if (arg->m_requiredValueCount != static_cast(-1)) { + while (valueNamesPrint < arg->m_requiredValueCount) { ss << "\nvalue " << (++valueNamesPrint); } } @@ -1190,10 +1208,10 @@ void ArgumentParser::checkConstraints(const ArgumentVector &args) */ void ArgumentParser::invokeCallbacks(const ArgumentVector &args) { - for(const Argument *arg : args) { + for (const Argument *arg : args) { // invoke the callback for each occurrence of the argument - if(arg->m_callbackFunction) { - for(const auto &occurrence : arg->m_occurrences) { + if (arg->m_callbackFunction) { + for (const auto &occurrence : arg->m_occurrences) { arg->m_callbackFunction(occurrence); } } @@ -1211,10 +1229,10 @@ void ArgumentParser::invokeCallbacks(const ArgumentVector &args) /*! * \brief Constructs a new help argument for the specified parser. */ -HelpArgument::HelpArgument(ArgumentParser &parser) : - Argument("help", 'h', "shows this information") +HelpArgument::HelpArgument(ArgumentParser &parser) + : Argument("help", 'h', "shows this information") { - setCallback([&parser] (const ArgumentOccurrence &) { + setCallback([&parser](const ArgumentOccurrence &) { CMD_UTILS_START_CONSOLE; parser.printHelp(cout); }); @@ -1230,5 +1248,4 @@ HelpArgument::HelpArgument(ArgumentParser &parser) : * \brief The ConfigValueArgument class is an Argument where setCombinable() is true by default. * \sa ConfigValueArgument::ConfigValueArgument() */ - } diff --git a/application/argumentparser.h b/application/argumentparser.h index 2a0e4c0..6a2f349 100644 --- a/application/argumentparser.h +++ b/application/argumentparser.h @@ -3,11 +3,11 @@ #include "../global.h" -#include -#include #include +#include +#include #ifdef DEBUG_BUILD -# include +#include #endif class ArgumentParserTests; @@ -27,11 +27,9 @@ CPP_UTILITIES_EXPORT extern std::initializer_list dependencyVersio * \remarks Reads those data from the config header so "config.h" must be included. */ #ifndef APP_STATICALLY_LINKED -#define SET_DEPENDENCY_INFO \ - ::ApplicationUtilities::dependencyVersions = DEPENCENCY_VERSIONS +#define SET_DEPENDENCY_INFO ::ApplicationUtilities::dependencyVersions = DEPENCENCY_VERSIONS #else -#define SET_DEPENDENCY_INFO \ - ::ApplicationUtilities::dependencyVersions = STATIC_DEPENCENCY_VERSIONS +#define SET_DEPENDENCY_INFO ::ApplicationUtilities::dependencyVersions = STATIC_DEPENCENCY_VERSIONS #endif /*! @@ -39,14 +37,14 @@ CPP_UTILITIES_EXPORT extern std::initializer_list dependencyVersio * \brief Sets application meta data (including SET_DEPENDENCY_INFO) used by ArgumentParser::printHelp(). * \remarks Reads those data from the config header so "config.h" must be included. */ -#define SET_APPLICATION_INFO \ - ::ApplicationUtilities::applicationName = APP_NAME; \ - ::ApplicationUtilities::applicationAuthor = APP_AUTHOR; \ - ::ApplicationUtilities::applicationVersion = APP_VERSION; \ - ::ApplicationUtilities::applicationUrl = APP_URL; \ - SET_DEPENDENCY_INFO \ +#define SET_APPLICATION_INFO \ + ::ApplicationUtilities::applicationName = APP_NAME; \ + ::ApplicationUtilities::applicationAuthor = APP_AUTHOR; \ + ::ApplicationUtilities::applicationVersion = APP_VERSION; \ + ::ApplicationUtilities::applicationUrl = APP_URL; \ + SET_DEPENDENCY_INFO -CPP_UTILITIES_EXPORT extern void(*exitFunction)(int); +CPP_UTILITIES_EXPORT extern void (*exitFunction)(int); class Argument; class ArgumentParser; @@ -54,14 +52,13 @@ class ArgumentReader; typedef std::initializer_list ArgumentInitializerList; typedef std::vector ArgumentVector; -typedef std::function ArgumentPredicate; +typedef std::function ArgumentPredicate; /*! * \brief The UnknownArgumentBehavior enum specifies the behavior of the argument parser when an unknown * argument is detected. */ -enum class UnknownArgumentBehavior -{ +enum class UnknownArgumentBehavior { Ignore, /**< Unknown arguments are ignored without warnings. */ Warn, /**< A warning is printed to std::cerr if an unknown argument is detected. */ Fail /**< Further parsing is aborted and an ApplicationUtilities::Failure instance with an error message is thrown. */ @@ -70,8 +67,7 @@ enum class UnknownArgumentBehavior /*! * \brief The ValueCompletionBehavior enum specifies the items to be considered when generating completion for an argument value. */ -enum class ValueCompletionBehavior : unsigned char -{ +enum class ValueCompletionBehavior : unsigned char { None = 0, /**< no auto-completion */ PreDefinedValues = 2, /**< values assigned with Argument::setPreDefinedCompletionValues() */ Files = 4, /**< files */ @@ -97,8 +93,7 @@ Argument CPP_UTILITIES_EXPORT *firstPresentUncombinableArg(const ArgumentVector /*! * \brief The ArgumentOccurrence struct holds argument values for an occurrence of an argument. */ -struct CPP_UTILITIES_EXPORT ArgumentOccurrence -{ +struct CPP_UTILITIES_EXPORT ArgumentOccurrence { ArgumentOccurrence(std::size_t index); ArgumentOccurrence(std::size_t index, const std::vector parentPath, Argument *parent); @@ -122,9 +117,10 @@ struct CPP_UTILITIES_EXPORT ArgumentOccurrence /*! * \brief Constructs an argument occurrence for the specified \a index. */ -inline ArgumentOccurrence::ArgumentOccurrence(std::size_t index) : - index(index) -{} +inline ArgumentOccurrence::ArgumentOccurrence(std::size_t index) + : index(index) +{ +} /*! * \brief Constructs an argument occurrence. @@ -134,22 +130,21 @@ inline ArgumentOccurrence::ArgumentOccurrence(std::size_t index) : * * The path of the new occurrence is built from the specified \a parentPath and \a parent. */ -inline ArgumentOccurrence::ArgumentOccurrence(std::size_t index, const std::vector parentPath, Argument *parent) : - index(index), - path(parentPath) +inline ArgumentOccurrence::ArgumentOccurrence(std::size_t index, const std::vector parentPath, Argument *parent) + : index(index) + , path(parentPath) { - if(parent) { + if (parent) { path.push_back(parent); } } -class CPP_UTILITIES_EXPORT Argument -{ +class CPP_UTILITIES_EXPORT Argument { friend ArgumentParser; friend ArgumentReader; public: - typedef std::function CallbackFunction; + typedef std::function CallbackFunction; Argument(const char *name, char abbreviation = '\0', const char *description = nullptr, const char *example = nullptr); ~Argument(); @@ -227,8 +222,7 @@ private: const char *m_preDefinedCompletionValues; }; -class CPP_UTILITIES_EXPORT ArgumentParser -{ +class CPP_UTILITIES_EXPORT ArgumentParser { friend ArgumentParserTests; friend ArgumentReader; @@ -254,7 +248,7 @@ public: private: IF_DEBUG_BUILD(void verifyArgs(const ArgumentVector &args, std::vector abbreviations, std::vector names);) - void printBashCompletion(int argc, const char * const *argv, unsigned int cursorPos, const ArgumentReader &reader); + void printBashCompletion(int argc, const char *const *argv, unsigned int cursorPos, const ArgumentReader &reader); void checkConstraints(const ArgumentVector &args); void invokeCallbacks(const ArgumentVector &args); @@ -285,9 +279,9 @@ inline const char *Argument::name() const inline void Argument::setName(const char *name) { #ifdef DEBUG_BUILD - if(name && *name) { + if (name && *name) { assert(*name != '-'); - for(const char *c = name; *c; ++c) { + for (const char *c = name; *c; ++c) { assert(*c != ' ' && *c != '=' && *c != '\'' && *c != '\"' && *c != '\n' && *c != '\r'); } } @@ -314,8 +308,8 @@ inline char Argument::abbreviation() const */ inline void Argument::setAbbreviation(char abbreviation) { - IF_DEBUG_BUILD(assert(abbreviation != ' ' && abbreviation != '=' && abbreviation != '-' - && abbreviation != '\'' && abbreviation != '"' && abbreviation != '\n' && abbreviation != '\r')); + IF_DEBUG_BUILD(assert(abbreviation != ' ' && abbreviation != '=' && abbreviation != '-' && abbreviation != '\'' && abbreviation != '"' + && abbreviation != '\n' && abbreviation != '\r')); m_abbreviation = abbreviation; } @@ -470,7 +464,7 @@ inline void Argument::appendValueName(const char *valueName) inline bool Argument::allRequiredValuesPresent(std::size_t occurrence) const { return m_requiredValueCount == static_cast(-1) - || (m_occurrences[occurrence].values.size() >= static_cast(m_requiredValueCount)); + || (m_occurrences[occurrence].values.size() >= static_cast(m_requiredValueCount)); } /*! @@ -577,8 +571,8 @@ inline bool Argument::isRequired() const */ inline void Argument::setRequired(bool required) { - if(required) { - if(!m_minOccurrences) { + if (required) { + if (!m_minOccurrences) { m_minOccurrences = 1; } } else { @@ -816,41 +810,39 @@ inline void ArgumentParser::invokeCallbacks() invokeCallbacks(m_mainArgs); } -class CPP_UTILITIES_EXPORT HelpArgument : public Argument -{ +class CPP_UTILITIES_EXPORT HelpArgument : public Argument { public: HelpArgument(ArgumentParser &parser); }; -class CPP_UTILITIES_EXPORT OperationArgument : public Argument -{ +class CPP_UTILITIES_EXPORT OperationArgument : public Argument { public: OperationArgument(const char *name, char abbreviation = '\0', const char *description = nullptr, const char *example = nullptr); }; -inline OperationArgument::OperationArgument(const char *name, char abbreviation, const char *description, const char *example) : - Argument(name, abbreviation, description, example) +inline OperationArgument::OperationArgument(const char *name, char abbreviation, const char *description, const char *example) + : Argument(name, abbreviation, description, example) { setDenotesOperation(true); } -class CPP_UTILITIES_EXPORT ConfigValueArgument : public Argument -{ +class CPP_UTILITIES_EXPORT ConfigValueArgument : public Argument { public: - ConfigValueArgument(const char *name, char abbreviation = '\0', const char *description = nullptr, std::initializer_list valueNames = std::initializer_list()); + ConfigValueArgument(const char *name, char abbreviation = '\0', const char *description = nullptr, + std::initializer_list valueNames = std::initializer_list()); }; /*! * \brief Constructs a new ConfigValueArgument with the specified parameter. The initial value of requiredValueCount() is set to size of specified \a valueNames. */ -inline ConfigValueArgument::ConfigValueArgument(const char *name, char abbreviation, const char *description, std::initializer_list valueNames) : - Argument(name, abbreviation, description) +inline ConfigValueArgument::ConfigValueArgument( + const char *name, char abbreviation, const char *description, std::initializer_list valueNames) + : Argument(name, abbreviation, description) { setCombinable(true); setRequiredValueCount(valueNames.size()); setValueNames(valueNames); } - } #endif // APPLICATION_UTILITIES_ARGUMENTPARSER_H diff --git a/application/argumentparserprivate.h b/application/argumentparserprivate.h index bfe92c2..b3ee8af 100644 --- a/application/argumentparserprivate.h +++ b/application/argumentparserprivate.h @@ -3,8 +3,7 @@ namespace ApplicationUtilities { -struct CPP_UTILITIES_EXPORT ArgumentReader -{ +struct CPP_UTILITIES_EXPORT ArgumentReader { ArgumentReader(ArgumentParser &parser, const char *const *argv, const char *const *end, bool completionMode = false); ApplicationUtilities::ArgumentReader &reset(const char *const *argv, const char *const *end); void read(); @@ -31,7 +30,6 @@ struct CPP_UTILITIES_EXPORT ArgumentReader /// \brief Whether completion mode is enabled. In this case reading args will be continued even if an denotation is unknown (regardless of unknownArgumentBehavior()). bool completionMode; }; - } #endif // APPLICATION_UTILITIES_ARGUMENTPARSER_PRIVATE_H diff --git a/application/commandlineutils.cpp b/application/commandlineutils.cpp index 028b3eb..5e4351c 100644 --- a/application/commandlineutils.cpp +++ b/application/commandlineutils.cpp @@ -1,11 +1,11 @@ #include "./commandlineutils.h" -#include #include +#include #ifdef PLATFORM_WINDOWS -# include -# include +#include +#include #endif using namespace std; @@ -23,11 +23,11 @@ bool confirmPrompt(const char *message, Response defaultResponse) cout << '/' << (defaultResponse == Response::No ? 'N' : 'n'); cout << ']' << ' '; cout.flush(); - for(string line; ;) { + for (string line;;) { getline(cin, line); - if(line == "y" || line == "Y" || (defaultResponse == Response::Yes && line.empty())) { + if (line == "y" || line == "Y" || (defaultResponse == Response::Yes && line.empty())) { return true; - } else if(line == "n" || line == "N" || (defaultResponse == Response::No && line.empty())) { + } else if (line == "n" || line == "N" || (defaultResponse == Response::No && line.empty())) { return false; } else { cout << "Please enter [y] or [n]: "; @@ -46,7 +46,7 @@ void stopConsole() fclose(stdout); fclose(stdin); fclose(stderr); - if(auto *consoleWindow = GetConsoleWindow()) { + if (auto *consoleWindow = GetConsoleWindow()) { PostMessage(consoleWindow, WM_KEYUP, VK_RETURN, 0); FreeConsole(); } @@ -61,7 +61,7 @@ void stopConsole() */ void startConsole() { - if(!AttachConsole(ATTACH_PARENT_PROCESS) && !AllocConsole()) { + if (!AttachConsole(ATTACH_PARENT_PROCESS) && !AllocConsole()) { return; } // redirect stdout @@ -104,21 +104,21 @@ pair >, vector > convertArgsToUtf8() int argc; LPWSTR *argv_w = CommandLineToArgvW(GetCommandLineW(), &argc); - if(!argv_w || argc <= 0) { + if (!argv_w || argc <= 0) { return res; } res.first.reserve(static_cast(argc)); res.second.reserve(static_cast(argc)); - for(LPWSTR *i = argv_w, *end = argv_w + argc; i != end; ++i) { + for (LPWSTR *i = argv_w, *end = argv_w + argc; i != end; ++i) { int requiredSize = WideCharToMultiByte(CP_UTF8, 0, *i, -1, nullptr, 0, 0, 0); - if(requiredSize <= 0) { + if (requiredSize <= 0) { break; // just stop on error } auto argv = make_unique(static_cast(requiredSize)); requiredSize = WideCharToMultiByte(CP_UTF8, 0, *i, -1, argv.get(), requiredSize, 0, 0); - if(requiredSize <= 0) { + if (requiredSize <= 0) { break; } diff --git a/application/commandlineutils.h b/application/commandlineutils.h index 91d841d..84ba32c 100644 --- a/application/commandlineutils.h +++ b/application/commandlineutils.h @@ -6,8 +6,8 @@ #include #ifdef PLATFORM_WINDOWS -# include -# include +#include +#include #endif namespace ApplicationUtilities { @@ -15,41 +15,35 @@ namespace ApplicationUtilities { /*! * \brief The Response enum is used to specify the default response for the confirmPrompt() method. */ -enum class Response -{ - None, - Yes, - No -}; +enum class Response { None, Yes, No }; bool CPP_UTILITIES_EXPORT confirmPrompt(const char *message, Response defaultResponse = Response::None); #ifdef PLATFORM_WINDOWS void CPP_UTILITIES_EXPORT startConsole(); std::pair >, std::vector > CPP_UTILITIES_EXPORT convertArgsToUtf8(); -# define CMD_UTILS_START_CONSOLE \ - ::ApplicationUtilities::startConsole(); -# define CMD_UTILS_CONVERT_ARGS_TO_UTF8 \ - auto utf8Args = ::ApplicationUtilities::convertArgsToUtf8(); \ - argv = utf8Args.second.data(); \ +#define CMD_UTILS_START_CONSOLE ::ApplicationUtilities::startConsole(); +#define CMD_UTILS_CONVERT_ARGS_TO_UTF8 \ + auto utf8Args = ::ApplicationUtilities::convertArgsToUtf8(); \ + argv = utf8Args.second.data(); \ argc = static_cast(utf8Args.second.size()); #else -# define CMD_UTILS_START_CONSOLE -# define CMD_UTILS_CONVERT_ARGS_TO_UTF8 +#define CMD_UTILS_START_CONSOLE +#define CMD_UTILS_CONVERT_ARGS_TO_UTF8 #endif /*! * \brief The Indentation class allows printing indentation conveniently, eg. cout << Indentation(4) << ... */ -class CPP_UTILITIES_EXPORT Indentation -{ +class CPP_UTILITIES_EXPORT Indentation { public: - Indentation(unsigned char level = 4, char character = ' ') : - level(level), - character(character) - {} + Indentation(unsigned char level = 4, char character = ' ') + : level(level) + , character(character) + { + } - Indentation operator +(unsigned char level) + Indentation operator+(unsigned char level) { return Indentation(this->level + level, character); } @@ -58,9 +52,9 @@ public: char character; }; -inline CPP_UTILITIES_EXPORT std::ostream &operator<< (std::ostream &out, Indentation indentation) +inline CPP_UTILITIES_EXPORT std::ostream &operator<<(std::ostream &out, Indentation indentation) { - for(unsigned char i = 0; i < indentation.level; ++i) { + for (unsigned char i = 0; i < indentation.level; ++i) { out << indentation.character; } return out; diff --git a/application/failure.cpp b/application/failure.cpp index 4adb8dd..41c359d 100644 --- a/application/failure.cpp +++ b/application/failure.cpp @@ -12,23 +12,26 @@ namespace ApplicationUtilities { /*! * Constructs a new Failure. */ -Failure::Failure() : - m_what("unspecified parsing exception") -{} +Failure::Failure() + : m_what("unspecified parsing exception") +{ +} /*! * Constructs a new Failure. \a what is a std::string * describing the cause of the Failure. */ -Failure::Failure(const std::string &what) : - m_what(what) -{} +Failure::Failure(const std::string &what) + : m_what(what) +{ +} /*! * Destroys the Failure. */ Failure::~Failure() USE_NOTHROW -{} +{ +} /*! * Returns a C-style character string describing the cause @@ -38,7 +41,4 @@ const char *Failure::what() const USE_NOTHROW { return m_what.c_str(); } - } - - diff --git a/application/failure.h b/application/failure.h index 4d443da..f68607e 100644 --- a/application/failure.h +++ b/application/failure.h @@ -8,8 +8,7 @@ namespace ApplicationUtilities { -class CPP_UTILITIES_EXPORT Failure : public std::exception -{ +class CPP_UTILITIES_EXPORT Failure : public std::exception { public: Failure(); Failure(const std::string &what); @@ -20,7 +19,6 @@ public: private: std::string m_what; }; - } #endif // APPLICATION_UTILITIES_FAILURE_H diff --git a/application/fakeqtconfigarguments.cpp b/application/fakeqtconfigarguments.cpp index 6bb84e9..39f16db 100644 --- a/application/fakeqtconfigarguments.cpp +++ b/application/fakeqtconfigarguments.cpp @@ -11,10 +11,12 @@ namespace ApplicationUtilities { /*! * \brief Constructs new fake Qt-config arguments. */ -FakeQtConfigArguments::FakeQtConfigArguments() : - m_qtWidgetsGuiArg("qt-widgets-gui", 'g', "shows a Qt widgets based graphical user interface (the application has not been built with Qt widgets support)"), - m_qtQuickGuiArg("qt-quick-gui", 'q', "shows a Qt quick based graphical user interface (the application has not been built with Qt quick support)") -{} +FakeQtConfigArguments::FakeQtConfigArguments() + : m_qtWidgetsGuiArg( + "qt-widgets-gui", 'g', "shows a Qt widgets based graphical user interface (the application has not been built with Qt widgets support)") + , m_qtQuickGuiArg( + "qt-quick-gui", 'q', "shows a Qt quick based graphical user interface (the application has not been built with Qt quick support)") +{ +} } // namespace ApplicationUtilities - diff --git a/application/fakeqtconfigarguments.h b/application/fakeqtconfigarguments.h index 9f5adb1..cc5afb7 100644 --- a/application/fakeqtconfigarguments.h +++ b/application/fakeqtconfigarguments.h @@ -5,8 +5,7 @@ namespace ApplicationUtilities { -class CPP_UTILITIES_EXPORT FakeQtConfigArguments -{ +class CPP_UTILITIES_EXPORT FakeQtConfigArguments { public: FakeQtConfigArguments(); @@ -47,7 +46,7 @@ inline bool FakeQtConfigArguments::areQtGuiArgsPresent() const } // namespace ApplicationUtilities #ifndef QT_CONFIG_ARGUMENTS -# define QT_CONFIG_ARGUMENTS ApplicationUtilities::FakeQtConfigArguments +#define QT_CONFIG_ARGUMENTS ApplicationUtilities::FakeQtConfigArguments #endif #endif // APPLICATIONUTILITIES_FAKEQTCONFIGARGUMENTS_H diff --git a/application/global.h b/application/global.h index 46dc707..3af9932 100644 --- a/application/global.h +++ b/application/global.h @@ -2,59 +2,59 @@ #define APPLICATION_UTILITIES_GLOBAL_H #if defined(_WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) -# ifndef PLATFORM_WINDOWS +#ifndef PLATFORM_WINDOWS /// \brief Defined when compiling for Windows. -# define PLATFORM_WINDOWS -# endif +#define PLATFORM_WINDOWS +#endif #endif #if defined(__CYGWIN__) -# ifndef PLATFORM_CYGWIN +#ifndef PLATFORM_CYGWIN /// \brief Defined when compiling for Cygwin. -# define PLATFORM_CYGWIN -# endif +#define PLATFORM_CYGWIN #endif -# if defined(__MINGW32__) || defined(__MINGW64__) -# ifndef PLATFORM_MINGW +#endif +#if defined(__MINGW32__) || defined(__MINGW64__) +#ifndef PLATFORM_MINGW /// \brief Defined when compiling with mingw(-w64). -# define PLATFORM_MINGW -# endif -# endif +#define PLATFORM_MINGW +#endif +#endif #if defined(__linux__) || defined(__linux) || defined(__gnu_linux__) -# ifndef PLATFORM_LINUX +#ifndef PLATFORM_LINUX /// \brief Defined when compiling for Linux. -# define PLATFORM_LINUX -# endif -# if defined(__ANDROID__) || defined(ANDROID) -# ifndef PLATFORM_ANDROID +#define PLATFORM_LINUX +#endif +#if defined(__ANDROID__) || defined(ANDROID) +#ifndef PLATFORM_ANDROID /// \brief Defined when compiling for Android. -# define PLATFORM_ANDROID -# endif -# endif +#define PLATFORM_ANDROID +#endif +#endif #endif #if defined(__APPLE__) -# include -# if defined(TARGET_OS_MAC) && TARGET_OS_MAC -# ifndef PLATFORM_MAC +#include +#if defined(TARGET_OS_MAC) && TARGET_OS_MAC +#ifndef PLATFORM_MAC /// \brief Defined when compiling for Mac/Darwin. -# define PLATFORM_MAC -# endif -# ifndef PLATFORM_BSD4 +#define PLATFORM_MAC +#endif +#ifndef PLATFORM_BSD4 /// \brief Defined when compiling for BSD 4. -# define PLATFORM_BSD4 -# endif -# endif +#define PLATFORM_BSD4 +#endif +#endif #endif #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__FreeBSD_kernel__) -# ifndef PLATFORM_FREE_BSD +#ifndef PLATFORM_FREE_BSD /// \brief Defined when compiling for FreeBSD -# define PLATFORM_FREE_BSD -# endif +#define PLATFORM_FREE_BSD +#endif #endif #if defined(__unix__) || defined(PLATFORM_LINUX) || defined(PLATFORM_FREE_BSD) || defined(PLATFORM_MAC) -# ifndef PLATFORM_UNIX +#ifndef PLATFORM_UNIX /// \brief Defined when compiling for any UNIX (like) system. -# define PLATFORM_UNIX -# endif +#define PLATFORM_UNIX +#endif #endif /*! @@ -75,13 +75,13 @@ */ #ifdef PLATFORM_WINDOWS -# define LIB_EXPORT __declspec(dllexport) -# define LIB_IMPORT __declspec(dllimport) -# define LIB_HIDDEN +#define LIB_EXPORT __declspec(dllexport) +#define LIB_IMPORT __declspec(dllimport) +#define LIB_HIDDEN #else -# define LIB_EXPORT __attribute__((visibility("default"))) -# define LIB_IMPORT __attribute__((visibility("default"))) -# define LIB_HIDDEN __attribute__((visibility("hidden"))) +#define LIB_EXPORT __attribute__((visibility("default"))) +#define LIB_IMPORT __attribute__((visibility("default"))) +#define LIB_HIDDEN __attribute__((visibility("hidden"))) #endif /*! @@ -91,11 +91,11 @@ */ #ifndef USE_NOTHROW -# if __cplusplus >= 201103L -# define USE_NOTHROW noexcept -# else -# define USE_NOTHROW throw() -# endif +#if __cplusplus >= 201103L +#define USE_NOTHROW noexcept +#else +#define USE_NOTHROW throw() +#endif #endif /*! @@ -125,9 +125,9 @@ */ #ifdef DEBUG_BUILD -# define IF_DEBUG_BUILD(x) x +#define IF_DEBUG_BUILD(x) x #else -# define IF_DEBUG_BUILD(x) +#define IF_DEBUG_BUILD(x) #endif /*! @@ -137,9 +137,9 @@ */ #ifdef __clang__ -# define FALLTHROUGH [[clang::fallthrough]] -# else -# define FALLTHROUGH +#define FALLTHROUGH [[clang::fallthrough]] +#else +#define FALLTHROUGH #endif #endif // APPLICATION_UTILITIES_GLOBAL_H diff --git a/chrono/datetime.cpp b/chrono/datetime.cpp index dbecb85..f8d4ac0 100644 --- a/chrono/datetime.cpp +++ b/chrono/datetime.cpp @@ -1,14 +1,14 @@ #include "./datetime.h" -#include "../conversion/stringconversion.h" #include "../conversion/stringbuilder.h" +#include "../conversion/stringconversion.h" -#include #include +#include #include #if defined(PLATFORM_UNIX) -# include +#include #endif using namespace std; @@ -22,21 +22,19 @@ const int DateTime::m_daysPer400Years = 146097; const int DateTime::m_daysTo1601 = 584388; const int DateTime::m_daysTo1899 = 693593; const int DateTime::m_daysTo10000 = 3652059; -const int DateTime::m_daysToMonth365[13] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; -const int DateTime::m_daysToMonth366[13] = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}; -const int DateTime::m_daysInMonth365[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; -const int DateTime::m_daysInMonth366[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; +const int DateTime::m_daysToMonth365[13] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; +const int DateTime::m_daysToMonth366[13] = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; +const int DateTime::m_daysInMonth365[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; +const int DateTime::m_daysInMonth366[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; -template -inline bool inRangeInclMax(num1 val, num2 min, num3 max) +template inline bool inRangeInclMax(num1 val, num2 min, num3 max) { return (val) >= (min) && (val) <= (max); } -template -inline bool inRangeExclMax(num1 val, num2 min, num3 max) +template inline bool inRangeExclMax(num1 val, num2 min, num3 max) { - return (val) >= (min) && (val) < (max); + return (val) >= (min) && (val) < (max); } /*! @@ -57,10 +55,10 @@ inline bool inRangeExclMax(num1 val, num2 min, num3 max) */ DateTime DateTime::fromTimeStamp(time_t timeStamp) { - if(timeStamp) { + if (timeStamp) { struct tm *timeinfo = localtime(&timeStamp); - return DateTime::fromDateAndTime(timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, - timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec < 60 ? timeinfo->tm_sec : 59, 0); + return DateTime::fromDateAndTime(timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, + timeinfo->tm_sec < 60 ? timeinfo->tm_sec : 59, 0); } else { return DateTime(); } @@ -79,30 +77,30 @@ DateTime DateTime::fromTimeStampGmt(time_t timeStamp) */ DateTime DateTime::fromString(const char *str) { - int values[6] = {0}; + int values[6] = { 0 }; int *const dayIndex = values + 2; int *const secondsIndex = values + 5; int *valueIndex = values; int *const valuesEnd = values + 7; double miliSecondsFact = 100.0, miliSeconds = 0.0; - for(const char *strIndex = str; ; ++strIndex) { + for (const char *strIndex = str;; ++strIndex) { const char c = *strIndex; - if(c <= '9' && c >= '0') { - if(valueIndex > secondsIndex) { - miliSeconds += (c - '0') * miliSecondsFact; - miliSecondsFact /= 10; + if (c <= '9' && c >= '0') { + if (valueIndex > secondsIndex) { + miliSeconds += (c - '0') * miliSecondsFact; + miliSecondsFact /= 10; } else { *valueIndex *= 10; *valueIndex += c - '0'; } - } else if((c == '-' || c == ':' || c == '/') || (c == '.' && (valueIndex == secondsIndex)) || (c == ' ' && (valueIndex == dayIndex))) { - if(++valueIndex == valuesEnd) { + } else if ((c == '-' || c == ':' || c == '/') || (c == '.' && (valueIndex == secondsIndex)) || (c == ' ' && (valueIndex == dayIndex))) { + if (++valueIndex == valuesEnd) { break; // just ignore further values for now } - } else if(c == '\0') { + } else if (c == '\0') { break; } else { - throw ConversionException("unexpected "s + c); + throw ConversionException(argsToString("unexpected ", c)); } } return DateTime::fromDateAndTime(values[0], values[1], *dayIndex, values[3], values[4], *secondsIndex, miliSeconds); @@ -117,7 +115,7 @@ DateTime DateTime::fromString(const char *str) */ std::pair DateTime::fromIsoString(const char *str) { - int values[9] = {0}; + int values[9] = { 0 }; int *const dayIndex = values + 2; int *const hourIndex = values + 3; int *const secondsIndex = values + 5; @@ -126,52 +124,53 @@ std::pair DateTime::fromIsoString(const char *str) int *valueIndex = values; bool deltaNegative = false; double miliSecondsFact = 100.0, miliSeconds = 0.0; - for(const char *strIndex = str; ; ++strIndex) { + for (const char *strIndex = str;; ++strIndex) { const char c = *strIndex; - if(c <= '9' && c >= '0') { - if(valueIndex == miliSecondsIndex) { + if (c <= '9' && c >= '0') { + if (valueIndex == miliSecondsIndex) { miliSeconds += (c - '0') * miliSecondsFact; miliSecondsFact /= 10; } else { *valueIndex *= 10; *valueIndex += c - '0'; } - } else if(c == 'T') { - if(++valueIndex != hourIndex) { + } else if (c == 'T') { + if (++valueIndex != hourIndex) { throw ConversionException("\"T\" expected before hour"); } - } else if(c == '-') { - if(valueIndex < dayIndex) { + } else if (c == '-') { + if (valueIndex < dayIndex) { ++valueIndex; } else { throw ConversionException("unexpected \"-\" after day"); } - } else if(c == '.') { - if(valueIndex != secondsIndex) { + } else if (c == '.') { + if (valueIndex != secondsIndex) { throw ConversionException("unexpected \".\""); } else { ++valueIndex; } - } else if(c == ':') { - if(valueIndex < hourIndex) { + } else if (c == ':') { + if (valueIndex < hourIndex) { throw ConversionException("unexpected \":\" before hour"); - } else if(valueIndex == secondsIndex) { + } else if (valueIndex == secondsIndex) { throw ConversionException("unexpected \":\" after second"); } else { ++valueIndex; } - } else if((c == '+') && (++valueIndex == deltaHourIndex)) { + } else if ((c == '+') && (++valueIndex == deltaHourIndex)) { deltaNegative = false; - } else if((c == '-') && (++valueIndex == deltaHourIndex)) { + } else if ((c == '-') && (++valueIndex == deltaHourIndex)) { deltaNegative = true; - } else if(c == '\0') { + } else if (c == '\0') { break; } else { - throw ConversionException("unexpected \""s % c + '\"'); + throw ConversionException(argsToString("unexpected \"", c, '\"')); } } deltaNegative && (*deltaHourIndex = -*deltaHourIndex); - return make_pair(DateTime::fromDateAndTime(values[0], values[1], *dayIndex, *hourIndex, values[4], *secondsIndex, miliSeconds), TimeSpan::fromMinutes(*deltaHourIndex * 60 + values[8])); + return make_pair(DateTime::fromDateAndTime(values[0], values[1], *dayIndex, *hourIndex, values[4], *secondsIndex, miliSeconds), + TimeSpan::fromMinutes(*deltaHourIndex * 60 + values[8])); } /*! @@ -195,25 +194,19 @@ void DateTime::toString(string &result, DateTimeOutputFormat format, bool noMill { stringstream s(stringstream::in | stringstream::out); s << setfill('0'); - if(format == DateTimeOutputFormat::DateTimeAndWeekday - || format == DateTimeOutputFormat::DateTimeAndShortWeekday) + if (format == DateTimeOutputFormat::DateTimeAndWeekday || format == DateTimeOutputFormat::DateTimeAndShortWeekday) s << printDayOfWeek(dayOfWeek(), format == DateTimeOutputFormat::DateTimeAndShortWeekday) << ' '; - if(format == DateTimeOutputFormat::DateOnly - || format == DateTimeOutputFormat::DateAndTime - || format == DateTimeOutputFormat::DateTimeAndWeekday - || format == DateTimeOutputFormat::DateTimeAndShortWeekday) + if (format == DateTimeOutputFormat::DateOnly || format == DateTimeOutputFormat::DateAndTime || format == DateTimeOutputFormat::DateTimeAndWeekday + || format == DateTimeOutputFormat::DateTimeAndShortWeekday) s << setw(4) << year() << '-' << setw(2) << month() << '-' << setw(2) << day(); - if(format == DateTimeOutputFormat::DateAndTime - || format == DateTimeOutputFormat::DateTimeAndWeekday - || format == DateTimeOutputFormat::DateTimeAndShortWeekday) + if (format == DateTimeOutputFormat::DateAndTime || format == DateTimeOutputFormat::DateTimeAndWeekday + || format == DateTimeOutputFormat::DateTimeAndShortWeekday) s << " "; - if(format == DateTimeOutputFormat::TimeOnly - || format == DateTimeOutputFormat::DateAndTime - || format == DateTimeOutputFormat::DateTimeAndWeekday - || format == DateTimeOutputFormat::DateTimeAndShortWeekday) { + if (format == DateTimeOutputFormat::TimeOnly || format == DateTimeOutputFormat::DateAndTime || format == DateTimeOutputFormat::DateTimeAndWeekday + || format == DateTimeOutputFormat::DateTimeAndShortWeekday) { s << setw(2) << hour() << ':' << setw(2) << minute() << ':' << setw(2) << second(); int ms = millisecond(); - if(!noMilliseconds && ms > 0) { + if (!noMilliseconds && ms > 0) { s << '.' << setw(3) << ms; } } @@ -228,9 +221,9 @@ string DateTime::toIsoString(TimeSpan timeZoneDelta) const { stringstream s(stringstream::in | stringstream::out); s << setfill('0'); - s << setw(4) << year() << '-' << setw(2) << month() << '-' << setw(2) << day() - << 'T' << setw(2) << hour() << ':' << setw(2) << minute() << ':' << setw(2) << second() << '.' << setw(3) << millisecond(); - if(!timeZoneDelta.isNull()) { + s << setw(4) << year() << '-' << setw(2) << month() << '-' << setw(2) << day() << 'T' << setw(2) << hour() << ':' << setw(2) << minute() << ':' + << setw(2) << second() << '.' << setw(3) << millisecond(); + if (!timeZoneDelta.isNull()) { s << (timeZoneDelta.isNegative() ? '-' : '+'); s << setw(2) << timeZoneDelta.hours() << ':' << setw(2) << timeZoneDelta.minutes(); } @@ -246,8 +239,8 @@ string DateTime::toIsoString(TimeSpan timeZoneDelta) const */ const char *DateTime::printDayOfWeek(DayOfWeek dayOfWeek, bool abbreviation) { - if(abbreviation) { - switch(dayOfWeek) { + if (abbreviation) { + switch (dayOfWeek) { case DayOfWeek::Monday: return "Mon"; case DayOfWeek::Tuesday: @@ -264,7 +257,7 @@ const char *DateTime::printDayOfWeek(DayOfWeek dayOfWeek, bool abbreviation) return "Sun"; } } else { - switch(dayOfWeek) { + switch (dayOfWeek) { case DayOfWeek::Monday: return "Monday"; case DayOfWeek::Tuesday: @@ -293,7 +286,8 @@ DateTime DateTime::exactGmtNow() { struct timespec t; clock_gettime(CLOCK_REALTIME, &t); - return DateTime(DateTime::unixEpochStart().totalTicks() + static_cast(t.tv_sec) * TimeSpan::ticksPerSecond + static_cast(t.tv_nsec) / 100); + return DateTime( + DateTime::unixEpochStart().totalTicks() + static_cast(t.tv_sec) * TimeSpan::ticksPerSecond + static_cast(t.tv_nsec) / 100); } #endif @@ -302,14 +296,15 @@ DateTime DateTime::exactGmtNow() */ uint64 DateTime::dateToTicks(int year, int month, int day) { - if(inRangeInclMax(year, 1, 9999)) { - if(inRangeInclMax(month, 1, 12)) { + if (inRangeInclMax(year, 1, 9999)) { + if (inRangeInclMax(month, 1, 12)) { const int *daysToMonth = isLeapYear(year) ? m_daysToMonth366 : m_daysToMonth365; int passedMonth = month - 1; - if(inRangeInclMax(day, 1, daysToMonth[month] - daysToMonth[passedMonth])) { + if (inRangeInclMax(day, 1, daysToMonth[month] - daysToMonth[passedMonth])) { int passedYears = year - 1; int passedDays = day - 1; - return (passedYears * m_daysPerYear + passedYears / 4 - passedYears / 100 + passedYears / 400 + daysToMonth[passedMonth] + passedDays) * TimeSpan::ticksPerDay; + return (passedYears * m_daysPerYear + passedYears / 4 - passedYears / 100 + passedYears / 400 + daysToMonth[passedMonth] + passedDays) + * TimeSpan::ticksPerDay; } else { throw ConversionException("day is out of range"); } @@ -327,19 +322,20 @@ uint64 DateTime::dateToTicks(int year, int month, int day) */ uint64 DateTime::timeToTicks(int hour, int minute, int second, double millisecond) { - if(!inRangeExclMax(hour, 0, 24)) { + if (!inRangeExclMax(hour, 0, 24)) { throw ConversionException("hour is out of range"); } - if(!inRangeExclMax(minute, 0, 60)) { + if (!inRangeExclMax(minute, 0, 60)) { throw ConversionException("minute is out of range"); } - if(!inRangeExclMax(second, 0, 60)) { + if (!inRangeExclMax(second, 0, 60)) { throw ConversionException("second is out of range"); } - if(!inRangeExclMax(millisecond, 0.0, 1000.0)) { + if (!inRangeExclMax(millisecond, 0.0, 1000.0)) { throw ConversionException("millisecond is out of range"); } - return (hour * TimeSpan::ticksPerHour) + (minute * TimeSpan::ticksPerMinute) + (second * TimeSpan::ticksPerSecond) + (uint64)(millisecond * (double)TimeSpan::ticksPerMillisecond); + return (hour * TimeSpan::ticksPerHour) + (minute * TimeSpan::ticksPerMinute) + (second * TimeSpan::ticksPerSecond) + + (uint64)(millisecond * (double)TimeSpan::ticksPerMillisecond); } /*! @@ -352,31 +348,31 @@ int DateTime::getDatePart(DatePart part) const int full400YearBlocks = fullDays / m_daysPer400Years; int daysMinusFull400YearBlocks = fullDays - full400YearBlocks * m_daysPer400Years; int full100YearBlocks = daysMinusFull400YearBlocks / m_daysPer100Years; - if(full100YearBlocks == 4) { + if (full100YearBlocks == 4) { full100YearBlocks = 3; } int daysMinusFull100YearBlocks = daysMinusFull400YearBlocks - full100YearBlocks * m_daysPer100Years; int full4YearBlocks = daysMinusFull100YearBlocks / m_daysPer4Years; int daysMinusFull4YearBlocks = daysMinusFull100YearBlocks - full4YearBlocks * m_daysPer4Years; int full1YearBlocks = daysMinusFull4YearBlocks / m_daysPerYear; - if(full1YearBlocks == 4) { + if (full1YearBlocks == 4) { full1YearBlocks = 3; } - if(part == DatePart::Year) { + if (part == DatePart::Year) { return full400YearBlocks * 400 + full100YearBlocks * 100 + full4YearBlocks * 4 + full1YearBlocks + 1; } int restDays = daysMinusFull4YearBlocks - full1YearBlocks * m_daysPerYear; - if(part == DatePart::DayOfYear) { // day + if (part == DatePart::DayOfYear) { // day return restDays + 1; } const int *daysToMonth = (full1YearBlocks == 3 && (full4YearBlocks != 24 || full100YearBlocks == 3)) ? m_daysToMonth366 : m_daysToMonth365; int month = 1; - while(restDays >= daysToMonth[month]) { + while (restDays >= daysToMonth[month]) { ++month; } - if(part == DatePart::Month) { + if (part == DatePart::Month) { return month; - } else if(part == DatePart::Day) { + } else if (part == DatePart::Day) { return restDays - daysToMonth[month - 1] + 1; } return 0; diff --git a/chrono/datetime.h b/chrono/datetime.h index fef2713..ca02fb6 100644 --- a/chrono/datetime.h +++ b/chrono/datetime.h @@ -5,19 +5,17 @@ #include "../conversion/types.h" -#include -#include #include +#include +#include -namespace ChronoUtilities -{ +namespace ChronoUtilities { /*! * \brief Specifies the output format. * \sa DateTime::toString() */ -enum class DateTimeOutputFormat -{ +enum class DateTimeOutputFormat { DateAndTime, /**< date and time */ DateOnly, /**< date only */ TimeOnly, /**< time only */ @@ -29,8 +27,7 @@ enum class DateTimeOutputFormat * \brief Specifies the day of the week. * \sa DateTime::dayOfWeek() */ -enum class DayOfWeek -{ +enum class DayOfWeek { Monday, /**< Monday */ Tuesday, /**< Tuesday */ Wednesday, /**< Wednesday */ @@ -44,16 +41,14 @@ enum class DayOfWeek * \brief Specifies the date part. * \sa DateTime::getDatePart() */ -enum class DatePart -{ +enum class DatePart { Year, /**< year */ Month, /**< month */ DayOfYear, /**< day of year */ Day /**< day */ }; -class CPP_UTILITIES_EXPORT DateTime -{ +class CPP_UTILITIES_EXPORT DateTime { public: explicit constexpr DateTime(); explicit constexpr DateTime(uint64 ticks); @@ -98,18 +93,18 @@ public: constexpr static bool isLeapYear(int year); static int daysInMonth(int year, int month); - constexpr bool operator ==(const DateTime &other) const; - constexpr bool operator !=(const DateTime &other) const; - constexpr bool operator <(const DateTime &other) const; - constexpr bool operator >(const DateTime &other) const; - constexpr bool operator <=(const DateTime &other) const; - constexpr bool operator >=(const DateTime &other) const; - constexpr DateTime operator +(const TimeSpan &timeSpan) const; - constexpr DateTime operator -(const TimeSpan &timeSpan) const; - constexpr TimeSpan operator +(const DateTime &other) const; - constexpr TimeSpan operator -(const DateTime &other) const; - DateTime &operator +=(const TimeSpan &timeSpan); - DateTime &operator -=(const TimeSpan &timeSpan); + constexpr bool operator==(const DateTime &other) const; + constexpr bool operator!=(const DateTime &other) const; + constexpr bool operator<(const DateTime &other) const; + constexpr bool operator>(const DateTime &other) const; + constexpr bool operator<=(const DateTime &other) const; + constexpr bool operator>=(const DateTime &other) const; + constexpr DateTime operator+(const TimeSpan &timeSpan) const; + constexpr DateTime operator-(const TimeSpan &timeSpan) const; + constexpr TimeSpan operator+(const DateTime &other) const; + constexpr TimeSpan operator-(const DateTime &other) const; + DateTime &operator+=(const TimeSpan &timeSpan); + DateTime &operator-=(const TimeSpan &timeSpan); private: static uint64 dateToTicks(int year, int month, int day); @@ -130,21 +125,21 @@ private: static const int m_daysInMonth366[12]; }; - - /*! * \brief Constructs a DateTime. */ -constexpr inline DateTime::DateTime() : - m_ticks(0) -{} +constexpr inline DateTime::DateTime() + : m_ticks(0) +{ +} /*! * \brief Constructs a DateTime with the specified number of \a ticks. */ -constexpr inline DateTime::DateTime(uint64 ticks) : - m_ticks(ticks) -{} +constexpr inline DateTime::DateTime(uint64 ticks) + : m_ticks(ticks) +{ +} /*! * \brief Constructs a DateTime to the specified \a year, \a month, and \a day. @@ -167,7 +162,7 @@ inline DateTime DateTime::fromTime(int hour, int minute, int second, double mill */ inline DateTime DateTime::fromDateAndTime(int year, int month, int day, int hour, int minute, int second, double millisecond) { - if(uint64 ticks = dateToTicks(year, month, day)) { + if (uint64 ticks = dateToTicks(year, month, day)) { return DateTime(ticks + timeToTicks(hour, minute, second, millisecond)); } return DateTime(); @@ -321,11 +316,7 @@ constexpr inline bool DateTime::isEternity() const */ constexpr inline bool DateTime::isLeapYear(int year) { - return (year % 4 != 0) - ? false - : ((year % 100 == 0) - ? (year % 400 == 0) - : true); + return (year % 4 != 0) ? false : ((year % 100 == 0) ? (year % 400 == 0) : true); } /*! @@ -333,11 +324,7 @@ constexpr inline bool DateTime::isLeapYear(int year) */ inline int DateTime::daysInMonth(int year, int month) { - return (month >= 1 && month <= 12) - ? (isLeapYear(year) - ? m_daysInMonth366[month - 1] - : m_daysInMonth365[month - 1]) - : (0); + return (month >= 1 && month <= 12) ? (isLeapYear(year) ? m_daysInMonth366[month - 1] : m_daysInMonth365[month - 1]) : (0); } /*! @@ -385,7 +372,7 @@ inline DateTime DateTime::gmtNow() /*! * \brief Indicates whether two DateTime instances are equal. */ -constexpr inline bool DateTime::operator ==(const DateTime &other) const +constexpr inline bool DateTime::operator==(const DateTime &other) const { return m_ticks == other.m_ticks; } @@ -393,7 +380,7 @@ constexpr inline bool DateTime::operator ==(const DateTime &other) const /*! * \brief Indicates whether two DateTime instances are not equal. */ -constexpr inline bool DateTime::operator !=(const DateTime &other) const +constexpr inline bool DateTime::operator!=(const DateTime &other) const { return m_ticks != other.m_ticks; } @@ -401,7 +388,7 @@ constexpr inline bool DateTime::operator !=(const DateTime &other) const /*! * \brief Indicates whether a specified DateTime is less than another specified DateTime. */ -constexpr inline bool DateTime::operator <(const DateTime &other) const +constexpr inline bool DateTime::operator<(const DateTime &other) const { return m_ticks < other.m_ticks; } @@ -409,7 +396,7 @@ constexpr inline bool DateTime::operator <(const DateTime &other) const /*! * \brief Indicates whether a specified DateTime is greater than another specified DateTime. */ -constexpr inline bool DateTime::operator >(const DateTime &other) const +constexpr inline bool DateTime::operator>(const DateTime &other) const { return m_ticks > other.m_ticks; } @@ -417,7 +404,7 @@ constexpr inline bool DateTime::operator >(const DateTime &other) const /*! * \brief Indicates whether a specified DateTime is less or equal than another specified DateTime. */ -constexpr inline bool DateTime::operator <=(const DateTime &other) const +constexpr inline bool DateTime::operator<=(const DateTime &other) const { return m_ticks <= other.m_ticks; } @@ -425,7 +412,7 @@ constexpr inline bool DateTime::operator <=(const DateTime &other) const /*! * \brief Indicates whether a specified DateTime is greater or equal than another specified DateTime. */ -constexpr inline bool DateTime::operator >=(const DateTime &other) const +constexpr inline bool DateTime::operator>=(const DateTime &other) const { return m_ticks >= other.m_ticks; } @@ -434,7 +421,7 @@ constexpr inline bool DateTime::operator >=(const DateTime &other) const * \brief Adds another instance. * \returns The result is another DateTime. */ -constexpr inline DateTime DateTime::operator +(const TimeSpan &timeSpan) const +constexpr inline DateTime DateTime::operator+(const TimeSpan &timeSpan) const { return DateTime(m_ticks + timeSpan.m_ticks); } @@ -443,7 +430,7 @@ constexpr inline DateTime DateTime::operator +(const TimeSpan &timeSpan) const * \brief Substracts another instance. * \returns The result is another DateTime. */ -constexpr inline DateTime DateTime::operator -(const TimeSpan &timeSpan) const +constexpr inline DateTime DateTime::operator-(const TimeSpan &timeSpan) const { return DateTime(m_ticks - timeSpan.m_ticks); } @@ -452,7 +439,7 @@ constexpr inline DateTime DateTime::operator -(const TimeSpan &timeSpan) const * \brief Adds two instances. * \returns The result is a TimeSpan. */ -constexpr inline TimeSpan DateTime::operator +(const DateTime &other) const +constexpr inline TimeSpan DateTime::operator+(const DateTime &other) const { return TimeSpan(m_ticks + other.m_ticks); } @@ -461,7 +448,7 @@ constexpr inline TimeSpan DateTime::operator +(const DateTime &other) const * \brief Substracts two DateTime instances. * \returns The result is a TimeSpan. */ -constexpr inline TimeSpan DateTime::operator -(const DateTime &other) const +constexpr inline TimeSpan DateTime::operator-(const DateTime &other) const { return TimeSpan(m_ticks - other.m_ticks); } @@ -469,7 +456,7 @@ constexpr inline TimeSpan DateTime::operator -(const DateTime &other) const /*! * \brief Adds a TimeSpan to the current instance. */ -inline DateTime &DateTime::operator +=(const TimeSpan &timeSpan) +inline DateTime &DateTime::operator+=(const TimeSpan &timeSpan) { m_ticks += timeSpan.m_ticks; return *this; @@ -478,20 +465,18 @@ inline DateTime &DateTime::operator +=(const TimeSpan &timeSpan) /*! * \brief Substracts a TimeSpan from the current instance. */ -inline DateTime &DateTime::operator -=(const TimeSpan &timeSpan) +inline DateTime &DateTime::operator-=(const TimeSpan &timeSpan) { m_ticks -= timeSpan.m_ticks; return *this; } - } namespace std { -template<> struct hash -{ +template <> struct hash { inline size_t operator()(const ChronoUtilities::DateTime &dateTime) const { - return hash()(dateTime.totalTicks()); + return hash()(dateTime.totalTicks()); } }; } diff --git a/chrono/format.h b/chrono/format.h index 30de10d..ae922c2 100644 --- a/chrono/format.h +++ b/chrono/format.h @@ -5,12 +5,12 @@ #include -inline std::ostream &operator<< (std::ostream &out, const ChronoUtilities::DateTime &value) +inline std::ostream &operator<<(std::ostream &out, const ChronoUtilities::DateTime &value) { return out << value.toString(ChronoUtilities::DateTimeOutputFormat::DateAndTime, false); } -inline std::ostream &operator<< (std::ostream &out, const ChronoUtilities::TimeSpan &value) +inline std::ostream &operator<<(std::ostream &out, const ChronoUtilities::TimeSpan &value) { return out << value.toString(ChronoUtilities::TimeSpanOutputFormat::Normal, false); } diff --git a/chrono/period.cpp b/chrono/period.cpp index cb449bf..98ec0cc 100644 --- a/chrono/period.cpp +++ b/chrono/period.cpp @@ -27,7 +27,4 @@ Period::Period(const DateTime &beg, const DateTime &end) --m_years; } } - } - - diff --git a/chrono/period.h b/chrono/period.h index 8ea594e..59d5f53 100644 --- a/chrono/period.h +++ b/chrono/period.h @@ -5,13 +5,13 @@ namespace ChronoUtilities { -class CPP_UTILITIES_EXPORT Period -{ +class CPP_UTILITIES_EXPORT Period { public: Period(const DateTime &beg, const DateTime &end); int years() const; int months() const; int days() const; + private: int m_years; int m_months; @@ -41,7 +41,6 @@ inline int Period::days() const { return m_days; } - } #endif // CHRONO_UTILITIES_PERIOD_H diff --git a/chrono/timespan.cpp b/chrono/timespan.cpp index 7913f40..f077b03 100644 --- a/chrono/timespan.cpp +++ b/chrono/timespan.cpp @@ -2,9 +2,9 @@ #include "../conversion/stringconversion.h" -#include #include #include +#include #include using namespace std; @@ -24,16 +24,16 @@ TimeSpan TimeSpan::fromString(const char *str, char separator) { vector parts; size_t partsSize = 1; - for(const char *i = str; *i; ++i) { + for (const char *i = str; *i; ++i) { *i == separator && ++partsSize; } parts.reserve(partsSize); - for(const char *i = str; ;) { - if(*i == separator) { + for (const char *i = str;;) { + if (*i == separator) { parts.emplace_back(stringToNumber(string(str, i))); str = ++i; - } else if(*i == '\0') { + } else if (*i == '\0') { parts.emplace_back(stringToNumber(string(str, i))); break; } else { @@ -41,7 +41,7 @@ TimeSpan TimeSpan::fromString(const char *str, char separator) } } - switch(parts.size()) { + switch (parts.size()) { case 0: return TimeSpan(); case 1: @@ -79,31 +79,31 @@ string TimeSpan::toString(TimeSpanOutputFormat format, bool noMilliseconds) cons void TimeSpan::toString(string &result, TimeSpanOutputFormat format, bool noMilliseconds) const { stringstream s(stringstream::in | stringstream::out); - if(isNegative()) + if (isNegative()) s << "- "; - switch(format) { + switch (format) { case TimeSpanOutputFormat::Normal: s << setfill('0') << setw(2) << floor(fabs(totalHours())) << ":" << setw(2) << minutes() << ":" << setw(2) << seconds() << " "; break; case TimeSpanOutputFormat::WithMeasures: - if(isNull()) { + if (isNull()) { s << "0 s "; - } else if(totalMilliseconds() < 1.0) { + } else if (totalMilliseconds() < 1.0) { s << setprecision(2) << (m_ticks / 10.0) << " µs "; } else { - if(days()) { + if (days()) { s << days() << " d "; } - if(hours()) { + if (hours()) { s << hours() << " h "; } - if(minutes()) { + if (minutes()) { s << minutes() << " min "; } - if(seconds()) { + if (seconds()) { s << seconds() << " s "; } - if(!noMilliseconds && milliseconds()) { + if (!noMilliseconds && milliseconds()) { s << milliseconds() << " ms "; } } @@ -111,5 +111,3 @@ void TimeSpan::toString(string &result, TimeSpanOutputFormat format, bool noMill } result = s.str().substr(0, static_cast(s.tellp()) - 1); } - - diff --git a/chrono/timespan.h b/chrono/timespan.h index ae2fc1a..ab10e4a 100644 --- a/chrono/timespan.h +++ b/chrono/timespan.h @@ -1,17 +1,16 @@ #ifndef CHRONO_UTILITIES_TIMESPAN_H #define CHRONO_UTILITIES_TIMESPAN_H -#include "../global.h" #include "../conversion/types.h" +#include "../global.h" -#include #include +#include /*! * \brief Contains classes providing a means for handling date and time information. */ -namespace ChronoUtilities -{ +namespace ChronoUtilities { class DateTime; @@ -19,15 +18,14 @@ class DateTime; * \brief Specifies the output format. * \sa TimeSpan::toString() */ -enum class TimeSpanOutputFormat -{ +enum class TimeSpanOutputFormat { Normal, /**< the normal form of specifing a time interval: hh:mm:ss */ WithMeasures /**< measures are used, eg.: 34 d 5 h 10 min 7 s 31 ms */ }; -class CPP_UTILITIES_EXPORT TimeSpan -{ +class CPP_UTILITIES_EXPORT TimeSpan { friend class DateTime; + public: explicit constexpr TimeSpan(); explicit constexpr TimeSpan(int64 ticks); @@ -86,14 +84,18 @@ private: /*! * \brief Constructs a new instance of the TimeSpan class with zero ticks. */ -constexpr inline TimeSpan::TimeSpan() : m_ticks(0) -{} +constexpr inline TimeSpan::TimeSpan() + : m_ticks(0) +{ +} /*! * \brief Constructs a new instance of the TimeSpan class with the specified number of ticks. */ -constexpr inline TimeSpan::TimeSpan(int64 ticks) : m_ticks(ticks) -{} +constexpr inline TimeSpan::TimeSpan(int64 ticks) + : m_ticks(ticks) +{ +} /*! * \brief Constructs a new instance of the TimeSpan class with the specified number of miliseconds. @@ -250,7 +252,7 @@ constexpr inline int TimeSpan::days() const /*! * \brief Indicates whether two TimeSpan instances are equal. */ -constexpr inline bool TimeSpan::operator ==(const TimeSpan &other) const +constexpr inline bool TimeSpan::operator==(const TimeSpan &other) const { return m_ticks == other.m_ticks; } @@ -258,7 +260,7 @@ constexpr inline bool TimeSpan::operator ==(const TimeSpan &other) const /*! * \brief Indicates whether two TimeSpan instances are not equal. */ -constexpr inline bool TimeSpan::operator !=(const TimeSpan &other) const +constexpr inline bool TimeSpan::operator!=(const TimeSpan &other) const { return m_ticks != other.m_ticks; } @@ -266,7 +268,7 @@ constexpr inline bool TimeSpan::operator !=(const TimeSpan &other) const /*! * \brief Indicates whether a specified TimeSpan is less than another specified TimeSpan. */ -constexpr inline bool TimeSpan::operator <(const TimeSpan &other) const +constexpr inline bool TimeSpan::operator<(const TimeSpan &other) const { return m_ticks < other.m_ticks; } @@ -274,7 +276,7 @@ constexpr inline bool TimeSpan::operator <(const TimeSpan &other) const /*! * \brief Indicates whether a specified TimeSpan is greater than another specified TimeSpan. */ -constexpr inline bool TimeSpan::operator >(const TimeSpan &other) const +constexpr inline bool TimeSpan::operator>(const TimeSpan &other) const { return m_ticks > other.m_ticks; } @@ -282,7 +284,7 @@ constexpr inline bool TimeSpan::operator >(const TimeSpan &other) const /*! * \brief Indicates whether a specified TimeSpan is less or equal than another specified TimeSpan. */ -constexpr inline bool TimeSpan::operator <=(const TimeSpan &other) const +constexpr inline bool TimeSpan::operator<=(const TimeSpan &other) const { return m_ticks <= other.m_ticks; } @@ -290,7 +292,7 @@ constexpr inline bool TimeSpan::operator <=(const TimeSpan &other) const /*! * \brief Indicates whether a specified TimeSpan is greater or equal than another specified TimeSpan. */ -constexpr inline bool TimeSpan::operator >=(const TimeSpan &other) const +constexpr inline bool TimeSpan::operator>=(const TimeSpan &other) const { return m_ticks >= other.m_ticks; } @@ -298,7 +300,7 @@ constexpr inline bool TimeSpan::operator >=(const TimeSpan &other) const /*! * \brief Adds two TimeSpan instances. */ -constexpr inline TimeSpan TimeSpan::operator +(const TimeSpan &other) const +constexpr inline TimeSpan TimeSpan::operator+(const TimeSpan &other) const { return TimeSpan(m_ticks + other.m_ticks); } @@ -306,7 +308,7 @@ constexpr inline TimeSpan TimeSpan::operator +(const TimeSpan &other) const /*! * \brief Substracts two TimeSpan instances. */ -constexpr inline TimeSpan TimeSpan::operator -(const TimeSpan &other) const +constexpr inline TimeSpan TimeSpan::operator-(const TimeSpan &other) const { return TimeSpan(m_ticks - other.m_ticks); } @@ -314,7 +316,7 @@ constexpr inline TimeSpan TimeSpan::operator -(const TimeSpan &other) const /*! * \brief Adds another TimeSpan to the current instance. */ -inline TimeSpan &TimeSpan::operator +=(const TimeSpan &other) +inline TimeSpan &TimeSpan::operator+=(const TimeSpan &other) { m_ticks += other.m_ticks; return *this; @@ -323,7 +325,7 @@ inline TimeSpan &TimeSpan::operator +=(const TimeSpan &other) /*! * \brief Substracts another TimeSpan from the current instance. */ -inline TimeSpan &TimeSpan::operator -=(const TimeSpan &other) +inline TimeSpan &TimeSpan::operator-=(const TimeSpan &other) { m_ticks -= other.m_ticks; return *this; @@ -360,15 +362,13 @@ constexpr inline bool TimeSpan::isInfinity() const { return m_ticks == std::numeric_limits::max(); } - } namespace std { -template<> struct hash -{ +template <> struct hash { inline size_t operator()(const ChronoUtilities::TimeSpan &timeSpan) const { - return hash()(timeSpan.totalTicks()); + return hash()(timeSpan.totalTicks()); } }; } diff --git a/conversion/binaryconversion.h b/conversion/binaryconversion.h index 6f30edb..29565d9 100644 --- a/conversion/binaryconversion.h +++ b/conversion/binaryconversion.h @@ -6,63 +6,63 @@ #include "../global.h" #ifdef __BYTE_ORDER__ -# if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ -# define CONVERSION_UTILITIES_IS_BYTE_ORDER_LITTLE_ENDIAN false -# define CONVERSION_UTILITIES_IS_BYTE_ORDER_BIG_ENDIAN true -# define CONVERSION_UTILITIES_BYTE_ORDER_BIG_ENDIAN -# elif __BYTE_ORDER__ == __ORDER_PDP_ENDIAN__ -# define CONVERSION_UTILITIES_IS_BYTE_ORDER_LITTLE_ENDIAN false -# define CONVERSION_UTILITIES_IS_BYTE_ORDER_BIG_ENDIAN false -# define CONVERSION_UTILITIES_BYTE_ORDER_MIDDLE_ENDIAN -# elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ -# define CONVERSION_UTILITIES_IS_BYTE_ORDER_LITTLE_ENDIAN true -# define CONVERSION_UTILITIES_IS_BYTE_ORDER_BIG_ENDIAN false -# define CONVERSION_UTILITIES_BYTE_ORDER_LITTLE_ENDIAN -# endif +#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +#define CONVERSION_UTILITIES_IS_BYTE_ORDER_LITTLE_ENDIAN false +#define CONVERSION_UTILITIES_IS_BYTE_ORDER_BIG_ENDIAN true +#define CONVERSION_UTILITIES_BYTE_ORDER_BIG_ENDIAN +#elif __BYTE_ORDER__ == __ORDER_PDP_ENDIAN__ +#define CONVERSION_UTILITIES_IS_BYTE_ORDER_LITTLE_ENDIAN false +#define CONVERSION_UTILITIES_IS_BYTE_ORDER_BIG_ENDIAN false +#define CONVERSION_UTILITIES_BYTE_ORDER_MIDDLE_ENDIAN +#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +#define CONVERSION_UTILITIES_IS_BYTE_ORDER_LITTLE_ENDIAN true +#define CONVERSION_UTILITIES_IS_BYTE_ORDER_BIG_ENDIAN false +#define CONVERSION_UTILITIES_BYTE_ORDER_LITTLE_ENDIAN +#endif #endif #ifdef __FLOAT_WORD_ORDER__ -# if __FLOAT_WORD_ORDER__ == __ORDER_BIG_ENDIAN__ -# define CONVERSION_UTILITIES_FLOAT_BYTE_ORDER_BIG_ENDIAN -# elif __FLOAT_WORD_ORDER__ == __ORDER_PDP_ENDIAN__ -# define CONVERSION_UTILITIES_FLOAT_BYTE_ORDER_MIDDLE_ENDIAN -# elif __FLOAT_WORD_ORDER__ == __ORDER_LITTLE_ENDIAN__ -# define CONVERSION_UTILITIES_FLOAT_BYTE_ORDER_LITTLE_ENDIAN -# endif +#if __FLOAT_WORD_ORDER__ == __ORDER_BIG_ENDIAN__ +#define CONVERSION_UTILITIES_FLOAT_BYTE_ORDER_BIG_ENDIAN +#elif __FLOAT_WORD_ORDER__ == __ORDER_PDP_ENDIAN__ +#define CONVERSION_UTILITIES_FLOAT_BYTE_ORDER_MIDDLE_ENDIAN +#elif __FLOAT_WORD_ORDER__ == __ORDER_LITTLE_ENDIAN__ +#define CONVERSION_UTILITIES_FLOAT_BYTE_ORDER_LITTLE_ENDIAN +#endif #endif #if defined(__BYTE_ORDER__) && defined(__FLOAT_WORD_ORDER__) #else -# if defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(_M_X64) || defined(__LITTLE_ENDIAN__) || defined(_little_endian__) || defined(_LITTLE_ENDIAN) || defined(_WIN32_WCE) || defined(WINAPI_FAMILY) -# ifndef __BYTE_ORDER__ -# define CONVERSION_UTILITIES_IS_BYTE_ORDER_LITTLE_ENDIAN true -# define CONVERSION_UTILITIES_IS_BYTE_ORDER_BIG_ENDIAN false -# define CONVERSION_UTILITIES_BYTE_ORDER_LITTLE_ENDIAN -# endif -# ifndef __FLOAT_WORD_ORDER__ -# define CONVERSION_UTILITIES_FLOAT_BYTE_ORDER_LITTLE_ENDIAN -# endif -# elif defined(__MIPSEB__) || defined(__s390__) || defined(__BIG_ENDIAN__) || defined(_big_endian__) || defined(_BIG_ENDIAN) -# ifndef __BYTE_ORDER__ -# define CONVERSION_UTILITIES_IS_BYTE_ORDER_LITTLE_ENDIAN false -# define CONVERSION_UTILITIES_IS_BYTE_ORDER_BIG_ENDIAN true -# define CONVERSION_UTILITIES_BYTE_ORDER_BIG_ENDIAN -# endif -# ifndef __FLOAT_WORD_ORDER__ -# define CONVERSION_UTILITIES_FLOAT_BYTE_ORDER_BIG_ENDIAN -# endif -# else -# error "Unable to determine byte order!" -# endif +#if defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(_M_X64) \ + || defined(__LITTLE_ENDIAN__) || defined(_little_endian__) || defined(_LITTLE_ENDIAN) || defined(_WIN32_WCE) || defined(WINAPI_FAMILY) +#ifndef __BYTE_ORDER__ +#define CONVERSION_UTILITIES_IS_BYTE_ORDER_LITTLE_ENDIAN true +#define CONVERSION_UTILITIES_IS_BYTE_ORDER_BIG_ENDIAN false +#define CONVERSION_UTILITIES_BYTE_ORDER_LITTLE_ENDIAN +#endif +#ifndef __FLOAT_WORD_ORDER__ +#define CONVERSION_UTILITIES_FLOAT_BYTE_ORDER_LITTLE_ENDIAN +#endif +#elif defined(__MIPSEB__) || defined(__s390__) || defined(__BIG_ENDIAN__) || defined(_big_endian__) || defined(_BIG_ENDIAN) +#ifndef __BYTE_ORDER__ +#define CONVERSION_UTILITIES_IS_BYTE_ORDER_LITTLE_ENDIAN false +#define CONVERSION_UTILITIES_IS_BYTE_ORDER_BIG_ENDIAN true +#define CONVERSION_UTILITIES_BYTE_ORDER_BIG_ENDIAN +#endif +#ifndef __FLOAT_WORD_ORDER__ +#define CONVERSION_UTILITIES_FLOAT_BYTE_ORDER_BIG_ENDIAN +#endif +#else +#error "Unable to determine byte order!" +#endif #endif #if defined(CONVERSION_UTILITIES_BYTE_ORDER_MIDDLE_ENDIAN) -# error "Middle endian byte order is not supported!" +#error "Middle endian byte order is not supported!" #endif #if defined(CONVERSION_UTILITIES_FLOAT_BYTE_ORDER_MIDDLE_ENDIAN) -# error "Middle endian byte order is not supported!" +#error "Middle endian byte order is not supported!" #endif -namespace ConversionUtilities -{ +namespace ConversionUtilities { /*! * \brief Encapsulates binary conversion functions using the big endian byte order. @@ -71,13 +71,12 @@ namespace ConversionUtilities namespace BE { #if defined(CONVERSION_UTILITIES_BYTE_ORDER_LITTLE_ENDIAN) -# define CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL 0 +#define CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL 0 #elif defined(CONVERSION_UTILITIES_BYTE_ORDER_BIG_ENDIAN) -# define CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL 1 +#define CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL 1 #endif #include "./binaryconversionprivate.h" #undef CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL - } /*! @@ -87,13 +86,12 @@ namespace BE { namespace LE { #if defined(CONVERSION_UTILITIES_BYTE_ORDER_LITTLE_ENDIAN) -# define CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL 1 +#define CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL 1 #elif defined(CONVERSION_UTILITIES_BYTE_ORDER_BIG_ENDIAN) -# define CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL 0 +#define CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL 0 #endif #include "./binaryconversionprivate.h" #undef CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL - } /*! @@ -135,10 +133,7 @@ CPP_UTILITIES_EXPORT constexpr float32 toFloat32(uint32 fixed16value) */ CPP_UTILITIES_EXPORT constexpr uint32 toSynchsafeInt(uint32 normalInt) { - return ((normalInt & 0x0000007fu) ) - | ((normalInt & 0x00003f80u) << 1) - | ((normalInt & 0x001fc000u) << 2) - | ((normalInt & 0x0fe00000u) << 3); + return ((normalInt & 0x0000007fu)) | ((normalInt & 0x00003f80u) << 1) | ((normalInt & 0x001fc000u) << 2) | ((normalInt & 0x0fe00000u) << 3); } /*! @@ -148,10 +143,8 @@ CPP_UTILITIES_EXPORT constexpr uint32 toSynchsafeInt(uint32 normalInt) */ CPP_UTILITIES_EXPORT constexpr uint32 toNormalInt(uint32 synchsafeInt) { - return ((synchsafeInt & 0x0000007fu) ) - | ((synchsafeInt & 0x00007f00u) >> 1) - | ((synchsafeInt & 0x007f0000u) >> 2) - | ((synchsafeInt & 0x7f000000u) >> 3); + return ((synchsafeInt & 0x0000007fu)) | ((synchsafeInt & 0x00007f00u) >> 1) | ((synchsafeInt & 0x007f0000u) >> 2) + | ((synchsafeInt & 0x7f000000u) >> 3); } /*! @@ -167,10 +160,7 @@ CPP_UTILITIES_EXPORT constexpr uint16 swapOrder(uint16 value) */ CPP_UTILITIES_EXPORT constexpr uint32 swapOrder(uint32 value) { - return (value >> 24) - | ((value & 0x00FF0000) >> 8) - | ((value & 0x0000FF00) << 8) - | (value << 24); + return (value >> 24) | ((value & 0x00FF0000) >> 8) | ((value & 0x0000FF00) << 8) | (value << 24); } /*! @@ -178,16 +168,10 @@ CPP_UTILITIES_EXPORT constexpr uint32 swapOrder(uint32 value) */ CPP_UTILITIES_EXPORT constexpr uint64 swapOrder(uint64 value) { - return(value >> (7 * 8)) - | ((value & 0x00FF000000000000) >> (5 * 8)) - | ((value & 0x0000FF0000000000) >> (3 * 8)) - | ((value & 0x000000FF00000000) >> (1 * 8)) - | ((value & 0x00000000FF000000) << (1 * 8)) - | ((value & 0x0000000000FF0000) << (3 * 8)) - | ((value & 0x000000000000FF00) << (5 * 8)) - | ((value) << (7 * 8)); + return (value >> (7 * 8)) | ((value & 0x00FF000000000000) >> (5 * 8)) | ((value & 0x0000FF0000000000) >> (3 * 8)) + | ((value & 0x000000FF00000000) >> (1 * 8)) | ((value & 0x00000000FF000000) << (1 * 8)) | ((value & 0x0000000000FF0000) << (3 * 8)) + | ((value & 0x000000000000FF00) << (5 * 8)) | ((value) << (7 * 8)); } - } #endif // CONVERSION_UTILITIES_BINARY_CONVERSION_H diff --git a/conversion/binaryconversionprivate.h b/conversion/binaryconversionprivate.h index f66567e..f2816ae 100644 --- a/conversion/binaryconversionprivate.h +++ b/conversion/binaryconversionprivate.h @@ -1,5 +1,5 @@ #ifndef CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL -# error "Do not include binaryconversionprivate.h directly." +#error "Do not include binaryconversionprivate.h directly." #else #include "./types.h" @@ -12,11 +12,9 @@ CPP_UTILITIES_EXPORT inline int16 toInt16(const char *value) { #if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 - return (static_cast(value[0]) << 8 & 0xFF00) - | (static_cast(value[1]) & 0x00FF); + return (static_cast(value[0]) << 8 & 0xFF00) | (static_cast(value[1]) & 0x00FF); #else - return (static_cast(value[1]) << 8 & 0xFF00) - | (static_cast(value[0]) & 0x00FF); + return (static_cast(value[1]) << 8 & 0xFF00) | (static_cast(value[0]) & 0x00FF); #endif } @@ -26,11 +24,9 @@ CPP_UTILITIES_EXPORT inline int16 toInt16(const char *value) CPP_UTILITIES_EXPORT inline uint16 toUInt16(const char *value) { #if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 - return (static_cast(value[0]) << 8 & 0xFF00) - | (static_cast(value[1]) & 0x00FF); + return (static_cast(value[0]) << 8 & 0xFF00) | (static_cast(value[1]) & 0x00FF); #else - return (static_cast(value[1]) << 8 & 0xFF00) - | (static_cast(value[0]) & 0x00FF); + return (static_cast(value[1]) << 8 & 0xFF00) | (static_cast(value[0]) & 0x00FF); #endif } @@ -40,15 +36,11 @@ CPP_UTILITIES_EXPORT inline uint16 toUInt16(const char *value) CPP_UTILITIES_EXPORT inline int32 toInt32(const char *value) { #if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 - return (static_cast(value[0]) << 24 & 0xFF000000) - | (static_cast(value[1]) << 16 & 0x00FF0000) - | (static_cast(value[2]) << 8 & 0x0000FF00) - | (static_cast(value[3]) & 0x000000FF); + return (static_cast(value[0]) << 24 & 0xFF000000) | (static_cast(value[1]) << 16 & 0x00FF0000) + | (static_cast(value[2]) << 8 & 0x0000FF00) | (static_cast(value[3]) & 0x000000FF); #else - return (static_cast(value[3]) << 24 & 0xFF000000) - | (static_cast(value[2]) << 16 & 0x00FF0000) - | (static_cast(value[1]) << 8 & 0x0000FF00) - | (static_cast(value[0]) & 0x000000FF); + return (static_cast(value[3]) << 24 & 0xFF000000) | (static_cast(value[2]) << 16 & 0x00FF0000) + | (static_cast(value[1]) << 8 & 0x0000FF00) | (static_cast(value[0]) & 0x000000FF); #endif } @@ -58,13 +50,11 @@ CPP_UTILITIES_EXPORT inline int32 toInt32(const char *value) CPP_UTILITIES_EXPORT inline uint32 toUInt24(const char *value) { #if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 - return (static_cast(value[0]) << 16 & 0x00FF0000) - | (static_cast(value[1]) << 8 & 0x0000FF00) - | (static_cast(value[2]) & 0x000000FF); + return (static_cast(value[0]) << 16 & 0x00FF0000) | (static_cast(value[1]) << 8 & 0x0000FF00) + | (static_cast(value[2]) & 0x000000FF); #else - return (static_cast(value[2]) << 16 & 0x00FF0000) - | (static_cast(value[1]) << 8 & 0x0000FF00) - | (static_cast(value[0]) & 0x000000FF); + return (static_cast(value[2]) << 16 & 0x00FF0000) | (static_cast(value[1]) << 8 & 0x0000FF00) + | (static_cast(value[0]) & 0x000000FF); #endif } @@ -74,15 +64,11 @@ CPP_UTILITIES_EXPORT inline uint32 toUInt24(const char *value) CPP_UTILITIES_EXPORT inline uint32 toUInt32(const char *value) { #if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 - return (static_cast(value[0]) << 24 & 0xFF000000) - | (static_cast(value[1]) << 16 & 0x00FF0000) - | (static_cast(value[2]) << 8 & 0x0000FF00) - | (static_cast(value[3]) & 0x000000FF); + return (static_cast(value[0]) << 24 & 0xFF000000) | (static_cast(value[1]) << 16 & 0x00FF0000) + | (static_cast(value[2]) << 8 & 0x0000FF00) | (static_cast(value[3]) & 0x000000FF); #else - return (static_cast(value[3]) << 24 & 0xFF000000) - | (static_cast(value[2]) << 16 & 0x00FF0000) - | (static_cast(value[1]) << 8 & 0x0000FF00) - | (static_cast(value[0]) & 0x000000FF); + return (static_cast(value[3]) << 24 & 0xFF000000) | (static_cast(value[2]) << 16 & 0x00FF0000) + | (static_cast(value[1]) << 8 & 0x0000FF00) | (static_cast(value[0]) & 0x000000FF); #endif } @@ -92,23 +78,15 @@ CPP_UTILITIES_EXPORT inline uint32 toUInt32(const char *value) CPP_UTILITIES_EXPORT inline int64 toInt64(const char *value) { #if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 - return (static_cast(value[0]) << 56 & 0xFF00000000000000) - | (static_cast(value[1]) << 48 & 0x00FF000000000000) - | (static_cast(value[2]) << 40 & 0x0000FF0000000000) - | (static_cast(value[3]) << 32 & 0x000000FF00000000) - | (static_cast(value[4]) << 24 & 0x00000000FF000000) - | (static_cast(value[5]) << 16 & 0x0000000000FF0000) - | (static_cast(value[6]) << 8 & 0x000000000000FF00) - | (static_cast(value[7]) & 0x00000000000000FF); + return (static_cast(value[0]) << 56 & 0xFF00000000000000) | (static_cast(value[1]) << 48 & 0x00FF000000000000) + | (static_cast(value[2]) << 40 & 0x0000FF0000000000) | (static_cast(value[3]) << 32 & 0x000000FF00000000) + | (static_cast(value[4]) << 24 & 0x00000000FF000000) | (static_cast(value[5]) << 16 & 0x0000000000FF0000) + | (static_cast(value[6]) << 8 & 0x000000000000FF00) | (static_cast(value[7]) & 0x00000000000000FF); #else - return (static_cast(value[7]) << 56 & 0xFF00000000000000) - | (static_cast(value[6]) << 48 & 0x00FF000000000000) - | (static_cast(value[5]) << 40 & 0x0000FF0000000000) - | (static_cast(value[4]) << 32 & 0x000000FF00000000) - | (static_cast(value[3]) << 24 & 0x00000000FF000000) - | (static_cast(value[2]) << 16 & 0x0000000000FF0000) - | (static_cast(value[1]) << 8 & 0x000000000000FF00) - | (static_cast(value[0]) & 0x00000000000000FF); + return (static_cast(value[7]) << 56 & 0xFF00000000000000) | (static_cast(value[6]) << 48 & 0x00FF000000000000) + | (static_cast(value[5]) << 40 & 0x0000FF0000000000) | (static_cast(value[4]) << 32 & 0x000000FF00000000) + | (static_cast(value[3]) << 24 & 0x00000000FF000000) | (static_cast(value[2]) << 16 & 0x0000000000FF0000) + | (static_cast(value[1]) << 8 & 0x000000000000FF00) | (static_cast(value[0]) & 0x00000000000000FF); #endif } @@ -118,23 +96,15 @@ CPP_UTILITIES_EXPORT inline int64 toInt64(const char *value) CPP_UTILITIES_EXPORT inline uint64 toUInt64(const char *value) { #if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 - return (static_cast(value[0]) << 56 & 0xFF00000000000000) - | (static_cast(value[1]) << 48 & 0x00FF000000000000) - | (static_cast(value[2]) << 40 & 0x0000FF0000000000) - | (static_cast(value[3]) << 32 & 0x000000FF00000000) - | (static_cast(value[4]) << 24 & 0x00000000FF000000) - | (static_cast(value[5]) << 16 & 0x0000000000FF0000) - | (static_cast(value[6]) << 8 & 0x000000000000FF00) - | (static_cast(value[7]) & 0x00000000000000FF); + return (static_cast(value[0]) << 56 & 0xFF00000000000000) | (static_cast(value[1]) << 48 & 0x00FF000000000000) + | (static_cast(value[2]) << 40 & 0x0000FF0000000000) | (static_cast(value[3]) << 32 & 0x000000FF00000000) + | (static_cast(value[4]) << 24 & 0x00000000FF000000) | (static_cast(value[5]) << 16 & 0x0000000000FF0000) + | (static_cast(value[6]) << 8 & 0x000000000000FF00) | (static_cast(value[7]) & 0x00000000000000FF); #else - return (static_cast(value[7]) << 56 & 0xFF00000000000000) - | (static_cast(value[6]) << 48 & 0x00FF000000000000) - | (static_cast(value[5]) << 40 & 0x0000FF0000000000) - | (static_cast(value[4]) << 32 & 0x000000FF00000000) - | (static_cast(value[3]) << 24 & 0x00000000FF000000) - | (static_cast(value[2]) << 16 & 0x0000000000FF0000) - | (static_cast(value[1]) << 8 & 0x000000000000FF00) - | (static_cast(value[0]) & 0x00000000000000FF); + return (static_cast(value[7]) << 56 & 0xFF00000000000000) | (static_cast(value[6]) << 48 & 0x00FF000000000000) + | (static_cast(value[5]) << 40 & 0x0000FF0000000000) | (static_cast(value[4]) << 32 & 0x000000FF00000000) + | (static_cast(value[3]) << 24 & 0x00000000FF000000) | (static_cast(value[2]) << 16 & 0x0000000000FF0000) + | (static_cast(value[1]) << 8 & 0x000000000000FF00) | (static_cast(value[0]) & 0x00000000000000FF); #endif } @@ -162,7 +132,7 @@ CPP_UTILITIES_EXPORT inline float64 toFloat64(const char *value) #if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 int64 val = toInt64(value); char *c = reinterpret_cast(&val); - return *reinterpret_cast(c); + return *reinterpret_cast(c); #else int64 val = toInt64(value); char *c = reinterpret_cast(&val); @@ -177,10 +147,10 @@ CPP_UTILITIES_EXPORT inline void getBytes(int16 value, char *outputbuffer) { #if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 outputbuffer[0] = static_cast((value >> 8) & 0xFF); - outputbuffer[1] = static_cast((value ) & 0xFF); + outputbuffer[1] = static_cast((value)&0xFF); #else outputbuffer[1] = static_cast((value >> 8) & 0xFF); - outputbuffer[0] = static_cast((value ) & 0xFF); + outputbuffer[0] = static_cast((value)&0xFF); #endif } @@ -191,10 +161,10 @@ CPP_UTILITIES_EXPORT inline void getBytes(uint16 value, char *outputbuffer) { #if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 outputbuffer[0] = static_cast((value >> 8) & 0xFF); - outputbuffer[1] = static_cast((value ) & 0xFF); + outputbuffer[1] = static_cast((value)&0xFF); #else outputbuffer[1] = static_cast((value >> 8) & 0xFF); - outputbuffer[0] = static_cast((value ) & 0xFF); + outputbuffer[0] = static_cast((value)&0xFF); #endif } @@ -206,12 +176,12 @@ CPP_UTILITIES_EXPORT inline void getBytes24(uint32 value, char *outputbuffer) { #if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 outputbuffer[0] = static_cast((value >> 16) & 0xFF); - outputbuffer[1] = static_cast((value >> 8) & 0xFF); - outputbuffer[2] = static_cast((value ) & 0xFF); + outputbuffer[1] = static_cast((value >> 8) & 0xFF); + outputbuffer[2] = static_cast((value)&0xFF); #else outputbuffer[2] = static_cast((value >> 16) & 0xFF); - outputbuffer[1] = static_cast((value >> 8) & 0xFF); - outputbuffer[0] = static_cast((value ) & 0xFF); + outputbuffer[1] = static_cast((value >> 8) & 0xFF); + outputbuffer[0] = static_cast((value)&0xFF); #endif } @@ -223,13 +193,13 @@ CPP_UTILITIES_EXPORT inline void getBytes(int32 value, char *outputbuffer) #if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 outputbuffer[0] = static_cast((value >> 24) & 0xFF); outputbuffer[1] = static_cast((value >> 16) & 0xFF); - outputbuffer[2] = static_cast((value >> 8) & 0xFF); - outputbuffer[3] = static_cast((value ) & 0xFF); + outputbuffer[2] = static_cast((value >> 8) & 0xFF); + outputbuffer[3] = static_cast((value)&0xFF); #else outputbuffer[3] = static_cast((value >> 24) & 0xFF); outputbuffer[2] = static_cast((value >> 16) & 0xFF); - outputbuffer[1] = static_cast((value >> 8) & 0xFF); - outputbuffer[0] = static_cast((value ) & 0xFF); + outputbuffer[1] = static_cast((value >> 8) & 0xFF); + outputbuffer[0] = static_cast((value)&0xFF); #endif } @@ -241,13 +211,13 @@ CPP_UTILITIES_EXPORT inline void getBytes(uint32 value, char *outputbuffer) #if CONVERSION_UTILITIES_BINARY_CONVERSION_INTERNAL == 0 outputbuffer[0] = static_cast((value >> 24) & 0xFF); outputbuffer[1] = static_cast((value >> 16) & 0xFF); - outputbuffer[2] = static_cast((value >> 8) & 0xFF); - outputbuffer[3] = static_cast((value ) & 0xFF); + outputbuffer[2] = static_cast((value >> 8) & 0xFF); + outputbuffer[3] = static_cast((value)&0xFF); #else outputbuffer[3] = static_cast((value >> 24) & 0xFF); outputbuffer[2] = static_cast((value >> 16) & 0xFF); - outputbuffer[1] = static_cast((value >> 8) & 0xFF); - outputbuffer[0] = static_cast((value ) & 0xFF); + outputbuffer[1] = static_cast((value >> 8) & 0xFF); + outputbuffer[0] = static_cast((value)&0xFF); #endif } @@ -263,8 +233,8 @@ CPP_UTILITIES_EXPORT inline void getBytes(int64 value, char *outputbuffer) outputbuffer[3] = static_cast((value >> 32) & 0xFF); outputbuffer[4] = static_cast((value >> 24) & 0xFF); outputbuffer[5] = static_cast((value >> 16) & 0xFF); - outputbuffer[6] = static_cast((value >> 8) & 0xFF); - outputbuffer[7] = static_cast((value ) & 0xFF); + outputbuffer[6] = static_cast((value >> 8) & 0xFF); + outputbuffer[7] = static_cast((value)&0xFF); #else outputbuffer[7] = static_cast((value >> 56) & 0xFF); outputbuffer[6] = static_cast((value >> 48) & 0xFF); @@ -272,8 +242,8 @@ CPP_UTILITIES_EXPORT inline void getBytes(int64 value, char *outputbuffer) outputbuffer[4] = static_cast((value >> 32) & 0xFF); outputbuffer[3] = static_cast((value >> 24) & 0xFF); outputbuffer[2] = static_cast((value >> 16) & 0xFF); - outputbuffer[1] = static_cast((value >> 8) & 0xFF); - outputbuffer[0] = static_cast((value ) & 0xFF); + outputbuffer[1] = static_cast((value >> 8) & 0xFF); + outputbuffer[0] = static_cast((value)&0xFF); #endif } @@ -289,8 +259,8 @@ CPP_UTILITIES_EXPORT inline void getBytes(uint64 value, char *outputbuffer) outputbuffer[3] = static_cast((value >> 32) & 0xFF); outputbuffer[4] = static_cast((value >> 24) & 0xFF); outputbuffer[5] = static_cast((value >> 16) & 0xFF); - outputbuffer[6] = static_cast((value >> 8) & 0xFF); - outputbuffer[7] = static_cast((value ) & 0xFF); + outputbuffer[6] = static_cast((value >> 8) & 0xFF); + outputbuffer[7] = static_cast((value)&0xFF); #else outputbuffer[7] = static_cast((value >> 56) & 0xFF); outputbuffer[6] = static_cast((value >> 48) & 0xFF); @@ -298,8 +268,8 @@ CPP_UTILITIES_EXPORT inline void getBytes(uint64 value, char *outputbuffer) outputbuffer[4] = static_cast((value >> 32) & 0xFF); outputbuffer[3] = static_cast((value >> 24) & 0xFF); outputbuffer[2] = static_cast((value >> 16) & 0xFF); - outputbuffer[1] = static_cast((value >> 8) & 0xFF); - outputbuffer[0] = static_cast((value ) & 0xFF); + outputbuffer[1] = static_cast((value >> 8) & 0xFF); + outputbuffer[0] = static_cast((value)&0xFF); #endif } diff --git a/conversion/conversionexception.cpp b/conversion/conversionexception.cpp index 9b47cd1..591758d 100644 --- a/conversion/conversionexception.cpp +++ b/conversion/conversionexception.cpp @@ -11,22 +11,22 @@ namespace ConversionUtilities { /*! * \brief Constructs a new ConversionException. */ -ConversionException::ConversionException() USE_NOTHROW : - runtime_error("unable to convert") -{} +ConversionException::ConversionException() USE_NOTHROW : runtime_error("unable to convert") +{ +} /*! * \brief Constructs a new ConversionException. \a what is a std::string * describing the cause of the ConversionException. */ -ConversionException::ConversionException(const std::string &what) USE_NOTHROW : - runtime_error(what) -{} +ConversionException::ConversionException(const std::string &what) USE_NOTHROW : runtime_error(what) +{ +} /*! * \brief Destroys the ConversionException. */ ConversionException::~ConversionException() USE_NOTHROW -{} - +{ +} } diff --git a/conversion/conversionexception.h b/conversion/conversionexception.h index 7991daa..5c7f0d2 100644 --- a/conversion/conversionexception.h +++ b/conversion/conversionexception.h @@ -8,14 +8,12 @@ namespace ConversionUtilities { -class CPP_UTILITIES_EXPORT ConversionException : public std::runtime_error -{ +class CPP_UTILITIES_EXPORT ConversionException : public std::runtime_error { public: ConversionException() USE_NOTHROW; ConversionException(const std::string &what) USE_NOTHROW; ~ConversionException() USE_NOTHROW; }; - } #endif // CONVERSION_UTILITIES_CONVERSIONEXCEPTION_H diff --git a/conversion/stringbuilder.h b/conversion/stringbuilder.h index 37955af..bc1ac5e 100644 --- a/conversion/stringbuilder.h +++ b/conversion/stringbuilder.h @@ -1,96 +1,97 @@ #ifndef CONVERSION_UTILITIES_STRINGBUILDER_H #define CONVERSION_UTILITIES_STRINGBUILDER_H -#include "./stringconversion.h" #include "../misc/traits.h" +#include "./stringconversion.h" #include #include -namespace ConversionUtilities -{ +namespace ConversionUtilities { /// \cond namespace Helper { -template >...> -std::size_t computeTupleElementSize(const StringType *str) +template >...> std::size_t computeTupleElementSize(const StringType *str) { return str->size(); } -template >...> -std::size_t computeTupleElementSize(const StringType &str) +template >...> std::size_t computeTupleElementSize(const StringType &str) { return str.size(); } -template >...> +template >...> std::size_t computeTupleElementSize(const CharType *str) { return std::char_traits::length(str); } -template >...> +template >...> constexpr std::size_t computeTupleElementSize(CharType) { return 1; } -template >, std::is_integral, std::is_unsigned >...> +template >, + std::is_integral, std::is_unsigned >...> std::size_t computeTupleElementSize(IntegralType number, typename StringType::value_type base = 10) { std::size_t size = 0; - for(auto n = number; n; n /= base, ++size); + for (auto n = number; n; n /= base, ++size) + ; return size; } -template >, std::is_integral, std::is_signed >...> +template >, + std::is_integral, std::is_signed >...> std::size_t computeTupleElementSize(IntegralType number, typename StringType::value_type base = 10) { std::size_t size = number < 0 ? 1 : 0; - for(auto n = number; n; n /= base, ++size); + for (auto n = number; n; n /= base, ++size) + ; return size; } -template >...> -void append(StringType &target, const StringType *str) +template >...> void append(StringType &target, const StringType *str) { target.append(*str); } -template >...> -void append(StringType &target, const StringType &str) +template >...> void append(StringType &target, const StringType &str) { target.append(str); } -template >...> +template >...> void append(StringType &target, const CharType *str) { target.append(str); } -template >...> +template >...> void append(StringType &target, CharType c) { target += c; } -template >, std::is_integral, std::is_unsigned >...> +template >, + std::is_integral, std::is_unsigned >...> void append(StringType &target, IntegralType number, typename StringType::value_type base = 10) { const auto start = target.begin() + target.size(); do { target.insert(start, digitToChar(number % base)); number /= base; - } while(number); + } while (number); } -template >, std::is_integral, std::is_signed >...> +template >, + std::is_integral, std::is_signed >...> void append(StringType &target, IntegralType number, typename StringType::value_type base = 10) { - if(number < 0) { + if (number < 0) { target += '-'; number = -number; } @@ -98,25 +99,23 @@ void append(StringType &target, IntegralType number, typename StringType::value_ do { target.insert(start, digitToChar(number % base)); number /= base; - } while(number); + } while (number); } -template -struct TupleToString { +template struct TupleToString { static std::size_t precomputeSize(const Tuple &tuple) { - return TupleToString::precomputeSize(tuple) + computeTupleElementSize(std::get(tuple)); + return TupleToString::precomputeSize(tuple) + computeTupleElementSize(std::get(tuple)); } static void append(const Tuple &tuple, StringType &str) { - TupleToString::append(tuple, str); - Helper::append(str, std::get(tuple)); + TupleToString::append(tuple, str); + Helper::append(str, std::get(tuple)); } }; -template -struct TupleToString { +template struct TupleToString { static std::size_t precomputeSize(const Tuple &tuple) { return computeTupleElementSize(std::get<0>(tuple)); @@ -127,15 +126,13 @@ struct TupleToString { Helper::append(str, std::get<0>(tuple)); } }; - } /// \endcond /*! * \brief Concatenates all strings hold by the specified \a tuple. */ -template -StringType tupleToString(const std::tuple &tuple) +template StringType tupleToString(const std::tuple &tuple) { StringType res; res.reserve(Helper::TupleToString::precomputeSize(tuple)); @@ -143,8 +140,7 @@ StringType tupleToString(const std::tuple &tuple) return res; } -template -constexpr StringType argsToString(Args&&... args) +template constexpr StringType argsToString(Args &&... args) { return tupleToString(std::make_tuple(args...)); } @@ -152,8 +148,7 @@ constexpr StringType argsToString(Args&&... args) /*! * \brief Allows construction of string-tuples via %-operator, eg. string1 % "string2" % string3. */ -template -constexpr auto operator %(const Tuple &lhs, const std::string &rhs) -> decltype(std::tuple_cat(lhs, std::make_tuple(&rhs))) +template constexpr auto operator%(const Tuple &lhs, const std::string &rhs) -> decltype(std::tuple_cat(lhs, std::make_tuple(&rhs))) { return std::tuple_cat(lhs, std::make_tuple(&rhs)); } @@ -161,8 +156,7 @@ constexpr auto operator %(const Tuple &lhs, const std::string &rhs) -> decltype( /*! * \brief Allows construction of string-tuples via %-operator, eg. string1 % "string2" % string3. */ -template -constexpr auto operator %(const Tuple &lhs, const char *rhs) -> decltype(std::tuple_cat(lhs, std::make_tuple(rhs))) +template constexpr auto operator%(const Tuple &lhs, const char *rhs) -> decltype(std::tuple_cat(lhs, std::make_tuple(rhs))) { return std::tuple_cat(lhs, std::make_tuple(rhs)); } @@ -170,8 +164,8 @@ constexpr auto operator %(const Tuple &lhs, const char *rhs) -> decltype(std::tu /*! * \brief Allows construction of string-tuples via %-operator, eg. string1 % "string2" % string3. */ -template >...> -constexpr auto operator %(const Tuple &lhs, IntegralType rhs) -> decltype(std::tuple_cat(lhs, std::make_tuple(rhs))) +template >...> +constexpr auto operator%(const Tuple &lhs, IntegralType rhs) -> decltype(std::tuple_cat(lhs, std::make_tuple(rhs))) { return std::tuple_cat(lhs, std::make_tuple(rhs)); } @@ -179,7 +173,7 @@ constexpr auto operator %(const Tuple &lhs, IntegralType rhs) -> decltype(std::t /*! * \brief Allows construction of string-tuples via %-operator, eg. string1 % "string2" % string3. */ -constexpr auto operator %(const std::string &lhs, const std::string &rhs) -> decltype(std::make_tuple(&lhs, &rhs)) +constexpr auto operator%(const std::string &lhs, const std::string &rhs) -> decltype(std::make_tuple(&lhs, &rhs)) { return std::make_tuple(&lhs, &rhs); } @@ -187,7 +181,7 @@ constexpr auto operator %(const std::string &lhs, const std::string &rhs) -> dec /*! * \brief Allows construction of string-tuples via %-operator, eg. string1 % "string2" % string3. */ -constexpr auto operator %(const char *lhs, const std::string &rhs) -> decltype(std::make_tuple(lhs, &rhs)) +constexpr auto operator%(const char *lhs, const std::string &rhs) -> decltype(std::make_tuple(lhs, &rhs)) { return std::make_tuple(lhs, &rhs); } @@ -195,7 +189,7 @@ constexpr auto operator %(const char *lhs, const std::string &rhs) -> decltype(s /*! * \brief Allows construction of string-tuples via %-operator, eg. string1 % "string2" % string3. */ -constexpr auto operator %(const std::string &lhs, const char *rhs) -> decltype(std::make_tuple(&lhs, rhs)) +constexpr auto operator%(const std::string &lhs, const char *rhs) -> decltype(std::make_tuple(&lhs, rhs)) { return std::make_tuple(&lhs, rhs); } @@ -203,7 +197,7 @@ constexpr auto operator %(const std::string &lhs, const char *rhs) -> decltype(s /*! * \brief Allows construction of string-tuples via %-operator, eg. string1 % "string2" % string3. */ -constexpr auto operator %(const std::string &lhs, char rhs) -> decltype(std::make_tuple(&lhs, rhs)) +constexpr auto operator%(const std::string &lhs, char rhs) -> decltype(std::make_tuple(&lhs, rhs)) { return std::make_tuple(&lhs, rhs); } @@ -211,7 +205,7 @@ constexpr auto operator %(const std::string &lhs, char rhs) -> decltype(std::mak /*! * \brief Allows construction of string-tuples via %-operator, eg. string1 % "string2" % string3. */ -constexpr auto operator %(char lhs, const std::string &rhs) -> decltype(std::make_tuple(lhs, &rhs)) +constexpr auto operator%(char lhs, const std::string &rhs) -> decltype(std::make_tuple(lhs, &rhs)) { return std::make_tuple(lhs, &rhs); } @@ -225,8 +219,8 @@ constexpr auto operator %(char lhs, const std::string &rhs) -> decltype(std::mak * printVelocity("velocity: " % numberToString(velocityExample) % " km/h (" % numberToString(velocityExample / 3.6) + " m/s)")); * ``` */ -template >...> -inline std::string operator +(const Tuple &lhs, const std::string &rhs) +template >...> +inline std::string operator+(const Tuple &lhs, const std::string &rhs) { return tupleToString(std::tuple_cat(lhs, std::make_tuple(&rhs))); } @@ -240,8 +234,8 @@ inline std::string operator +(const Tuple &lhs, const std::string &rhs) * printVelocity("velocity: " % numberToString(velocityExample) % " km/h (" % numberToString(velocityExample / 3.6) + " m/s)")); * ``` */ -template >...> -inline std::string operator +(const Tuple &lhs, const char *rhs) +template >...> +inline std::string operator+(const Tuple &lhs, const char *rhs) { return tupleToString(std::tuple_cat(lhs, std::make_tuple(rhs))); } @@ -255,12 +249,11 @@ inline std::string operator +(const Tuple &lhs, const char *rhs) * printVelocity("velocity: " % numberToString(velocityExample) % " km/h (" % numberToString(velocityExample / 3.6) + " m/s)")); * ``` */ -template, std::is_integral >...> -inline std::string operator +(const Tuple &lhs, IntegralType rhs) +template , std::is_integral >...> +inline std::string operator+(const Tuple &lhs, IntegralType rhs) { return tupleToString(std::tuple_cat(lhs, std::make_tuple(rhs))); } - } #endif // CONVERSION_UTILITIES_STRINGBUILDER_H diff --git a/conversion/stringconversion.cpp b/conversion/stringconversion.cpp index d460623..618994b 100644 --- a/conversion/stringconversion.cpp +++ b/conversion/stringconversion.cpp @@ -1,12 +1,12 @@ #include "./stringconversion.h" +#include +#include #include #include -#include -#include -#include #include +#include using namespace std; @@ -17,38 +17,54 @@ using namespace std; * binaryconversion.h declares functions which convert base data types to an array of bytes and vice versa. * stringconversion.h declares different functions around string conversion such as converting a number to a string and vice versa. */ -namespace ConversionUtilities -{ +namespace ConversionUtilities { /// \cond -struct Keep { size_t operator()(size_t value) { return value; } }; -struct Double { size_t operator()(size_t value) { return value + value; } }; -struct Half { size_t operator()(size_t value) { return value / 2; } }; +struct Keep { + size_t operator()(size_t value) + { + return value; + } +}; +struct Double { + size_t operator()(size_t value) + { + return value + value; + } +}; +struct Half { + size_t operator()(size_t value) + { + return value / 2; + } +}; struct Factor { - Factor(float factor) : factor(factor) {}; - size_t operator()(size_t value) { return value * factor; } + Factor(float factor) + : factor(factor){}; + size_t operator()(size_t value) + { + return value * factor; + } float factor; }; -template -class ConversionDescriptor -{ +template class ConversionDescriptor { public: - ConversionDescriptor(const char *fromCharset, const char *toCharset) : - m_ptr(iconv_open(toCharset, fromCharset)), - m_outputSizeHint(OutputSizeHint()) + ConversionDescriptor(const char *fromCharset, const char *toCharset) + : m_ptr(iconv_open(toCharset, fromCharset)) + , m_outputSizeHint(OutputSizeHint()) { - if(m_ptr == reinterpret_cast(-1)) { + if (m_ptr == reinterpret_cast(-1)) { throw ConversionException("Unable to allocate descriptor for character set conversion."); } } - ConversionDescriptor(const char *fromCharset, const char *toCharset, OutputSizeHint outputSizeHint) : - m_ptr(iconv_open(toCharset, fromCharset)), - m_outputSizeHint(outputSizeHint) + ConversionDescriptor(const char *fromCharset, const char *toCharset, OutputSizeHint outputSizeHint) + : m_ptr(iconv_open(toCharset, fromCharset)) + , m_outputSizeHint(outputSizeHint) { - if(m_ptr == reinterpret_cast(-1)) { + if (m_ptr == reinterpret_cast(-1)) { throw ConversionException("Unable to allocate descriptor for character set conversion."); } } @@ -69,14 +85,14 @@ public: size_t bytesWritten; char *currentOutputOffset = outputBuffer; - for(; ; currentOutputOffset = outputBuffer + bytesWritten) { + for (;; currentOutputOffset = outputBuffer + bytesWritten) { bytesWritten = iconv(m_ptr, const_cast(&inputBuffer), &inputBytesLeft, ¤tOutputOffset, &outputBytesLeft); - if(bytesWritten == static_cast(-1)) { - if(errno == EINVAL) { + if (bytesWritten == static_cast(-1)) { + if (errno == EINVAL) { // ignore incomplete multibyte sequence in the input bytesWritten = currentOutputOffset - outputBuffer; break; - } else if(errno == E2BIG) { + } else if (errno == E2BIG) { // output buffer has no more room for next converted character bytesWritten = currentOutputOffset - outputBuffer; outputBytesLeft = (outputSize += m_outputSizeHint(inputBytesLeft)) - bytesWritten; @@ -110,7 +126,8 @@ private: * to reduce buffer reallocations during the conversion (eg. for the conversion from Latin-1 to UTF-16 * the factor would be 2, for the conversion from UTF-16 to Latin-1 the factor would be 0.5). */ -StringData convertString(const char *fromCharset, const char *toCharset, const char *inputBuffer, std::size_t inputBufferSize, float outputBufferSizeFactor) +StringData convertString( + const char *fromCharset, const char *toCharset, const char *inputBuffer, std::size_t inputBufferSize, float outputBufferSizeFactor) { return ConversionDescriptor(fromCharset, toCharset, outputBufferSizeFactor).convertString(inputBuffer, inputBufferSize); } @@ -176,7 +193,7 @@ StringData convertUtf8ToLatin1(const char *inputBuffer, std::size_t inputBufferS void truncateString(string &str, char terminationChar) { string::size_type firstNullByte = str.find(terminationChar); - if(firstNullByte != string::npos) { + if (firstNullByte != string::npos) { str.resize(firstNullByte); } } @@ -202,7 +219,7 @@ string dataSizeToString(uint64 sizeInByte, bool includeByte) } else { res << (static_cast(sizeInByte) / 1099511627776.0) << " TiB"; } - if(includeByte && sizeInByte > 1024LL) { + if (includeByte && sizeInByte > 1024LL) { res << ' ' << '(' << sizeInByte << " byte)"; } return res.str(); @@ -260,16 +277,16 @@ string encodeBase64(const byte *data, uint32 dataSize) byte mod = dataSize % 3; encoded.reserve(((dataSize / 3) + (mod > 0)) * 4); uint32 temp; - for(const byte *end = --data + dataSize - mod; data != end; ) { + for (const byte *end = --data + dataSize - mod; data != end;) { temp = *++data << 16; temp |= *++data << 8; temp |= *++data; encoded.push_back(base64Chars[(temp & 0x00FC0000) >> 18]); encoded.push_back(base64Chars[(temp & 0x0003F000) >> 12]); - encoded.push_back(base64Chars[(temp & 0x00000FC0) >> 6 ]); - encoded.push_back(base64Chars[(temp & 0x0000003F) ]); + encoded.push_back(base64Chars[(temp & 0x00000FC0) >> 6]); + encoded.push_back(base64Chars[(temp & 0x0000003F)]); } - switch(mod) { + switch (mod) { case 1: temp = *++data << 16; encoded.push_back(base64Chars[(temp & 0x00FC0000) >> 18]); @@ -282,7 +299,7 @@ string encodeBase64(const byte *data, uint32 dataSize) temp |= *++data << 8; encoded.push_back(base64Chars[(temp & 0x00FC0000) >> 18]); encoded.push_back(base64Chars[(temp & 0x0003F000) >> 12]); - encoded.push_back(base64Chars[(temp & 0x00000FC0) >> 6 ]); + encoded.push_back(base64Chars[(temp & 0x00000FC0) >> 6]); encoded.push_back(base64Pad); break; } @@ -295,40 +312,40 @@ string encodeBase64(const byte *data, uint32 dataSize) */ pair, uint32> decodeBase64(const char *encodedStr, const uint32 strSize) { - if(strSize % 4) { + if (strSize % 4) { throw ConversionException("invalid size of base64"); } uint32 decodedSize = (strSize / 4) * 3; const char *const end = encodedStr + strSize; - if(strSize) { - if(*(end - 1) == base64Pad) { + if (strSize) { + if (*(end - 1) == base64Pad) { --decodedSize; } - if(*(end - 2) == base64Pad) { + if (*(end - 2) == base64Pad) { --decodedSize; } } auto buffer = make_unique(decodedSize); auto *iter = buffer.get() - 1; - while(encodedStr < end) { + while (encodedStr < end) { uint32 temp = 0; - for(byte quantumPos = 0; quantumPos < 4; ++quantumPos, ++encodedStr) { + for (byte quantumPos = 0; quantumPos < 4; ++quantumPos, ++encodedStr) { temp <<= 6; - if(*encodedStr >= 'A' && *encodedStr <= 'Z') { + if (*encodedStr >= 'A' && *encodedStr <= 'Z') { temp |= *encodedStr - 'A'; - } else if(*encodedStr >= 'a' && *encodedStr <= 'z') { + } else if (*encodedStr >= 'a' && *encodedStr <= 'z') { temp |= *encodedStr - 'a' + 26; - } else if(*encodedStr >= '0' && *encodedStr <= '9') { + } else if (*encodedStr >= '0' && *encodedStr <= '9') { temp |= *encodedStr - '0' + 2 * 26; - } else if(*encodedStr == '+') { + } else if (*encodedStr == '+') { temp |= 2 * 26 + 10; - } else if(*encodedStr == '/') { + } else if (*encodedStr == '/') { temp |= 2 * 26 + 10 + 1; - } else if(*encodedStr == base64Pad) { - switch(end - encodedStr) { + } else if (*encodedStr == base64Pad) { + switch (end - encodedStr) { case 1: *++iter = (temp >> 16) & 0xFF; - *++iter = (temp >> 8) & 0xFF; + *++iter = (temp >> 8) & 0xFF; return make_pair(move(buffer), decodedSize); case 2: *++iter = (temp >> 10) & 0xFF; @@ -341,10 +358,9 @@ pair, uint32> decodeBase64(const char *encodedStr, const uint } } *++iter = (temp >> 16) & 0xFF; - *++iter = (temp >> 8) & 0xFF; - *++iter = (temp ) & 0xFF; + *++iter = (temp >> 8) & 0xFF; + *++iter = (temp)&0xFF; } return make_pair(move(buffer), decodedSize); } - } diff --git a/conversion/stringconversion.h b/conversion/stringconversion.h index 37f1f7d..c48e74b 100644 --- a/conversion/stringconversion.h +++ b/conversion/stringconversion.h @@ -1,22 +1,21 @@ #ifndef CONVERSION_UTILITIES_STRINGCONVERSION_H #define CONVERSION_UTILITIES_STRINGCONVERSION_H -#include "./conversionexception.h" #include "./binaryconversion.h" +#include "./conversionexception.h" #include "../misc/traits.h" -#include #include -#include -#include #include +#include #include -#include #include +#include +#include +#include -namespace ConversionUtilities -{ +namespace ConversionUtilities { /*! * \brief The StringDataDeleter struct deletes the data of a StringData instance. @@ -28,7 +27,7 @@ struct CPP_UTILITIES_EXPORT StringDataDeleter { */ void operator()(char *stringData) { - std::free(stringData); + std::free(stringData); } }; @@ -38,7 +37,8 @@ struct CPP_UTILITIES_EXPORT StringDataDeleter { typedef std::pair, std::size_t> StringData; //typedef std::pair, std::size_t> StringData; // might work too -CPP_UTILITIES_EXPORT StringData convertString(const char *fromCharset, const char *toCharset, const char *inputBuffer, std::size_t inputBufferSize, float outputBufferSizeFactor = 1.0f); +CPP_UTILITIES_EXPORT StringData convertString( + const char *fromCharset, const char *toCharset, const char *inputBuffer, std::size_t inputBufferSize, float outputBufferSizeFactor = 1.0f); CPP_UTILITIES_EXPORT StringData convertUtf8ToUtf16LE(const char *inputBuffer, std::size_t inputBufferSize); CPP_UTILITIES_EXPORT StringData convertUtf16LEToUtf8(const char *inputBuffer, std::size_t inputBufferSize); CPP_UTILITIES_EXPORT StringData convertUtf8ToUtf16BE(const char *inputBuffer, std::size_t inputBufferSize); @@ -62,23 +62,26 @@ CPP_UTILITIES_EXPORT void truncateString(std::string &str, char terminationChar * \returns Returns the joined string. */ template > -typename Container::value_type joinStrings(const Container &strings, const typename Container::value_type &delimiter = typename Container::value_type(), bool omitEmpty = false, const typename Container::value_type &leftClosure = typename Container::value_type(), const typename Container::value_type &rightClosure = typename Container::value_type()) +typename Container::value_type joinStrings(const Container &strings, + const typename Container::value_type &delimiter = typename Container::value_type(), bool omitEmpty = false, + const typename Container::value_type &leftClosure = typename Container::value_type(), + const typename Container::value_type &rightClosure = typename Container::value_type()) { typename Container::value_type res; - if(strings.size()) { + if (strings.size()) { size_t entries = 0, size = 0; - for(const auto &str : strings) { - if(!omitEmpty || !str.empty()) { + for (const auto &str : strings) { + if (!omitEmpty || !str.empty()) { size += str.size(); ++entries; } } - if(entries) { + if (entries) { size += (entries * leftClosure.size()) + (entries * rightClosure.size()) + ((entries - 1) * delimiter.size()); res.reserve(size); - for(const auto &str : strings) { - if(!omitEmpty || !str.empty()) { - if(!res.empty()) { + for (const auto &str : strings) { + if (!omitEmpty || !str.empty()) { + if (!res.empty()) { res.append(delimiter); } res.append(leftClosure); @@ -94,8 +97,7 @@ typename Container::value_type joinStrings(const Container &strings, const typen /*! * \brief Specifies the role of empty parts when splitting strings. */ -enum class EmptyPartsTreat -{ +enum class EmptyPartsTreat { Keep, /**< empty parts are kept */ Omit, /**< empty parts are omitted */ Merge /**< empty parts are omitted but cause the adjacent parts being joined using the delimiter */ @@ -111,35 +113,36 @@ enum class EmptyPartsTreat * \returns Returns the parts. */ template > -Container splitString(const typename Container::value_type &string, const typename Container::value_type &delimiter, EmptyPartsTreat emptyPartsRole = EmptyPartsTreat::Keep, int maxParts = -1) +Container splitString(const typename Container::value_type &string, const typename Container::value_type &delimiter, + EmptyPartsTreat emptyPartsRole = EmptyPartsTreat::Keep, int maxParts = -1) { --maxParts; Container res; bool merge = false; - for(typename Container::value_type::size_type i = 0, end = string.size(), delimPos; i < end; i = delimPos + delimiter.size()) { + for (typename Container::value_type::size_type i = 0, end = string.size(), delimPos; i < end; i = delimPos + delimiter.size()) { delimPos = string.find(delimiter, i); - if(!merge && maxParts >= 0 && res.size() == static_cast(maxParts)) { - if(delimPos == i && emptyPartsRole == EmptyPartsTreat::Merge) { - if(!res.empty()) { + if (!merge && maxParts >= 0 && res.size() == static_cast(maxParts)) { + if (delimPos == i && emptyPartsRole == EmptyPartsTreat::Merge) { + if (!res.empty()) { merge = true; continue; } } delimPos = Container::value_type::npos; } - if(delimPos == Container::value_type::npos) { + if (delimPos == Container::value_type::npos) { delimPos = string.size(); } - if(emptyPartsRole == EmptyPartsTreat::Keep || i != delimPos) { - if(merge) { + if (emptyPartsRole == EmptyPartsTreat::Keep || i != delimPos) { + if (merge) { res.back().append(delimiter); res.back().append(string.substr(i, delimPos - i)); merge = false; } else { res.emplace_back(string.substr(i, delimPos - i)); } - } else if(emptyPartsRole == EmptyPartsTreat::Merge) { - if(!res.empty()) { + } else if (emptyPartsRole == EmptyPartsTreat::Merge) { + if (!res.empty()) { merge = true; } } @@ -150,16 +153,15 @@ Container splitString(const typename Container::value_type &string, const typena /*! * \brief Returns whether \a str starts with \a phrase. */ -template -bool startsWith(const StringType &str, const StringType &phrase) +template bool startsWith(const StringType &str, const StringType &phrase) { - if(str.size() < phrase.size()) { + if (str.size() < phrase.size()) { return false; } - for(auto stri = str.cbegin(), strend = str.cend(), phrasei = phrase.cbegin(), phraseend = phrase.cend(); stri != strend; ++stri, ++phrasei) { - if(phrasei == phraseend) { + for (auto stri = str.cbegin(), strend = str.cend(), phrasei = phrase.cbegin(), phraseend = phrase.cend(); stri != strend; ++stri, ++phrasei) { + if (phrasei == phraseend) { return true; - } else if(*stri != *phrasei) { + } else if (*stri != *phrasei) { return false; } } @@ -169,13 +171,12 @@ bool startsWith(const StringType &str, const StringType &phrase) /*! * \brief Returns whether \a str starts with \a phrase. */ -template -bool startsWith(const StringType &str, const typename StringType::value_type *phrase) +template bool startsWith(const StringType &str, const typename StringType::value_type *phrase) { - for(auto stri = str.cbegin(), strend = str.cend(); stri != strend; ++stri, ++phrase) { - if(!*phrase) { + for (auto stri = str.cbegin(), strend = str.cend(); stri != strend; ++stri, ++phrase) { + if (!*phrase) { return true; - } else if(*stri != *phrase) { + } else if (*stri != *phrase) { return false; } } @@ -186,12 +187,11 @@ bool startsWith(const StringType &str, const typename StringType::value_type *ph * \brief Returns whether \a str contains the specified \a substrings. * \remarks The \a substrings must occur in the specified order. */ -template -bool containsSubstrings(const StringType &str, std::initializer_list substrings) +template bool containsSubstrings(const StringType &str, std::initializer_list substrings) { typename StringType::size_type currentPos = 0; - for(const auto &substr : substrings) { - if((currentPos = str.find(substr, currentPos)) == StringType::npos) { + for (const auto &substr : substrings) { + if ((currentPos = str.find(substr, currentPos)) == StringType::npos) { return false; } currentPos += substr.size(); @@ -207,8 +207,8 @@ template bool containsSubstrings(const StringType &str, std::initializer_list substrings) { typename StringType::size_type currentPos = 0; - for(const auto *substr : substrings) { - if((currentPos = str.find(substr, currentPos)) == StringType::npos) { + for (const auto *substr : substrings) { + if ((currentPos = str.find(substr, currentPos)) == StringType::npos) { return false; } currentPos += std::strlen(substr); @@ -219,10 +219,9 @@ bool containsSubstrings(const StringType &str, std::initializer_list -void findAndReplace(StringType &str, const StringType &find, const StringType &replace) +template void findAndReplace(StringType &str, const StringType &find, const StringType &replace) { - for(typename StringType::size_type i = 0; (i = str.find(find, i)) != StringType::npos; i += replace.size()) { + for (typename StringType::size_type i = 0; (i = str.find(find, i)) != StringType::npos; i += replace.size()) { str.replace(i, find.size(), replace); } } @@ -233,11 +232,10 @@ void findAndReplace(StringType &str, const StringType &find, const StringType &r * - Uses capital letters. * - Valid values for \a digit: 0 <= \a digit <= 35 */ -template -CharType digitToChar(CharType digit) +template CharType digitToChar(CharType digit) { CharType res; - if(digit <= 9) { + if (digit <= 9) { res = digit + '0'; } else { res = digit + 'A' - 10; @@ -251,17 +249,19 @@ CharType digitToChar(CharType digit) * \tparam StringType The string type (should be an instantiation of the basic_string class template). * \sa stringToNumber() */ -template , Traits::Not > >...> +template , Traits::Not > >...> StringType numberToString(IntegralType number, typename StringType::value_type base = 10) { std::size_t resSize = 0; - for(auto n = number; n; n /= base, ++resSize); + for (auto n = number; n; n /= base, ++resSize) + ; StringType res; res.reserve(resSize); do { res.insert(res.begin(), digitToChar(number % base)); number /= base; - } while(number); + } while (number); return res; } @@ -276,19 +276,20 @@ StringType numberToString(IntegralType number, typename StringType::value_type b { const bool negative = number < 0; std::size_t resSize; - if(negative) { + if (negative) { number = -number, resSize = 1; } else { resSize = 0; } - for(auto n = number; n; n /= base, ++resSize); + for (auto n = number; n; n /= base, ++resSize) + ; StringType res; res.reserve(resSize); do { res.insert(res.begin(), digitToChar(number % base)); number /= base; - } while(number); - if(negative) { + } while (number); + if (negative) { res.insert(res.begin(), '-'); } return res; @@ -314,20 +315,19 @@ StringType numberToString(FloatingType number, typename StringType::value_type b * \brief Returns number/digit of the specified \a character representation using the specified \a base. * \throws A ConversionException will be thrown if the provided \a character does not represent a valid digit for the specified \a base. */ -template -CharType charToDigit(CharType character, CharType base) +template CharType charToDigit(CharType character, CharType base) { CharType res; - if(character >= '0' && character <= '9') { + if (character >= '0' && character <= '9') { res = character - '0'; - } else if(character >= 'a' && character <= 'z') { + } else if (character >= 'a' && character <= 'z') { res = character - 'a' + 10; - } else if(character >= 'A' && character <= 'Z') { + } else if (character >= 'A' && character <= 'Z') { res = character - 'A' + 10; } else { throw ConversionException("The string is no valid number"); } - if(res >= base) { + if (res >= base) { throw ConversionException("The string is no valid number"); } return res; @@ -344,8 +344,8 @@ template ss; ss << std::setbase(base) << string; FloatingType result; - if((ss >> result) && ss.eof()) { + if ((ss >> result) && ss.eof()) { return result; } else { throw ConversionException("The string is no valid number."); @@ -417,8 +417,8 @@ template , std::is_signed >...> IntegralType stringToNumber(const CharType *string, unsigned char base = 10) { - if(!*string) { + if (!*string) { return 0; } const bool negative = (*string == '-'); - if(negative) { + if (negative) { ++string; } IntegralType result = 0; - for(; *string; ++string) { - if(*string == ' ') { + for (; *string; ++string) { + if (*string == ' ') { continue; } result *= base; @@ -464,8 +464,7 @@ IntegralType stringToNumber(const CharType *string, unsigned char base = 10) * * \tparam T The data type of the integer to be interpreted. */ -template -std::string interpretIntegerAsString(T integer, int startOffset = 0) +template std::string interpretIntegerAsString(T integer, int startOffset = 0) { char buffer[sizeof(T)]; ConversionUtilities::BE::getBytes(integer, buffer); @@ -476,7 +475,6 @@ CPP_UTILITIES_EXPORT std::string dataSizeToString(uint64 sizeInByte, bool includ CPP_UTILITIES_EXPORT std::string bitrateToString(double speedInKbitsPerSecond, bool useByteInsteadOfBits = false); CPP_UTILITIES_EXPORT std::string encodeBase64(const byte *data, uint32 dataSize); CPP_UTILITIES_EXPORT std::pair, uint32> decodeBase64(const char *encodedStr, const uint32 strSize); - } #endif // CONVERSION_UTILITIES_STRINGCONVERSION_H diff --git a/conversion/types.h b/conversion/types.h index ac62c32..ae1ef2b 100644 --- a/conversion/types.h +++ b/conversion/types.h @@ -59,7 +59,7 @@ typedef std::uintptr_t uintptr; */ typedef float float32; #else -# error "Unable to define float32!" +#error "Unable to define float32!" #endif #if __SIZEOF_DOUBLE__ == 8 @@ -68,7 +68,7 @@ typedef float float32; */ typedef double float64; #else -# error "Unable to define float64!" +#error "Unable to define float64!" #endif #endif // CONVERSION_UTILITIES_TYPES_H diff --git a/conversion/widen.h b/conversion/widen.h index 1aff6b1..8ecfd9f 100644 --- a/conversion/widen.h +++ b/conversion/widen.h @@ -3,38 +3,37 @@ #include "../global.h" -#include -#include -#include #include #include +#include +#include +#include -namespace ConversionUtilities -{ +namespace ConversionUtilities { /*! * \brief Converts a std::string to a wide string using the specified locale. * \deprecated Might be removed in future release because not used anymore. Use iconv based string converion functions instead. */ -template, class A = std::allocator > -class CPP_UTILITIES_EXPORT Widen : public std::unary_function > -{ +template , class A = std::allocator > +class CPP_UTILITIES_EXPORT Widen : public std::unary_function > { public: /*! * \brief Constructs a new instance with the specified \a locale. */ - Widen(const std::locale &locale = std::locale()) : - m_loc(locale), - m_pctype(&std::use_facet >(locale)) - {} + Widen(const std::locale &locale = std::locale()) + : m_loc(locale) + , m_pctype(&std::use_facet >(locale)) + { + } Widen(const Widen &) = delete; - Widen& operator= (const Widen &) = delete; + Widen &operator=(const Widen &) = delete; /*! * \brief Performs the conversation for the provided \a string. */ - std::basic_string operator() (const std::string &string) const + std::basic_string operator()(const std::string &string) const { typename std::basic_string::size_type srcLen = string.length(); const char *srcBeg = string.c_str(); @@ -45,9 +44,8 @@ public: private: std::locale m_loc; - const std::ctype* m_pctype; + const std::ctype *m_pctype; }; - } #endif // CONVERSION_UTILITIES_WIDEN_H diff --git a/io/ansiescapecodes.h b/io/ansiescapecodes.h index 89be599..d19bddc 100644 --- a/io/ansiescapecodes.h +++ b/io/ansiescapecodes.h @@ -11,26 +11,11 @@ */ namespace EscapeCodes { -enum class Color : char -{ - Black = '0', - Red, - Green, - Yellow, - Blue, - Purple, - Cyan, - White -}; +enum class Color : char { Black = '0', Red, Green, Yellow, Blue, Purple, Cyan, White }; -enum class ColorContext : char -{ - Foreground = '3', - Background = '4' -}; +enum class ColorContext : char { Foreground = '3', Background = '4' }; -enum class TextAttribute : char -{ +enum class TextAttribute : char { Reset = '0', Bold = '1', Dim = '2', @@ -41,33 +26,23 @@ enum class TextAttribute : char Concealed = '8' }; -enum class Direction : char -{ - Up = 'A', - Down = 'B', - Forward = 'C', - Backward = 'D' -}; +enum class Direction : char { Up = 'A', Down = 'B', Forward = 'C', Backward = 'D' }; inline void setStyle(std::ostream &stream, TextAttribute displayAttribute = TextAttribute::Reset) { stream << '\e' << '[' << static_cast(displayAttribute) << 'm'; } -inline void setStyle(std::ostream &stream, Color color, - ColorContext context = ColorContext::Foreground, - TextAttribute displayAttribute = TextAttribute::Reset) +inline void setStyle( + std::ostream &stream, Color color, ColorContext context = ColorContext::Foreground, TextAttribute displayAttribute = TextAttribute::Reset) { - stream << '\e' << '[' << static_cast(displayAttribute) << ';' - << static_cast(context) << static_cast(color) << 'm'; + stream << '\e' << '[' << static_cast(displayAttribute) << ';' << static_cast(context) << static_cast(color) << 'm'; } -inline void setStyle(std::ostream &stream, Color foregroundColor, Color backgroundColor, - TextAttribute displayAttribute = TextAttribute::Reset) +inline void setStyle(std::ostream &stream, Color foregroundColor, Color backgroundColor, TextAttribute displayAttribute = TextAttribute::Reset) { - stream << '\e' << '[' << static_cast(displayAttribute) << ';' - << static_cast(ColorContext::Foreground) << static_cast(foregroundColor) << ';' - << static_cast(ColorContext::Foreground) << static_cast(backgroundColor) << 'm'; + stream << '\e' << '[' << static_cast(displayAttribute) << ';' << static_cast(ColorContext::Foreground) + << static_cast(foregroundColor) << ';' << static_cast(ColorContext::Foreground) << static_cast(backgroundColor) << 'm'; } inline void resetStyle(std::ostream &stream) @@ -104,8 +79,6 @@ inline void eraseLine(std::ostream &stream) { stream << "\33[2K"; } - } #endif // IOUTILITIES_ANSIESCAPECODES - diff --git a/io/binaryreader.cpp b/io/binaryreader.cpp index 2576a14..e4d77bf 100644 --- a/io/binaryreader.cpp +++ b/io/binaryreader.cpp @@ -2,9 +2,9 @@ #include "../conversion/conversionexception.h" +#include #include #include -#include using namespace std; using namespace IoUtilities; @@ -25,26 +25,28 @@ using namespace ConversionUtilities; * \brief Constructs a new BinaryReader. * \param stream Specifies the stream to read from. */ -BinaryReader::BinaryReader(istream *stream) : - m_stream(stream), - m_ownership(false) -{} +BinaryReader::BinaryReader(istream *stream) + : m_stream(stream) + , m_ownership(false) +{ +} /*! * \brief Copies the specified BinaryReader. * \remarks The copy will not take ownership over the stream. */ -BinaryReader::BinaryReader(const BinaryReader &other) : - m_stream(other.m_stream), - m_ownership(false) -{} +BinaryReader::BinaryReader(const BinaryReader &other) + : m_stream(other.m_stream) + , m_ownership(false) +{ +} /*! * \brief Destroys the BinaryReader. */ BinaryReader::~BinaryReader() { - if(m_ownership) { + if (m_ownership) { delete m_stream; } } @@ -62,10 +64,10 @@ BinaryReader::~BinaryReader() */ void BinaryReader::setStream(istream *stream, bool giveOwnership) { - if(m_ownership) { + if (m_ownership) { delete m_stream; } - if(stream) { + if (stream) { m_stream = stream; m_ownership = giveOwnership; } else { @@ -102,11 +104,11 @@ string BinaryReader::readLengthPrefixedString() int prefixLength = 1; const byte beg = static_cast(m_stream->peek()); byte mask = 0x80; - while(prefixLength <= maxPrefixLength && (beg & mask) == 0) { + while (prefixLength <= maxPrefixLength && (beg & mask) == 0) { ++prefixLength; mask >>= 1; } - if(prefixLength > maxPrefixLength) { + if (prefixLength > maxPrefixLength) { throw ConversionException("Length denotation of length-prefixed string exceeds maximum."); } memset(m_buffer, 0, maxPrefixLength); @@ -154,10 +156,10 @@ string BinaryReader::readTerminatedString(byte termination) */ string BinaryReader::readTerminatedString(size_t maxBytesToRead, byte termination) { - unique_ptr buff = make_unique(maxBytesToRead); - for(char *i = buff.get(), *end = i + maxBytesToRead; i < end; ++i) { + unique_ptr buff = make_unique(maxBytesToRead); + for (char *i = buff.get(), *end = i + maxBytesToRead; i < end; ++i) { m_stream->get(*i); - if(*(reinterpret_cast(i)) == termination) { + if (*(reinterpret_cast(i)) == termination) { return string(buff.get(), i - buff.get()); } } @@ -180,7 +182,7 @@ string BinaryReader::readMultibyteTerminatedStringBE(uint16 termination) do { m_stream->get(buff[0]); m_stream->get(buff[1]); - } while(!((buff[0] == delimChars[0]) && (buff[1] == delimChars[1]))); + } while (!((buff[0] == delimChars[0]) && (buff[1] == delimChars[1]))); return ss.str(); } @@ -200,7 +202,7 @@ string BinaryReader::readMultibyteTerminatedStringLE(uint16 termination) do { m_stream->get(buff[0]); m_stream->get(buff[1]); - } while(!((buff[0] == delimChars[0]) && (buff[1] == delimChars[1]))); + } while (!((buff[0] == delimChars[0]) && (buff[1] == delimChars[1]))); return ss.str(); } @@ -215,13 +217,13 @@ string BinaryReader::readMultibyteTerminatedStringLE(uint16 termination) */ string BinaryReader::readMultibyteTerminatedStringBE(std::size_t maxBytesToRead, uint16 termination) { - unique_ptr buff = make_unique(maxBytesToRead); + unique_ptr buff = make_unique(maxBytesToRead); char *delimChars = m_buffer; ConversionUtilities::BE::getBytes(termination, delimChars); - for(char *i = buff.get(), *end = i + maxBytesToRead; (i + 1) < end; i += 2) { + for (char *i = buff.get(), *end = i + maxBytesToRead; (i + 1) < end; i += 2) { m_stream->get(*i); m_stream->get(*(i + 1)); - if((*i == delimChars[0]) && (*(i + 1) == delimChars[1])) { + if ((*i == delimChars[0]) && (*(i + 1) == delimChars[1])) { return string(buff.get(), i - buff.get()); } } @@ -239,13 +241,13 @@ string BinaryReader::readMultibyteTerminatedStringBE(std::size_t maxBytesToRead, */ string BinaryReader::readMultibyteTerminatedStringLE(std::size_t maxBytesToRead, uint16 termination) { - unique_ptr buff = make_unique(maxBytesToRead); + unique_ptr buff = make_unique(maxBytesToRead); char *delimChars = m_buffer; ConversionUtilities::LE::getBytes(termination, delimChars); - for(char *i = buff.get(), *end = i + maxBytesToRead; (i + 1) < end; i += 2) { + for (char *i = buff.get(), *end = i + maxBytesToRead; (i + 1) < end; i += 2) { m_stream->get(*i); m_stream->get(*(i + 1)); - if((*i == delimChars[0]) && (*(i + 1) == delimChars[1])) { + if ((*i == delimChars[0]) && (*(i + 1) == delimChars[1])) { return string(buff.get(), i - buff.get()); } } @@ -263,7 +265,7 @@ string BinaryReader::readMultibyteTerminatedStringLE(std::size_t maxBytesToRead, uint32 BinaryReader::readCrc32(size_t length) { uint32 crc = 0x00; - for(uint32 i = 0; i < length; ++i) { + for (uint32 i = 0; i < length; ++i) { crc = (crc << 8) ^ crc32Table[((crc >> 24) & 0xff) ^ static_cast(m_stream->get())]; } return crc; @@ -280,7 +282,7 @@ uint32 BinaryReader::readCrc32(size_t length) uint32 BinaryReader::computeCrc32(const char *buffer, size_t length) { uint32 crc = 0x00; - for(const char *i = buffer, *end = buffer + length; i != end; ++i) { + for (const char *i = buffer, *end = buffer + length; i != end; ++i) { crc = (crc << 8) ^ crc32Table[((crc >> 24) & 0xff) ^ static_cast(*i)]; } return crc; @@ -291,49 +293,25 @@ uint32 BinaryReader::computeCrc32(const char *buffer, size_t length) * \remarks Internally used by readCrc32() method. * \sa readCrc32() */ -const uint32 BinaryReader::crc32Table[] = { - 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, - 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, - 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, - 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, - 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, - 0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, - 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef, - 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, - 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, - 0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, - 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, - 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, - 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, - 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, - 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, - 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, - 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, - 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, - 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050, - 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, - 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, - 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, - 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, - 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, - 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, - 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, - 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9, - 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, - 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, - 0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, - 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, - 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, - 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, - 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, - 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, - 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, - 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, - 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, - 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676, - 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, - 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, - 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, - 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 -}; - +const uint32 BinaryReader::crc32Table[] = { 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, + 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, + 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, + 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, + 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, + 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, + 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, + 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, + 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, + 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, + 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, + 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, + 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, + 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, + 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, + 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, + 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, + 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, + 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, + 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, + 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, + 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 }; diff --git a/io/binaryreader.h b/io/binaryreader.h index ce85afe..00279d8 100644 --- a/io/binaryreader.h +++ b/io/binaryreader.h @@ -3,19 +3,17 @@ #include "../conversion/binaryconversion.h" -#include -#include #include +#include +#include -namespace IoUtilities -{ -class CPP_UTILITIES_EXPORT BinaryReader -{ +namespace IoUtilities { +class CPP_UTILITIES_EXPORT BinaryReader { public: BinaryReader(std::istream *stream); BinaryReader(const BinaryReader &other); - BinaryReader & operator=(const BinaryReader & rhs) = delete; + BinaryReader &operator=(const BinaryReader &rhs) = delete; ~BinaryReader(); const std::istream *stream() const; @@ -127,7 +125,7 @@ inline bool BinaryReader::hasOwnership() const */ inline void BinaryReader::giveOwnership() { - if(m_stream) { + if (m_stream) { m_ownership = true; } } @@ -219,7 +217,7 @@ inline int32 BinaryReader::readInt24BE() *m_buffer = 0; m_stream->read(m_buffer + 1, 3); auto val = ConversionUtilities::BE::toInt32(m_buffer); - if(val >= 0x800000) { + if (val >= 0x800000) { val = -(0x1000000 - val); } return val; @@ -261,7 +259,7 @@ inline int64 BinaryReader::readInt40BE() *m_buffer = *(m_buffer + 1) = *(m_buffer + 2) = 0; m_stream->read(m_buffer + 3, 5); auto val = ConversionUtilities::BE::toInt64(m_buffer); - if(val >= 0x8000000000) { + if (val >= 0x8000000000) { val = -(0x10000000000 - val); } return val; @@ -285,7 +283,7 @@ inline int64 BinaryReader::readInt56BE() *m_buffer = 0; m_stream->read(m_buffer + 1, 7); auto val = ConversionUtilities::BE::toInt64(m_buffer); - if(val >= 0x80000000000000) { + if (val >= 0x80000000000000) { val = -(0x100000000000000 - val); } return val; @@ -363,7 +361,7 @@ inline int32 BinaryReader::readInt24LE() *(m_buffer + 3) = 0; m_stream->read(m_buffer, 3); auto val = ConversionUtilities::LE::toInt32(m_buffer); - if(val >= 0x800000) { + if (val >= 0x800000) { val = -(0x1000000 - val); } return val; @@ -405,7 +403,7 @@ inline int64 BinaryReader::readInt40LE() *(m_buffer + 5) = *(m_buffer + 6) = *(m_buffer + 7) = 0; m_stream->read(m_buffer, 5); auto val = ConversionUtilities::LE::toInt64(m_buffer); - if(val >= 0x8000000000) { + if (val >= 0x8000000000) { val = -(0x10000000000 - val); } return val; @@ -429,7 +427,7 @@ inline int64 BinaryReader::readInt56LE() *(m_buffer + 7) = 0; m_stream->read(m_buffer, 7); auto val = ConversionUtilities::LE::toInt64(m_buffer); - if(val >= 0x80000000000000) { + if (val >= 0x80000000000000) { val = -(0x100000000000000 - val); } return val; @@ -559,7 +557,6 @@ inline float32 BinaryReader::readFixed16LE() { return ConversionUtilities::toFloat32(readUInt32LE()); } - } #endif // IOUTILITIES_BINERYREADER_H diff --git a/io/binarywriter.cpp b/io/binarywriter.cpp index 8acda42..dd9e5b7 100644 --- a/io/binarywriter.cpp +++ b/io/binarywriter.cpp @@ -19,26 +19,28 @@ using namespace ConversionUtilities; * \brief Constructs a new BinaryWriter. * \param stream Specifies the stream to write to. */ -BinaryWriter::BinaryWriter(ostream *stream) : - m_stream(stream), - m_ownership(false) -{} +BinaryWriter::BinaryWriter(ostream *stream) + : m_stream(stream) + , m_ownership(false) +{ +} /*! * \brief Copies the specified BinaryWriter. * \remarks The copy will not take ownership over the stream. */ -BinaryWriter::BinaryWriter(const BinaryWriter &other) : - m_stream(other.m_stream), - m_ownership(false) -{} +BinaryWriter::BinaryWriter(const BinaryWriter &other) + : m_stream(other.m_stream) + , m_ownership(false) +{ +} /*! * \brief Destroys the BinaryWriter. */ BinaryWriter::~BinaryWriter() { - if(m_ownership) { + if (m_ownership) { delete m_stream; } } @@ -56,10 +58,10 @@ BinaryWriter::~BinaryWriter() */ void BinaryWriter::setStream(ostream *stream, bool giveOwnership) { - if(m_ownership) { + if (m_ownership) { delete m_stream; } - if(stream) { + if (stream) { m_stream = stream; m_ownership = giveOwnership; } else { @@ -76,16 +78,16 @@ void BinaryWriter::setStream(ostream *stream, bool giveOwnership) void BinaryWriter::writeLengthPrefixedString(const string &value) { size_t length = value.length(); - if(length < 0x80) { + if (length < 0x80) { m_buffer[0] = 0x80 | length; m_stream->write(m_buffer, 1); - } else if(length < 0x4000) { + } else if (length < 0x4000) { BE::getBytes(static_cast(0x4000 | length), m_buffer); m_stream->write(m_buffer, 2); - } else if(length < 0x200000) { + } else if (length < 0x200000) { BE::getBytes(static_cast(0x200000 | length), m_buffer); m_stream->write(m_buffer + 1, 3); - } else if(length < 0x10000000) { + } else if (length < 0x10000000) { BE::getBytes(static_cast(0x10000000 | length), m_buffer); m_stream->write(m_buffer, 4); } else { diff --git a/io/binarywriter.h b/io/binarywriter.h index c53d57e..ee9838a 100644 --- a/io/binarywriter.h +++ b/io/binarywriter.h @@ -1,22 +1,20 @@ #ifndef IOUTILITIES_BINARYWRITER_H #define IOUTILITIES_BINARYWRITER_H -#include "../conversion/types.h" #include "../conversion/binaryconversion.h" +#include "../conversion/types.h" -#include -#include #include +#include +#include -namespace IoUtilities -{ +namespace IoUtilities { -class CPP_UTILITIES_EXPORT BinaryWriter -{ +class CPP_UTILITIES_EXPORT BinaryWriter { public: BinaryWriter(std::ostream *stream); BinaryWriter(const BinaryWriter &other); - BinaryWriter & operator=(const BinaryWriter & rhs) = delete; + BinaryWriter &operator=(const BinaryWriter &rhs) = delete; ~BinaryWriter(); const std::ostream *stream() const; @@ -117,7 +115,7 @@ inline bool BinaryWriter::hasOwnership() const */ inline void BinaryWriter::giveOwnership() { - if(m_stream) { + if (m_stream) { m_ownership = true; } } @@ -527,7 +525,6 @@ inline void BinaryWriter::writeFixed16LE(float32 valueToConvertAndWrite) { writeUInt32LE(ConversionUtilities::toFixed16(valueToConvertAndWrite)); } - } #endif // IO_UTILITIES_BINARYWRITER_H diff --git a/io/bitreader.cpp b/io/bitreader.cpp index 1dc6031..1019472 100644 --- a/io/bitreader.cpp +++ b/io/bitreader.cpp @@ -18,10 +18,10 @@ namespace IoUtilities { */ void BitReader::skipBits(std::size_t bitCount) { - if(bitCount <= m_bitsAvail) { + if (bitCount <= m_bitsAvail) { m_bitsAvail -= bitCount; } else { - if((m_buffer += 1 + (bitCount -= m_bitsAvail) / 8) >= m_end) { + if ((m_buffer += 1 + (bitCount -= m_bitsAvail) / 8) >= m_end) { throwIoFailure("end of buffer exceeded"); } m_bitsAvail = 8 - (bitCount % 8); @@ -29,4 +29,3 @@ void BitReader::skipBits(std::size_t bitCount) } } // namespace IoUtilities - diff --git a/io/bitreader.h b/io/bitreader.h index 036548a..5dd72ef 100644 --- a/io/bitreader.h +++ b/io/bitreader.h @@ -2,8 +2,8 @@ #define IOUTILITIES_BITREADER_H #include "../conversion/types.h" -#include "../io/catchiofailure.h" #include "../global.h" +#include "../io/catchiofailure.h" #include #include @@ -11,17 +11,16 @@ namespace IoUtilities { -class CPP_UTILITIES_EXPORT BitReader -{ +class CPP_UTILITIES_EXPORT BitReader { public: BitReader(const char *buffer, std::size_t bufferSize); BitReader(const char *buffer, const char *end); - template intType readBits(byte bitCount); + template intType readBits(byte bitCount); byte readBit(); - template intType readUnsignedExpGolombCodedBits(); - template intType readSignedExpGolombCodedBits(); - template intType showBits(byte bitCount); + template intType readUnsignedExpGolombCodedBits(); + template intType readSignedExpGolombCodedBits(); + template intType showBits(byte bitCount); void skipBits(std::size_t bitCount); void align(); std::size_t bitsAvailable(); @@ -40,9 +39,10 @@ private: * - Does not take ownership over the specified \a buffer. * - bufferSize must be equal or greather than 1. */ -inline BitReader::BitReader(const char *buffer, std::size_t bufferSize) : - BitReader(buffer, buffer + bufferSize) -{} +inline BitReader::BitReader(const char *buffer, std::size_t bufferSize) + : BitReader(buffer, buffer + bufferSize) +{ +} /*! * \brief Constructs a new BitReader. @@ -50,11 +50,12 @@ inline BitReader::BitReader(const char *buffer, std::size_t bufferSize) : * - Does not take ownership over the specified \a buffer. * - \a end must be greather than \a buffer. */ -inline BitReader::BitReader(const char *buffer, const char *end) : - m_buffer(reinterpret_cast(buffer)), - m_end(reinterpret_cast(end)), - m_bitsAvail(8) -{} +inline BitReader::BitReader(const char *buffer, const char *end) + : m_buffer(reinterpret_cast(buffer)) + , m_end(reinterpret_cast(end)) + , m_bitsAvail(8) +{ +} /*! * \brief Reads the specified number of bits from the buffer advancing the current position by \a bitCount bits. @@ -64,13 +65,12 @@ inline BitReader::BitReader(const char *buffer, const char *end) : * \throws Throws ios_base::failure if the end of the buffer is exceeded. * The reader becomes invalid in that case. */ -template -intType BitReader::readBits(byte bitCount) +template intType BitReader::readBits(byte bitCount) { intType val = 0; - for(byte readAtOnce; bitCount; bitCount -= readAtOnce) { - if(!m_bitsAvail) { - if(++m_buffer >= m_end) { + for (byte readAtOnce; bitCount; bitCount -= readAtOnce) { + if (!m_bitsAvail) { + if (++m_buffer >= m_end) { throwIoFailure("end of buffer exceeded"); } m_bitsAvail = 8; @@ -99,11 +99,10 @@ inline byte BitReader::readBit() * The reader becomes invalid in that case. * \sa https://en.wikipedia.org/wiki/Exponential-Golomb_coding */ -template -intType BitReader::readUnsignedExpGolombCodedBits() +template intType BitReader::readUnsignedExpGolombCodedBits() { byte count = 0; - while(!readBit()) { + while (!readBit()) { ++count; } return count ? (((1 << count) | readBits(count)) - 1) : 0; @@ -117,8 +116,7 @@ intType BitReader::readUnsignedExpGolombCodedBits() * The reader becomes invalid in that case. * \sa https://en.wikipedia.org/wiki/Exponential-Golomb_coding */ -template -intType BitReader::readSignedExpGolombCodedBits() +template intType BitReader::readSignedExpGolombCodedBits() { auto value = readUnsignedExpGolombCodedBits::type>(); return (value % 2) ? static_cast((value + 1) / 2) : (-static_cast(value / 2)); @@ -127,8 +125,7 @@ intType BitReader::readSignedExpGolombCodedBits() /*! * \brief Reads the specified number of bits from the buffer without advancing the current position. */ -template -intType BitReader::showBits(byte bitCount) +template intType BitReader::showBits(byte bitCount) { auto tmp = *this; return tmp.readBits(bitCount); diff --git a/io/catchiofailure.cpp b/io/catchiofailure.cpp index 8b6910e..060cc6b 100644 --- a/io/catchiofailure.cpp +++ b/io/catchiofailure.cpp @@ -19,7 +19,7 @@ const char *catchIoFailure() { try { throw; - } catch(const ios_base::failure &e) { + } catch (const ios_base::failure &e) { return e.what(); } } @@ -31,6 +31,4 @@ void throwIoFailure(const char *what) { throw ios_base::failure(what); } - } - diff --git a/io/catchiofailure.h b/io/catchiofailure.h index e96d600..5ec97a5 100644 --- a/io/catchiofailure.h +++ b/io/catchiofailure.h @@ -9,7 +9,6 @@ namespace IoUtilities { CPP_UTILITIES_EXPORT const char *catchIoFailure(); CPP_UTILITIES_EXPORT void throwIoFailure(const char *what); - } #endif // IOUTILITIES_CATCHIOFAILURE_H diff --git a/io/copy.h b/io/copy.h index c6b508a..338662e 100644 --- a/io/copy.h +++ b/io/copy.h @@ -3,8 +3,8 @@ #include "../global.h" -#include #include +#include namespace IoUtilities { @@ -13,14 +13,14 @@ namespace IoUtilities { * \brief The CopyHelper class helps to copy bytes from one stream to another. * \tparam Specifies the buffer size. */ -template -class CPP_UTILITIES_EXPORT CopyHelper -{ +template class CPP_UTILITIES_EXPORT CopyHelper { public: CopyHelper(); void copy(std::istream &input, std::ostream &output, std::size_t count); - void callbackCopy(std::istream &input, std::ostream &output, std::size_t count, const std::function &isAborted, const std::function &callback); + void callbackCopy(std::istream &input, std::ostream &output, std::size_t count, const std::function &isAborted, + const std::function &callback); char *buffer(); + private: char m_buffer[bufferSize]; }; @@ -28,19 +28,18 @@ private: /*! * \brief Constructs a new copy helper. */ -template -CopyHelper::CopyHelper() -{} +template CopyHelper::CopyHelper() +{ +} /*! * \brief Copies \a count bytes from \a input to \a output. * \remarks Set an exception mask using std::ios::exceptions() to get a std::ios_base::failure exception * when an IO error occurs. */ -template -void CopyHelper::copy(std::istream &input, std::ostream &output, std::size_t count) +template void CopyHelper::copy(std::istream &input, std::ostream &output, std::size_t count) { - while(count > bufferSize) { + while (count > bufferSize) { input.read(m_buffer, bufferSize); output.write(m_buffer, bufferSize); count -= bufferSize; @@ -49,7 +48,6 @@ void CopyHelper::copy(std::istream &input, std::ostream &output, std output.write(m_buffer, count); } - /*! * \brief Copies \a count bytes from \a input to \a output. The procedure might be aborted and * progress updates will be reported. @@ -60,15 +58,16 @@ void CopyHelper::copy(std::istream &input, std::ostream &output, std * \remarks Set an exception mask using std::ios::exceptions() to get a std::ios_base::failure exception * when an IO error occurs. */ -template -void CopyHelper::callbackCopy(std::istream &input, std::ostream &output, std::size_t count, const std::function &isAborted, const std::function &callback) +template +void CopyHelper::callbackCopy(std::istream &input, std::ostream &output, std::size_t count, const std::function &isAborted, + const std::function &callback) { const std::size_t totalBytes = count; - while(count > bufferSize) { + while (count > bufferSize) { input.read(m_buffer, bufferSize); output.write(m_buffer, bufferSize); count -= bufferSize; - if(isAborted()) { + if (isAborted()) { return; } callback(static_cast(totalBytes - count) / totalBytes); @@ -81,12 +80,10 @@ void CopyHelper::callbackCopy(std::istream &input, std::ostream &out /*! * \brief Returns the internal buffer. */ -template -char *CopyHelper::buffer() +template char *CopyHelper::buffer() { return m_buffer; } - } #endif // IOUTILITIES_COPY_H diff --git a/io/inifile.cpp b/io/inifile.cpp index 6c6cfab..95d32a5 100644 --- a/io/inifile.cpp +++ b/io/inifile.cpp @@ -18,7 +18,7 @@ namespace IoUtilities { void IniFile::parse(std::istream &inputStream) { // define variable for state machine - enum State {Init, Comment, ScopeName, Key, Value} state = Init; + enum State { Init, Comment, ScopeName, Key, Value } state = Init; // current character char c; // number of postponed whitespaces @@ -31,10 +31,10 @@ void IniFile::parse(std::istream &inputStream) // define actions for state machine // called when key/value pair is complete const auto finishKeyValue = [&state, &scope, &key, &value, &whitespace, this] { - if(key.empty() && value.empty() && state != Value) { + if (key.empty() && value.empty() && state != Value) { return; } - if(m_data.empty() || m_data.back().first != scope) { + if (m_data.empty() || m_data.back().first != scope) { m_data.emplace_back(make_pair(scope, decltype(m_data)::value_type::second_type())); } m_data.back().second.insert(make_pair(key, value)); @@ -43,12 +43,12 @@ void IniFile::parse(std::istream &inputStream) whitespace = 0; }; // called to add current character to current key or value - const auto addChar = [&whitespace, &c] (string &to) { - if(c == ' ') { + const auto addChar = [&whitespace, &c](string &to) { + if (c == ' ') { ++whitespace; } else { - if(!to.empty()) { - while(whitespace) { + if (!to.empty()) { + while (whitespace) { to += ' '; --whitespace; } @@ -62,10 +62,10 @@ void IniFile::parse(std::istream &inputStream) inputStream.exceptions(ios_base::failbit | ios_base::badbit); // parse the file char by char try { - while(inputStream.get(c)) { - switch(state) { + while (inputStream.get(c)) { + switch (state) { case Init: - switch(c) { + switch (c) { case '\n': break; case '#': @@ -85,7 +85,7 @@ void IniFile::parse(std::istream &inputStream) } break; case Key: - switch(c) { + switch (c) { case '\n': finishKeyValue(); state = Init; @@ -103,16 +103,15 @@ void IniFile::parse(std::istream &inputStream) } break; case Comment: - switch(c) { + switch (c) { case '\n': state = Init; break; - default: - ; + default:; } break; case ScopeName: - switch(c) { + switch (c) { case ']': state = Init; break; @@ -121,7 +120,7 @@ void IniFile::parse(std::istream &inputStream) } break; case Value: - switch(c) { + switch (c) { case '\n': finishKeyValue(); state = Init; @@ -136,9 +135,9 @@ void IniFile::parse(std::istream &inputStream) break; } } - } catch(...) { + } catch (...) { const char *what = catchIoFailure(); - if(inputStream.eof()) { + if (inputStream.eof()) { // we just reached the end of the file // don't forget to save the last key/value pair finishKeyValue(); @@ -155,9 +154,9 @@ void IniFile::make(ostream &outputStream) { // thorw an exception when an IO error occurs outputStream.exceptions(ios_base::failbit | ios_base::badbit); - for(const auto &scope : m_data) { + for (const auto &scope : m_data) { outputStream << '[' << scope.first << ']' << '\n'; - for(const auto &field : scope.second) { + for (const auto &field : scope.second) { outputStream << field.first << '=' << field.second << '\n'; } outputStream << '\n'; @@ -165,4 +164,3 @@ void IniFile::make(ostream &outputStream) } } // namespace IoUtilities - diff --git a/io/inifile.h b/io/inifile.h index df492f7..55a8b5b 100644 --- a/io/inifile.h +++ b/io/inifile.h @@ -3,14 +3,13 @@ #include "../global.h" -#include #include #include +#include namespace IoUtilities { -class CPP_UTILITIES_EXPORT IniFile -{ +class CPP_UTILITIES_EXPORT IniFile { public: IniFile(); @@ -27,7 +26,8 @@ private: * \brief Constructs an empty ini file. */ inline IniFile::IniFile() -{} +{ +} /*! * \brief Returns the data of the file. diff --git a/io/misc.cpp b/io/misc.cpp index 5c4245e..ad92f55 100644 --- a/io/misc.cpp +++ b/io/misc.cpp @@ -21,7 +21,7 @@ string readFile(const string &path, std::string::size_type maxSize) file.seekg(0, ios_base::end); string res; const auto size = static_cast(file.tellg()); - if(maxSize != string::npos && size > maxSize) { + if (maxSize != string::npos && size > maxSize) { throwIoFailure("File exceeds max size"); } res.reserve(size); @@ -29,5 +29,4 @@ string readFile(const string &path, std::string::size_type maxSize) res.assign((istreambuf_iterator(file)), istreambuf_iterator()); return res; } - } diff --git a/io/misc.h b/io/misc.h index 88e51fe..f31e2e2 100644 --- a/io/misc.h +++ b/io/misc.h @@ -8,7 +8,6 @@ namespace IoUtilities { CPP_UTILITIES_EXPORT std::string readFile(const std::string &path, std::string::size_type maxSize = std::string::npos); - } #endif // IOUTILITIES_MISC_H diff --git a/io/nativefilestream.cpp b/io/nativefilestream.cpp index bbc02e6..31c894f 100644 --- a/io/nativefilestream.cpp +++ b/io/nativefilestream.cpp @@ -1,10 +1,10 @@ #include "./nativefilestream.h" #ifdef PLATFORM_MINGW -# include "catchiofailure.h" -# include -# include -# include +#include "catchiofailure.h" +#include +#include +#include #endif using namespace std; @@ -17,44 +17,45 @@ namespace IoUtilities { #else -NativeFileStream::NativeFileStream() : - m_filebuf(new __gnu_cxx::stdio_filebuf) +NativeFileStream::NativeFileStream() + : m_filebuf(new __gnu_cxx::stdio_filebuf) { rdbuf(m_filebuf.get()); } NativeFileStream::~NativeFileStream() -{} +{ +} void NativeFileStream::open(const string &path, ios_base::openmode flags) { // convert path to UTF-16 int requiredSize = MultiByteToWideChar(CP_UTF8, 0, path.data(), -1, nullptr, 0); - if(requiredSize <= 0) { + if (requiredSize <= 0) { ::IoUtilities::throwIoFailure("Unable to calculate buffer size for conversion of path to UTF-16"); } auto widePath = make_unique(static_cast(requiredSize)); requiredSize = MultiByteToWideChar(CP_UTF8, 0, path.data(), -1, widePath.get(), requiredSize); - if(requiredSize <= 0) { + if (requiredSize <= 0) { ::IoUtilities::throwIoFailure("Unable to convert path to UTF-16"); } // translate flags int nativeFlags = (flags & ios_base::binary ? _O_BINARY : 0); int permissions = 0; - if((flags & ios_base::out) && (flags & ios_base::in)) { + if ((flags & ios_base::out) && (flags & ios_base::in)) { nativeFlags |= _O_RDWR; - } else if(flags & ios_base::out) { + } else if (flags & ios_base::out) { nativeFlags |= _O_WRONLY | _O_CREAT; permissions = _S_IREAD | _S_IWRITE; - } else if(flags & ios_base::in) { + } else if (flags & ios_base::in) { nativeFlags |= _O_RDONLY; } - if(flags & ios_base::trunc) { + if (flags & ios_base::trunc) { nativeFlags |= _O_TRUNC; } // initialize stdio_filebuf int fd = _wopen(widePath.get(), nativeFlags, permissions); - if(fd == -1) { + if (fd == -1) { ::IoUtilities::throwIoFailure("_wopen failed"); } m_filebuf = make_unique<__gnu_cxx::stdio_filebuf >(fd, flags); @@ -63,11 +64,10 @@ void NativeFileStream::open(const string &path, ios_base::openmode flags) void NativeFileStream::close() { - if(m_filebuf) { + if (m_filebuf) { m_filebuf->close(); } } #endif - } diff --git a/io/nativefilestream.h b/io/nativefilestream.h index 42e9c5a..81588ad 100644 --- a/io/nativefilestream.h +++ b/io/nativefilestream.h @@ -4,12 +4,12 @@ #include "../global.h" #ifndef PLATFORM_MINGW -# include +#include #else -# include -# include -# include -# include +#include +#include +#include +#include #endif namespace IoUtilities { @@ -20,8 +20,7 @@ typedef std::fstream NativeFileStream; #else -class CPP_UTILITIES_EXPORT NativeFileStream : public std::iostream -{ +class CPP_UTILITIES_EXPORT NativeFileStream : public std::iostream { public: NativeFileStream(); ~NativeFileStream(); @@ -41,8 +40,6 @@ inline bool NativeFileStream::is_open() const } #endif - } #endif // IOUTILITIES_NATIVE_FILE_STREAM - diff --git a/io/path.cpp b/io/path.cpp index 68630ee..d57806f 100644 --- a/io/path.cpp +++ b/io/path.cpp @@ -1,25 +1,25 @@ #include "./path.h" -#include -#include -#include #include +#include +#include +#include #if defined(PLATFORM_UNIX) -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #elif defined(PLATFORM_WINDOWS) -# ifdef UNICODE -# undef UNICODE -# endif -# ifdef _UNICODE -# undef _UNICODE -# endif -# include +#ifdef UNICODE +#undef UNICODE +#endif +#ifdef _UNICODE +#undef _UNICODE +#endif +#include #else -# error Platform not supported. +#error Platform not supported. #endif using namespace std; @@ -34,11 +34,11 @@ string fileName(const string &path) size_t lastSlash = path.rfind('/'); size_t lastBackSlash = path.rfind('\\'); size_t lastSeparator; - if(lastSlash == string::npos && lastBackSlash == string::npos) { + if (lastSlash == string::npos && lastBackSlash == string::npos) { return path; - } else if(lastSlash == string::npos) { + } else if (lastSlash == string::npos) { lastSeparator = lastBackSlash; - } else if(lastBackSlash == string::npos) { + } else if (lastBackSlash == string::npos) { lastSeparator = lastSlash; } else { lastSeparator = lastSlash > lastBackSlash ? lastSlash : lastBackSlash; @@ -54,11 +54,11 @@ string directory(const string &path) size_t lastSlash = path.rfind('/'); size_t lastBackSlash = path.rfind('\\'); size_t lastSeparator; - if(lastSlash == string::npos && lastBackSlash == string::npos) { + if (lastSlash == string::npos && lastBackSlash == string::npos) { return string(); - } else if(lastSlash == string::npos) { + } else if (lastSlash == string::npos) { lastSeparator = lastBackSlash; - } else if(lastBackSlash == string::npos) { + } else if (lastBackSlash == string::npos) { lastSeparator = lastSlash; } else { lastSeparator = lastSlash > lastBackSlash ? lastSlash : lastBackSlash; @@ -74,10 +74,10 @@ string directory(const string &path) void removeInvalidChars(std::string &fileName) { size_t startPos = 0; - static const char invalidPathChars[] = {'\"', '<', '>', '?', '!', '*', '|', '/', ':', '\\', '\n'}; - for(const char *i = invalidPathChars, *end = invalidPathChars + sizeof(invalidPathChars); i != end; ++i) { + static const char invalidPathChars[] = { '\"', '<', '>', '?', '!', '*', '|', '/', ':', '\\', '\n' }; + for (const char *i = invalidPathChars, *end = invalidPathChars + sizeof(invalidPathChars); i != end; ++i) { startPos = fileName.find(*i); - while(startPos != string::npos) { + while (startPos != string::npos) { fileName.replace(startPos, 1, string()); startPos = fileName.find(*i, startPos); } @@ -97,18 +97,18 @@ bool settingsDirectory(std::string &result, std::string applicationDirectoryName result.clear(); // FIXME: this kind of configuration is not actually used so get rid of it, maybe just read env variable instead fstream pathConfigFile("path.config", ios_base::in); - if(pathConfigFile.good()) { - for(string line; getline(pathConfigFile, line); ) { + if (pathConfigFile.good()) { + for (string line; getline(pathConfigFile, line);) { string::size_type p = line.find('='); - if((p != string::npos) && (p + 1 < line.length())) { + if ((p != string::npos) && (p + 1 < line.length())) { string fieldName = line.substr(0, p); - if(fieldName == "settings") { + if (fieldName == "settings") { result.assign(line.substr(p + 1)); } } } } - if(!result.empty()) { + if (!result.empty()) { #if defined(PLATFORM_UNIX) struct stat sb; return (stat(result.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)); @@ -118,11 +118,11 @@ bool settingsDirectory(std::string &result, std::string applicationDirectoryName return (ftyp != INVALID_FILE_ATTRIBUTES) && (ftyp & FILE_ATTRIBUTE_DIRECTORY); #endif } else { - if(!applicationDirectoryName.empty()) { + if (!applicationDirectoryName.empty()) { removeInvalidChars(applicationDirectoryName); } #if defined(PLATFORM_UNIX) || defined(PLATFORM_MAC) - if(char *homeDir = getenv("HOME")) { + if (char *homeDir = getenv("HOME")) { result = homeDir; } else { struct passwd *pw = getpwuid(getuid()); @@ -130,35 +130,35 @@ bool settingsDirectory(std::string &result, std::string applicationDirectoryName } struct stat sb; result += "/.config"; - if(createApplicationDirectory && !(stat(result.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))) { - if(mkdir(result.c_str(), S_IRUSR | S_IWUSR | S_IXUSR) != 0) { + if (createApplicationDirectory && !(stat(result.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))) { + if (mkdir(result.c_str(), S_IRUSR | S_IWUSR | S_IXUSR) != 0) { return false; } } - if(!applicationDirectoryName.empty()) { + if (!applicationDirectoryName.empty()) { result += '/'; result += applicationDirectoryName; - if(createApplicationDirectory && !(stat(result.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))) { - if(mkdir(result.c_str(), S_IRUSR | S_IWUSR | S_IXUSR) != 0) { + if (createApplicationDirectory && !(stat(result.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))) { + if (mkdir(result.c_str(), S_IRUSR | S_IWUSR | S_IXUSR) != 0) { return false; } } } #else // PLATFORM_WINDOWS - if(char *appData = getenv("appdata")) { + if (char *appData = getenv("appdata")) { result = appData; - if(!applicationDirectoryName.empty()) { + if (!applicationDirectoryName.empty()) { result += '\\'; result += applicationDirectoryName; - if(createApplicationDirectory) { + if (createApplicationDirectory) { // FIXME: use UTF-16 API to support unicode, or rewrite using fs abstraction lib DWORD ftyp = GetFileAttributesA(result.c_str()); - if(ftyp == INVALID_FILE_ATTRIBUTES) { + if (ftyp == INVALID_FILE_ATTRIBUTES) { return false; - } else if(ftyp & FILE_ATTRIBUTE_DIRECTORY) { + } else if (ftyp & FILE_ATTRIBUTE_DIRECTORY) { return true; } else { - if(CreateDirectory(result.c_str(), NULL) == 0) { + if (CreateDirectory(result.c_str(), NULL) == 0) { return false; } else { return true; @@ -182,10 +182,10 @@ std::list directoryEntries(const char *path, DirectoryEntryType typ { #ifdef PLATFORM_UNIX list entries; - if(auto dir = opendir(path)) { - while(auto dirEntry = readdir(dir)) { + if (auto dir = opendir(path)) { + while (auto dirEntry = readdir(dir)) { bool filter = false; - switch(dirEntry->d_type) { + switch (dirEntry->d_type) { case DT_REG: filter = (types & DirectoryEntryType::File) != DirectoryEntryType::None; break; @@ -198,7 +198,7 @@ std::list directoryEntries(const char *path, DirectoryEntryType typ default: filter = (types & DirectoryEntryType::All) != DirectoryEntryType::None; } - if(filter) { + if (filter) { entries.emplace_back(dirEntry->d_name); } } @@ -209,5 +209,4 @@ std::list directoryEntries(const char *path, DirectoryEntryType typ return list(); // TODO #endif } - } diff --git a/io/path.h b/io/path.h index 0d82901..7e0edc6 100644 --- a/io/path.h +++ b/io/path.h @@ -3,19 +3,19 @@ #include "../global.h" -#include #include +#include #ifdef PLATFORM_WINDOWS -# define PATH_SEP_CHAR '\\' -# define SEARCH_PATH_SEP_CHAR ';' -# define PATH_SEP_STR "\\" -# define SEARCH_PATH_SEP_STR ";" +#define PATH_SEP_CHAR '\\' +#define SEARCH_PATH_SEP_CHAR ';' +#define PATH_SEP_STR "\\" +#define SEARCH_PATH_SEP_STR ";" #else -# define PATH_SEP_CHAR '/' -# define SEARCH_PATH_SEP_CHAR ':' -# define PATH_SEP_STR "/" -# define SEARCH_PATH_SEP_STR ":" +#define PATH_SEP_CHAR '/' +#define SEARCH_PATH_SEP_CHAR ':' +#define PATH_SEP_STR "/" +#define SEARCH_PATH_SEP_STR ":" #endif namespace IoUtilities { @@ -23,14 +23,7 @@ namespace IoUtilities { /*! * \brief The DirectoryEntryType enum specifies the type of a directory entry (file, directory or symlink). */ -enum class DirectoryEntryType : unsigned char -{ - None = 0, - File = 1, - Directory = 2, - Symlink = 4, - All = 0xFF -}; +enum class DirectoryEntryType : unsigned char { None = 0, File = 1, Directory = 2, Symlink = 4, All = 0xFF }; constexpr DirectoryEntryType operator|(DirectoryEntryType lhs, DirectoryEntryType rhs) { @@ -50,9 +43,9 @@ constexpr DirectoryEntryType operator&(DirectoryEntryType lhs, DirectoryEntryTyp CPP_UTILITIES_EXPORT std::string fileName(const std::string &path); CPP_UTILITIES_EXPORT std::string directory(const std::string &path); CPP_UTILITIES_EXPORT void removeInvalidChars(std::string &fileName); -CPP_UTILITIES_EXPORT bool settingsDirectory(std::string &result, std::string applicationDirectoryName = std::string(), bool createApplicationDirectory = false); +CPP_UTILITIES_EXPORT bool settingsDirectory( + std::string &result, std::string applicationDirectoryName = std::string(), bool createApplicationDirectory = false); CPP_UTILITIES_EXPORT std::list directoryEntries(const char *path, DirectoryEntryType types = DirectoryEntryType::All); - } #endif // IOUTILITIES_PATHHELPER_H diff --git a/math/math.cpp b/math/math.cpp index a7a8e23..65d95ba 100644 --- a/math/math.cpp +++ b/math/math.cpp @@ -1,7 +1,7 @@ #include "./math.h" -#include #include +#include /*! * \namespace MathUtilities @@ -24,7 +24,7 @@ int MathUtilities::random(int lowerbounds, int upperbounds) int MathUtilities::digitsum(int number, int base) { int res = 0; - while(number > 0) { + while (number > 0) { res += number % base; number /= base; } @@ -37,7 +37,7 @@ int MathUtilities::digitsum(int number, int base) int MathUtilities::factorial(int number) { int res = 1; - for(int i = 1; i <= number; ++i) { + for (int i = 1; i <= number; ++i) { res *= i; } return res; @@ -49,11 +49,11 @@ int MathUtilities::factorial(int number) uint64 powerModulo(const uint64 base, const uint64 exponent, const uint64 module) { uint64 res = 1; - for(uint64 mask = 0x8000000000000000; mask; mask >>= 1) { - if(mask & exponent) { + for (uint64 mask = 0x8000000000000000; mask; mask >>= 1) { + if (mask & exponent) { res *= base; } - if(mask != 1) { + if (mask != 1) { res *= res; } res %= module; @@ -67,7 +67,7 @@ uint64 powerModulo(const uint64 base, const uint64 exponent, const uint64 module int64 inverseModulo(int64 number, int64 module) { int64 y1 = 0, y2 = 1, tmp; - while(number != 1) { + while (number != 1) { tmp = y1 - (module / number) * y2; y1 = y2; y2 = tmp; @@ -84,6 +84,7 @@ int64 inverseModulo(int64 number, int64 module) uint64 orderModulo(const uint64 number, const uint64 module) { uint64 order = 1; - for(; powerModulo(number, order, module) != 1; ++order); + for (; powerModulo(number, order, module) != 1; ++order) + ; return order; } diff --git a/math/math.h b/math/math.h index 7ff7e0e..95e5402 100644 --- a/math/math.h +++ b/math/math.h @@ -1,8 +1,8 @@ #ifndef MATHUTILITIES_H #define MATHUTILITIES_H -#include "../global.h" #include "../conversion/types.h" +#include "../global.h" namespace MathUtilities { @@ -12,7 +12,6 @@ CPP_UTILITIES_EXPORT int factorial(int number); CPP_UTILITIES_EXPORT uint64 powerModulo(uint64 base, uint64 expontent, uint64 module); CPP_UTILITIES_EXPORT int64 inverseModulo(int64 number, int64 module); CPP_UTILITIES_EXPORT uint64 orderModulo(uint64 number, uint64 module); - } #endif // MATHUTILITIES_H diff --git a/misc/memory.h b/misc/memory.h index a7e773d..a2b8bbc 100644 --- a/misc/memory.h +++ b/misc/memory.h @@ -8,38 +8,36 @@ #if __cplusplus <= 201103L #define __cpp_lib_make_unique 201304 namespace std { - template - struct _MakeUniq - { typedef unique_ptr<_Tp> __single_object; }; +template struct _MakeUniq { + typedef unique_ptr<_Tp> __single_object; +}; - template - struct _MakeUniq<_Tp[]> - { typedef unique_ptr<_Tp[]> __array; }; +template struct _MakeUniq<_Tp[]> { + typedef unique_ptr<_Tp[]> __array; +}; - template - struct _MakeUniq<_Tp[_Bound]> - { struct __invalid_type { }; }; +template struct _MakeUniq<_Tp[_Bound]> { + struct __invalid_type { + }; +}; - /// std::make_unique for single objects - template - inline typename _MakeUniq<_Tp>::__single_object - make_unique(_Args&&... __args) - { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); } +/// std::make_unique for single objects +template inline typename _MakeUniq<_Tp>::__single_object make_unique(_Args &&... __args) +{ + return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); +} - /// std::make_unique for arrays of unknown bound - template - inline typename _MakeUniq<_Tp>::__array - make_unique(size_t __num) - { return unique_ptr<_Tp>(new typename remove_extent<_Tp>::type[__num]()); } +/// std::make_unique for arrays of unknown bound +template inline typename _MakeUniq<_Tp>::__array make_unique(size_t __num) +{ + return unique_ptr<_Tp>(new typename remove_extent<_Tp>::type[__num]()); +} - /// Disable std::make_unique for arrays of known bound - template - inline typename _MakeUniq<_Tp>::__invalid_type - make_unique(_Args&&...) = delete; +/// Disable std::make_unique for arrays of known bound +template inline typename _MakeUniq<_Tp>::__invalid_type make_unique(_Args &&...) = delete; } #endif /// \endcond #endif // MEMORY_H - diff --git a/misc/random.cpp b/misc/random.cpp index 2dd441a..31c8dea 100644 --- a/misc/random.cpp +++ b/misc/random.cpp @@ -1,11 +1,11 @@ #include "./random.h" -#include -#include -#include +#include #include #include -#include +#include +#include +#include using namespace std; @@ -28,9 +28,10 @@ const char symbols[24] = "!\"$%&/()=?'#*+~-_><.:,;"; * \brief Generates a random character sequence using the given \a randomizer. * \deprecated Might be removed in future release because API is bad and it is not used anymore anyways. */ -void generateRandomCharacterSequence(char *result, unsigned int length, std::function randomizer, int highestRandomNumber, bool useSmallLetters, bool useCapitalLetters, bool useNumbers, bool useSymbols, bool useAtLeastOneOfEachCategory) +void generateRandomCharacterSequence(char *result, unsigned int length, std::function randomizer, int highestRandomNumber, + bool useSmallLetters, bool useCapitalLetters, bool useNumbers, bool useSymbols, bool useAtLeastOneOfEachCategory) { - if(length) { + if (length) { return; } signed char categoryCount = 0; @@ -38,73 +39,73 @@ void generateRandomCharacterSequence(char *result, unsigned int length, std::fun bool needCapitalLetter = false; bool needNumber = false; bool needSymbol = false; - if(useSmallLetters) { + if (useSmallLetters) { needSmallLetter = useAtLeastOneOfEachCategory; ++categoryCount; } - if(useCapitalLetters) { + if (useCapitalLetters) { needCapitalLetter = useAtLeastOneOfEachCategory; ++categoryCount; } - if(useNumbers) { + if (useNumbers) { needNumber = useAtLeastOneOfEachCategory; ++categoryCount; } - if(useSymbols) { + if (useSymbols) { needSymbol = useAtLeastOneOfEachCategory; ++categoryCount; } signed char neededCharacters = useAtLeastOneOfEachCategory ? categoryCount : 0; - if(!categoryCount) { + if (!categoryCount) { *result = '\0'; return; } - for(char *i = result, *end = result + length; i < end; ++i) { + for (char *i = result, *end = result + length; i < end; ++i) { int category = -1; - if((neededCharacters > 0 && (randomizer() < (highestRandomNumber / 2.0))) || ((end - i) >= neededCharacters)) { - if(needSmallLetter) + if ((neededCharacters > 0 && (randomizer() < (highestRandomNumber / 2.0))) || ((end - i) >= neededCharacters)) { + if (needSmallLetter) category = 0; - if(needCapitalLetter && ((category == -1) || (randomizer() < (highestRandomNumber / 2.0)))) + if (needCapitalLetter && ((category == -1) || (randomizer() < (highestRandomNumber / 2.0)))) category = 1; - if(needNumber && ((category == -1) || (randomizer() < (highestRandomNumber / 4.0)))) + if (needNumber && ((category == -1) || (randomizer() < (highestRandomNumber / 4.0)))) category = 2; - if(needSymbol && ((category == -1) || (randomizer() < (highestRandomNumber / 8.0)))) - category = 3; + if (needSymbol && ((category == -1) || (randomizer() < (highestRandomNumber / 8.0)))) + category = 3; } else { - if(useSmallLetters) + if (useSmallLetters) category = 0; - if(useCapitalLetters && ((category == -1) || (randomizer() < (highestRandomNumber / 2.0)))) + if (useCapitalLetters && ((category == -1) || (randomizer() < (highestRandomNumber / 2.0)))) category = 1; - if(useNumbers && ((category == -1) || (randomizer() < (highestRandomNumber / 4.0)))) + if (useNumbers && ((category == -1) || (randomizer() < (highestRandomNumber / 4.0)))) category = 2; - if(useSymbols && ((category == -1) || (randomizer() < (highestRandomNumber / 8.0)))) - category = 3; + if (useSymbols && ((category == -1) || (randomizer() < (highestRandomNumber / 8.0)))) + category = 3; } - switch(category) { + switch (category) { case 0: *i = letters[rand() % 26]; - if(needSmallLetter) { + if (needSmallLetter) { needSmallLetter = false; --neededCharacters; } break; case 1: *i = capitalLetters[rand() % 26]; - if(needCapitalLetter) { + if (needCapitalLetter) { needCapitalLetter = false; --neededCharacters; } break; case 2: *i = numbers[rand() % 9]; - if(needNumber) { + if (needNumber) { needNumber = false; --neededCharacters; } break; case 3: *i = symbols[rand() % 22]; - if(needSymbol) { + if (needSymbol) { needSymbol = false; --neededCharacters; } @@ -117,10 +118,10 @@ void generateRandomCharacterSequence(char *result, unsigned int length, std::fun * \brief Generates a random character sequence using std::rand(). * \deprecated Might be removed in future release because API is bad and it is not used anymore anyways. */ -void generateRandomCharacterSequence(char *result, unsigned int length, bool useSmallLetters, bool useCapitalLetters, bool useNumbers, bool useSymbols, bool useAtLeastOneOfEachCategory) +void generateRandomCharacterSequence(char *result, unsigned int length, bool useSmallLetters, bool useCapitalLetters, bool useNumbers, + bool useSymbols, bool useAtLeastOneOfEachCategory) { - generateRandomCharacterSequence(result, length, rand, RAND_MAX, useSmallLetters, useCapitalLetters, useNumbers, useSymbols, useAtLeastOneOfEachCategory); + generateRandomCharacterSequence( + result, length, rand, RAND_MAX, useSmallLetters, useCapitalLetters, useNumbers, useSymbols, useAtLeastOneOfEachCategory); } - } - diff --git a/misc/random.h b/misc/random.h index 9f50357..83ba3a9 100644 --- a/misc/random.h +++ b/misc/random.h @@ -7,9 +7,11 @@ namespace RandomUtilities { -CPP_UTILITIES_EXPORT void generateRandomCharacterSequence(char *result, unsigned int length, bool useSmallLetters = true, bool useCapitalLetters = true, bool useNumbers = true, bool useSymbols = true, bool useAtLeastOneOfEachCategory = true); -CPP_UTILITIES_EXPORT void generateRandomCharacterSequence(char *result, unsigned int length, std::function randomizer, int maximalRandomNumber, bool useSmallLetters = true, bool useCapitalLetters = true, bool useNumbers = true, bool useSymbols = true, bool useAtLeastOneOfEachCategory = true); - +CPP_UTILITIES_EXPORT void generateRandomCharacterSequence(char *result, unsigned int length, bool useSmallLetters = true, + bool useCapitalLetters = true, bool useNumbers = true, bool useSymbols = true, bool useAtLeastOneOfEachCategory = true); +CPP_UTILITIES_EXPORT void generateRandomCharacterSequence(char *result, unsigned int length, std::function randomizer, int maximalRandomNumber, + bool useSmallLetters = true, bool useCapitalLetters = true, bool useNumbers = true, bool useSymbols = true, + bool useAtLeastOneOfEachCategory = true); } #endif // RANDOMUTILS_H diff --git a/misc/traits.h b/misc/traits.h index 009cbfe..f9aa088 100644 --- a/misc/traits.h +++ b/misc/traits.h @@ -8,45 +8,37 @@ namespace Traits { /// \cond namespace Detail { - enum class Enabler {}; +enum class Enabler {}; } /// \endcond -template -using Conditional = typename std::conditional::type; +template using Conditional = typename std::conditional::type; -template -struct Bool : std::integral_constant {}; +template struct Bool : std::integral_constant { +}; -template -using Not = Bool; +template using Not = Bool; -template -struct Any : Bool {}; -template -struct Any : Conditional, Any > {}; +template struct Any : Bool { +}; +template struct Any : Conditional, Any > { +}; -template -struct All : Bool {}; -template -struct All : Conditional, Bool > {}; +template struct All : Bool { +}; +template struct All : Conditional, Bool > { +}; -template -using EnableIf = typename std::enable_if::value, Detail::Enabler>::type; -template -using DisableIf = typename std::enable_if::value, Detail::Enabler>::type; +template using EnableIf = typename std::enable_if::value, Detail::Enabler>::type; +template using DisableIf = typename std::enable_if::value, Detail::Enabler>::type; -template -using EnableIfAny = typename std::enable_if::value, Detail::Enabler>::type; -template -using DisableIfAny = typename std::enable_if::value, Detail::Enabler>::type; - -template class Template> -struct IsSpecializationOf : Bool {}; -template