Apply clang-format

testing/bash_completion_debugging
Martchus 5 years ago
parent 7e49d3994f
commit 59e20b1043
  1. 497
      application/argumentparser.cpp
  2. 98
      application/argumentparser.h
  3. 4
      application/argumentparserprivate.h
  4. 24
      application/commandlineutils.cpp
  5. 42
      application/commandlineutils.h
  6. 20
      application/failure.cpp
  7. 4
      application/failure.h
  8. 12
      application/fakeqtconfigarguments.cpp
  9. 5
      application/fakeqtconfigarguments.h
  10. 100
      application/global.h
  11. 156
      chrono/datetime.cpp
  12. 103
      chrono/datetime.h
  13. 4
      chrono/format.h
  14. 3
      chrono/period.cpp
  15. 5
      chrono/period.h
  16. 32
      chrono/timespan.cpp
  17. 52
      chrono/timespan.h
  18. 128
      conversion/binaryconversion.h
  19. 146
      conversion/binaryconversionprivate.h
  20. 16
      conversion/conversionexception.cpp
  21. 4
      conversion/conversionexception.h
  22. 101
      conversion/stringbuilder.h
  23. 116
      conversion/stringconversion.cpp
  24. 160
      conversion/stringconversion.h
  25. 4
      conversion/types.h
  26. 30
      conversion/widen.h
  27. 47
      io/ansiescapecodes.h
  28. 124
      io/binaryreader.cpp
  29. 27
      io/binaryreader.h
  30. 32
      io/binarywriter.cpp
  31. 17
      io/binarywriter.h
  32. 5
      io/bitreader.cpp
  33. 51
      io/bitreader.h
  34. 4
      io/catchiofailure.cpp
  35. 1
      io/catchiofailure.h
  36. 35
      io/copy.h
  37. 40
      io/inifile.cpp
  38. 8
      io/inifile.h
  39. 3
      io/misc.cpp
  40. 1
      io/misc.h
  41. 32
      io/nativefilestream.cpp
  42. 15
      io/nativefilestream.h
  43. 95
      io/path.cpp
  44. 31
      io/path.h
  45. 17
      math/math.cpp
  46. 3
      math/math.h
  47. 56
      misc/memory.h
  48. 65
      misc/random.cpp
  49. 8
      misc/random.h
  50. 50
      misc/traits.h
  51. 10
      tests/cppunit.h
  52. 117
      tests/testutils.cpp
  53. 22
      tests/testutils.h

File diff suppressed because it is too large Load Diff

@ -3,11 +3,11 @@
#include "../global.h"
#include <vector>
#include <initializer_list>
#include <functional>
#include <initializer_list>
#include <vector>
#ifdef DEBUG_BUILD
# include <cassert>
#include <cassert>
#endif
class ArgumentParserTests;
@ -27,11 +27,9 @@ CPP_UTILITIES_EXPORT extern std::initializer_list<const char *> 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<const char *> 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<Argument *> ArgumentInitializerList;
typedef std::vector<Argument *> ArgumentVector;
typedef std::function<bool (Argument *)> ArgumentPredicate;
typedef std::function<bool(Argument *)> 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<Argument *> 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<Argument *> parentPath, Argument *parent) :
index(index),
path(parentPath)
inline ArgumentOccurrence::ArgumentOccurrence(std::size_t index, const std::vector<Argument *> 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 <void (const ArgumentOccurrence &)> CallbackFunction;
typedef std::function<void(const ArgumentOccurrence &)> 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<char> abbreviations, std::vector<const char *> 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<std::size_t>(-1)
|| (m_occurrences[occurrence].values.size() >= static_cast<std::size_t>(m_requiredValueCount));
|| (m_occurrences[occurrence].values.size() >= static_cast<std::size_t>(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<const char *> valueNames = std::initializer_list<const char *>());
ConfigValueArgument(const char *name, char abbreviation = '\0', const char *description = nullptr,
std::initializer_list<const char *> valueNames = std::initializer_list<const char *>());
};
/*!
* \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<const char *> valueNames) :
Argument(name, abbreviation, description)
inline ConfigValueArgument::ConfigValueArgument(
const char *name, char abbreviation, const char *description, std::initializer_list<const char *> valueNames)
: Argument(name, abbreviation, description)
{
setCombinable(true);
setRequiredValueCount(valueNames.size());
setValueNames(valueNames);
}
}
#endif // APPLICATION_UTILITIES_ARGUMENTPARSER_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

@ -1,11 +1,11 @@
#include "./commandlineutils.h"
#include <string>
#include <iostream>
#include <string>
#ifdef PLATFORM_WINDOWS
# include <windows.h>
# include <fcntl.h>
#include <fcntl.h>
#include <windows.h>
#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<unique_ptr<char[]> >, vector<char *> > 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<size_t>(argc));
res.second.reserve(static_cast<size_t>(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<char[]>(static_cast<size_t>(requiredSize));
requiredSize = WideCharToMultiByte(CP_UTF8, 0, *i, -1, argv.get(), requiredSize, 0, 0);
if(requiredSize <= 0) {
if (requiredSize <= 0) {
break;
}

@ -6,8 +6,8 @@
#include <ostream>
#ifdef PLATFORM_WINDOWS
# include <memory>
# include <vector>
#include <memory>
#include <vector>
#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<std::unique_ptr<char[]> >, std::vector<char *> > 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<int>(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;

@ -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();
}
}

@ -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

@ -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

@ -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

@ -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
#endif
# if defined(__MINGW32__) || defined(__MINGW64__)
# ifndef PLATFORM_MINGW
#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 <TargetConditionals.h>
# if defined(TARGET_OS_MAC) && TARGET_OS_MAC
# ifndef PLATFORM_MAC
#include <TargetConditionals.h>
#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

@ -1,14 +1,14 @@
#include "./datetime.h"
#include "../conversion/stringconversion.h"
#include "../conversion/stringbuilder.h"
#include "../conversion/stringconversion.h"
#include <sstream>
#include <iomanip>
#include <sstream>
#include <stdexcept>
#if defined(PLATFORM_UNIX)
# include <time.h>
#include <time.h>
#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<typename num1, typename num2, typename num3>
inline bool inRangeInclMax(num1 val, num2 min, num3 max)
template <typename num1, typename num2, typename num3> inline bool inRangeInclMax(num1 val, num2 min, num3 max)
{
return (val) >= (min) && (val) <= (max);
}
template<typename num1, typename num2, typename num3>
inline bool inRangeExclMax(num1 val, num2 min, num3 max)
template <typename num1, typename num2, typename num3> 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, TimeSpan> 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, TimeSpan> 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<uint64>(t.tv_sec) * TimeSpan::ticksPerSecond + static_cast<uint64>(t.tv_nsec) / 100);
return DateTime(
DateTime::unixEpochStart().totalTicks() + static_cast<uint64>(t.tv_sec) * TimeSpan::ticksPerSecond + static_cast<uint64>(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;

@ -5,19 +5,17 @@
#include "../conversion/types.h"
#include <string>
#include <limits>
#include <ctime>
#include <limits>
#include <string>
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);
}