Gromacs
2024.3
|
Provides low-level utilities for error handling and other tasks.
This module provides various low-level utilities for tasks such as error handling and string formatting, as well as helper classes and common custom containers to simplify implementation of other code. Contents of the module are discussed in more details under the different headings below. Some of the code in installed headers in the module is intended for use directly from code outside the GROMACS library, but a significant portion is exposed only because other public headers depend on it.
Since this module implements error handling, it should be at the lowest level: it should not depend on other modules. Any functionality needed by the error handling code should also be kept in this module.
Exception classes used in the library are declared in the exceptions.h header file. Most GROMACS-specific exceptions derive from gmx::GromacsException.
This header also declares a GMX_THROW macro that should be used for throwing exceptions. GMX_THROW_WITH_ERRNO is also provided for reporting syscall errors, but its use should be mostly limited to within the library. This header also declares helper functions printFatalErrorMessage(), formatExceptionMessageToString(), and formatExceptionMessageToFile() for creating standard error messages. processExceptionAtExit() provides clean-up code before exiting the program after an exception. To help in cases where bottom-up conversion to C++ is appropriate, macro GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR is also provided to catch all exceptions at C++ to C boundary.
Header file gmxassert.h is also provided for assertions. It declares macros GMX_ASSERT and GMX_RELEASE_ASSERT that should be used for assertions.
The header basedefinitions.h contains common definitions and macros used throughout GROMACS. It includes gmx_bool
for C code, some macros for compiler-specific attributes, and GMX_UNUSED_VALUE and GMX_IGNORE_RETURN_VALUE for handling warnings about unused values.
The header classhelpers.h declares GMX_DISALLOW_COPY_AND_ASSIGN, GMX_DISALLOW_COPY_MOVE_AND_ASSIGN, GMX_DISALLOW_ASSIGN, and GMX_DEFAULT_CONSTRUCTORS macros for class declarations.
The header flags.h implements a gmx::FlagsTemplate template for better type safety when using bit flag fields.
The header init.h declares gmx::init() and gmx::finalize() for initializing and deinitializing the GROMACS library.
The header arrayref.h implements a gmx::ArrayRef class for exposing a C array or part of a std::vector (basically, any continuous stretch of memory) throuh a std::vector-like interface.
The header stringutil.h declares various string utility routines.
Classes | |
class | gmx::DataFileOptions |
Search parameters for DataFileFinder. More... | |
struct | gmx::DataFileInfo |
Information about a data file found by DataFileFinder::enumerateFiles(). More... | |
class | gmx::DataFileFinder |
Searches data files from a set of paths. More... | |
class | gmx::FixedCapacityVector< typename, size_t > |
Vector that behaves likes std::vector but has fixed capacity. More... | |
class | gmx::ArrayRef< typename > |
STL-like interface to a C array of T (or part of a std container of T). More... | |
class | gmx::ExceptionInfo< Tag, T > |
Stores additional context information for exceptions. More... | |
class | gmx::ExceptionInitializer |
Provides information for Gromacs exception constructors. More... | |
class | gmx::GromacsException |
Base class for all exception objects in Gromacs. More... | |
class | gmx::FileIOError |
Exception class for file I/O errors. More... | |
class | gmx::UserInputError |
Exception class for user input errors. More... | |
class | gmx::InvalidInputError |
Exception class for situations where user input cannot be parsed/understood. More... | |
class | gmx::InconsistentInputError |
Exception class for situations where user input is inconsistent. More... | |
class | gmx::ToleranceError |
Exception class when a specified tolerance cannot be achieved. More... | |
class | gmx::SimulationInstabilityError |
Exception class for simulation instabilities. More... | |
class | gmx::InternalError |
Exception class for internal errors. More... | |
class | gmx::APIError |
Exception class for incorrect use of an API. More... | |
class | gmx::RangeError |
Exception class for out-of-range values or indices. More... | |
class | gmx::NotImplementedError |
Exception class for use of an unimplemented feature. More... | |
class | gmx::ParallelConsistencyError |
Exception class for use when ensuring that MPI ranks to throw in a coordinated fashion. More... | |
class | gmx::ModularSimulatorError |
Exception class for modular simulator. More... | |
class | gmx::FlagsTemplate< FlagType > |
Template class for typesafe handling of combination of flags. More... | |
struct | gmx::InstallationPrefixInfo |
Provides information about installation prefix (see IProgramContext::installationPrefix()). More... | |
class | gmx::IProgramContext |
Provides context information about the program that is calling the library. More... | |
class | gmx::StringFormatter |
Function object that wraps a call to formatString() that expects a single conversion argument, for use with algorithms. More... | |
class | gmx::IdentityFormatter |
Function object to implement the same interface as StringFormatter to use with strings that should not be formatted further. More... | |
class | gmx::EqualCaseInsensitive |
Function object for comparisons with equalCaseInsensitive . More... | |
class | gmx::TextLineWrapperSettings |
Stores settings for line wrapping. More... | |
class | gmx::TextLineWrapper |
Wraps lines to a predefined length. More... | |
Macros | |
#define | GMX_LOG(logger) |
Helper to log information using gmx::MDLogger. More... | |
#define | gmx_used_in_debug |
Attribute to explicitly indicate that a parameter or locally scoped variable is used just in debug mode. | |
#define | GMX_UNUSED_VALUE(value) (void)value |
Macro to explicitly ignore an unused value. More... | |
#define | GMX_IGNORE_RETURN_VALUE(call) ::gmx::internal::ignoreValueHelper(call) |
Macro to explicitly ignore a return value of a call. More... | |
#define | GMX_DISALLOW_COPY_AND_ASSIGN(ClassName) |
Macro to declare a class non-copyable and non-assignable. More... | |
#define | GMX_DISALLOW_COPY_MOVE_AND_ASSIGN(ClassName) |
Macro to declare a class non-copyable, non-movable, non-copy-assignable and non-move-assignable. More... | |
#define | GMX_DISALLOW_ASSIGN(ClassName) ClassName& operator=(const ClassName&) = delete |
Macro to declare a class non-assignable. More... | |
#define | GMX_DEFAULT_CONSTRUCTORS(ClassName) |
Macro to declare default constructors. More... | |
#define | GMX_CURRENT_FUNCTION "(unknown)" |
Expands to a string that provides the name of the current function. | |
#define | GMX_THROW(e) throw(e) << gmx::ExceptionInfoLocation(gmx::ThrowLocation(GMX_CURRENT_FUNCTION, __FILE__, __LINE__)) |
Macro for throwing an exception. More... | |
#define | GMX_THROW_WITH_ERRNO(e, syscall, err) |
Macro for throwing an exception based on errno. More... | |
#define | GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR catch (const std::exception& ex) { ::gmx::processExceptionAsFatalError(ex); } |
Macro for catching exceptions at C++ -> C boundary. More... | |
#define | GMX_RELEASE_ASSERT(condition, msg) |
Macro for asserts that should also be present in the release version. More... | |
#define | GMX_ASSERT(condition, msg) GMX_RELEASE_ASSERT(condition, msg) |
Macro for debug asserts. More... | |
#define | gmx_format(archetype, string_index, first_to_check) |
GCC like function format attribute. More... | |
#define | gmx_fmtstr |
MSVC like function format attribute. More... | |
Typedefs | |
typedef ExceptionInfo< struct ExceptionInfoErrno_, int > | gmx::ExceptionInfoErrno |
Stores errno value that triggered the exception. | |
typedef ExceptionInfo< struct ExceptionInfoApiFunc_, const char * > | gmx::ExceptionInfoApiFunction |
Stores the function name that returned the errno in ExceptionInfoErrno. | |
typedef ExceptionInfo< struct ExceptionInfoLocation_, ThrowLocation > | gmx::ExceptionInfoLocation |
Stores the location where the exception was thrown. | |
Enumerations | |
enum | gmx::ErrorCode { gmx::eeOK, gmx::eeOutOfMemory, gmx::eeFileNotFound, gmx::eeFileIO, gmx::eeInvalidInput, gmx::eeInconsistentInput, gmx::eeTolerance, gmx::eeInstability, gmx::eeNotImplemented, gmx::eeInvalidValue, gmx::eeInvalidCall, gmx::eeInternalError, gmx::eeAPIError, gmx::eeRange, gmx::eeParallelConsistency, gmx::eeModularSimulator, gmx::eeUnknownError } |
Possible error return codes from Gromacs functions. More... | |
Functions | |
const char * | gmx::getErrorCodeString (int errorcode) |
Returns a short string description of an error code. More... | |
template<typename T , int N> | |
constexpr int | asize (T(&)[N]) |
Calculates the number of elements in a static array at compile time. | |
int | gmx_omp_get_max_threads () |
Returns an integer equal to or greater than the number of threads that would be available if a parallel region without num_threads were defined at that point in the code. More... | |
int | gmx_omp_get_num_procs () |
Returns the number of processors available when the function is called. More... | |
int | gmx_omp_get_thread_num () |
Returns the thread number of the thread executing within its thread team. More... | |
void | gmx_omp_set_num_threads (int num_threads) |
Sets the number of threads in subsequent parallel regions, unless overridden by a num_threads clause. More... | |
bool | gmx_omp_check_thread_affinity (char **message) |
Check for externally set thread affinity to avoid conflicts with GROMACS internal setting. More... | |
void | gmx::init (int *argc, char ***argv) |
Initializes the GROMACS library. More... | |
void | gmx::finalize () |
Deinitializes the GROMACS library. More... | |
int | gmx_gethostname (char *buf, size_t len) |
Gets the hostname as given by gethostname(), if available. More... | |
int | gmx_getpid () |
Returns the process ID of the current process. More... | |
int | gmx_getuid () |
Returns the current user ID, or -1 if not available. More... | |
int | gmx_getusername (char *buf, size_t len) |
Gets the current user name, if available. More... | |
std::string | gmx_ctime_r (const time_t *clock) |
Portable version of ctime_r. More... | |
std::string | gmx_format_current_time () |
Gets the current time as a string. More... | |
int | gmx_set_nice (int level) |
Wrapper for nice(). More... | |
template<typename T > | |
void | gmx::swap (ArrayRef< T > &a, ArrayRef< T > &b) |
Simple swap method for ArrayRef objects. More... | |
template<typename T > | |
std::vector< T > | gmx::copyOf (const ArrayRef< const T > &arrayRef) |
Return a vector that is a copy of an ArrayRef. More... | |
const char * | gmx_version () |
Version string, containing the version, date, and abbreviated hash. More... | |
const char * | gmx_version_git_full_hash () |
Full git hash of the latest commit. More... | |
const char * | gmx_version_git_central_base_hash () |
Full git hash of the latest commit in a central GROMACS repository. More... | |
void | gmx_is_double_precision () |
Defined if libgromacs has been compiled in double precision. More... | |
void | gmx_is_single_precision () |
Defined if libgromacs has been compiled in single/mixed precision. More... | |
template<class Exception , class Tag , class T > | |
std::enable_if_t < std::is_base_of < GromacsException, Exception > ::value, Exception > | gmx::operator<< (Exception ex, const ExceptionInfo< Tag, T > &item) |
Associates extra information with an exception. More... | |
void | gmx::printFatalErrorMessage (FILE *fp, const std::exception &ex) |
Formats a standard fatal error message for reporting an exception. More... | |
std::string | gmx::formatExceptionMessageToString (const std::exception &ex) |
Formats an error message for reporting an exception. More... | |
void | gmx::formatExceptionMessageToFile (FILE *fp, const std::exception &ex) |
Formats an error message for reporting an exception. More... | |
void | gmx::formatExceptionMessageToWriter (TextWriter *writer, const std::exception &ex) |
Formats an error message for reporting an exception. More... | |
int | gmx::processExceptionAtExit (const std::exception &ex) |
Handles an exception that is causing the program to terminate. More... | |
void | gmx::processExceptionAsFatalError (const std::exception &ex) |
Helper function for terminating the program on an exception. More... | |
const DataFileFinder & | gmx::getLibraryFileFinder () |
Gets a finder for locating data files from share/top/. More... | |
const IProgramContext & | gmx::getProgramContext () |
Returns the global IProgramContext instance. More... | |
void | gmx::setProgramContext (const IProgramContext *context) |
Sets the global IProgramContext instance. More... | |
static bool | gmx::isNullOrEmpty (const char *str) |
Tests whether a string is null or empty. More... | |
static bool | gmx::startsWith (const std::string &str, const std::string &prefix) |
Tests whether a string starts with another string. More... | |
static bool | gmx::startsWith (const char *str, const char *prefix) |
Tests whether a string starts with another string. More... | |
bool | gmx::endsWith (const char *str, const char *suffix) |
Tests whether a string ends with another string. More... | |
static bool | gmx::endsWith (const std::string &str, const char *suffix) |
Tests whether a string ends with another string. More... | |
static bool | gmx::contains (const std::string &str, const char *substr) |
Tests whether a string contains another as a substring. More... | |
static bool | gmx::contains (const std::string &str, const std::string &substr) |
Tests whether a string contains another as a substring. More... | |
std::size_t | gmx::countWords (const char *s) |
Returns number of space-separated words in zero-terminated char ptr. More... | |
std::size_t | gmx::countWords (const std::string &str) |
Returns the number of space-separated words in a string object. More... | |
static bool | gmx::endsWith (const std::string &str, const std::string &suffix) |
Tests whether a string ends with another string. More... | |
std::string | gmx::stripSuffixIfPresent (const std::string &str, const char *suffix) |
Removes a suffix from a string. More... | |
std::string | gmx::stripString (const std::string &str) |
Removes leading and trailing whitespace from a string. More... | |
std::string | gmx::formatString (const char *fmt,...) |
Formats a string (snprintf() wrapper). More... | |
std::string | gmx::formatStringV (const char *fmt, va_list ap) |
Formats a string (vsnprintf() wrapper). More... | |
template<typename InputIterator , typename FormatterType > | |
std::string | gmx::formatAndJoin (InputIterator begin, InputIterator end, const char *separator, const FormatterType &formatter) |
Formats all the range as strings, and then joins them with a separator in between. More... | |
template<typename ContainerType , typename FormatterType > | |
std::string | gmx::formatAndJoin (const ContainerType &container, const char *separator, const FormatterType &formatter) |
Formats all elements of the container as strings, and then joins them with a separator in between. More... | |
template<typename InputIterator > | |
std::string | gmx::joinStrings (InputIterator begin, InputIterator end, const char *separator) |
Joins strings from a range with a separator in between. More... | |
template<typename ContainerType > | |
std::string | gmx::joinStrings (const ContainerType &container, const char *separator) |
Joins strings from a container with a separator in between. More... | |
template<size_t count> | |
std::string | gmx::joinStrings (const char *const (&array)[count], const char *separator) |
Joins strings from an array with a separator in between. More... | |
std::vector< std::string > | gmx::splitString (const std::string &str) |
Splits a string to whitespace separated tokens. More... | |
std::vector< std::string > | gmx::splitDelimitedString (const std::string &str, char delim) |
Splits a string to tokens separated by a given delimiter. More... | |
std::vector< std::string > | gmx::splitAndTrimDelimitedString (const std::string &str, char delim) |
Splits str to tokens separated by delimiter delim . Removes leading and trailing whitespace from those strings with std::isspace. More... | |
std::string | gmx::replaceAll (const std::string &input, const char *from, const char *to) |
Replace all occurrences of a string with another string. More... | |
std::string | gmx::replaceAll (const std::string &input, const std::string &from, const std::string &to) |
Replace all occurrences of a string with another string. More... | |
std::string | gmx::replaceAllWords (const std::string &input, const char *from, const char *to) |
Replace whole words with others. More... | |
std::string | gmx::replaceAllWords (const std::string &input, const std::string &from, const std::string &to) |
Replace whole words with others. More... | |
bool | gmx::equalCaseInsensitive (const std::string &source, const std::string &target) |
Return whether two strings are equal, ignoring case. More... | |
bool | gmx::equalIgnoreDash (const std::string &source, const std::string &target) |
Return whether too strings are case sensitive equal, ignoring dashes. | |
bool | gmx::equalCaseInsensitive (const std::string &source, const std::string &target, size_t maxLengthOfComparison) |
Checks if at most maxLengthOfComparison characters of two strings match case insensitive. More... | |
std::string | gmx::toUpperCase (const std::string &text) |
Makes the string uppercase. More... | |
std::string | gmx::toLowerCase (const std::string &text) |
Makes the string lowercase. More... | |
Directories | |
directory | utility |
Low-Level Utilities (utility) | |
Files | |
file | errorcodes.h |
Declares error codes and related functions for fatal error handling. | |
file | alignedallocator.h |
Declares allocation policy classes and allocators that are used to make library containers compatible with alignment requirements of particular hardware, e.g. memory operations for SIMD or accelerators. | |
file | allocator.h |
Declares gmx::Allocator template whose allocation functionality is configured both by type of object allocated and a policy class that configures the necessary matching malloc and free operation. | |
file | arraysize.h |
Provides asize() function for calculating the static size of an array at compile time. | |
file | cstringutil.h |
Generic C string handling functions. | |
file | datafilefinder.h |
Declares gmx::DataFileFinder and related classes. | |
file | fatalerror.h |
Declares fatal error handling and debugging routines for C code. | |
file | fixedcapacityvector.h |
Declares gmx::FixedCapacityVector. | |
file | init.h |
Declares functions for initializing the GROMACS library. | |
file | stringtoenumvalueconverter.h |
Defines helper function object for class enumerations. | |
file | utility.h |
Public API convenience header for low-level utilities. | |
file | arrayref.h |
Declares gmx::ArrayRef. | |
file | basedefinitions.h |
Basic types and macros used throughout GROMACS. | |
file | baseversion.h |
Declares functions to get basic version information. | |
file | classhelpers.h |
Declares common utility classes and macros. | |
file | current_function.h |
Declares GMX_CURRENT_FUNCTION for getting the current function name. | |
file | enumerationhelpers.h |
Defines helper types for class enumerations. | |
file | exceptions.h |
Declares common exception classes and macros for fatal error handling. | |
file | fileptr.h |
Declares guard pointer for RAII-style handling of cstdio FILE pointers. | |
file | flags.h |
Declares gmx::FlagsTemplate. | |
file | futil.h |
Low-level wrappers for OS-specific file handling with some GROMACS customizations. | |
file | gmxassert.h |
Defines assert macros customized for Gromacs. | |
file | listoflists.h |
Declares gmx::ListOfLists. | |
file | programcontext.h |
Declares gmx::IProgramContext and related methods. | |
file | range.h |
Declares gmx::Range. | |
file | real.h |
Declares real and related constants. | |
file | smalloc.h |
C-style memory allocation routines for GROMACS. | |
file | stringutil.h |
Declares common string utility and formatting routines. | |
file | unique_cptr.h |
Declares gmx::unique_cptr and gmx::sfree_guard. | |
#define GMX_ASSERT | ( | condition, | |
msg | |||
) | GMX_RELEASE_ASSERT(condition, msg) |
Macro for debug asserts.
If NDEBUG is defined, this macro expands to nothing. If it is not defined, it will work exactly like GMX_RELEASE_ASSERT.
#define GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR catch (const std::exception& ex) { ::gmx::processExceptionAsFatalError(ex); } |
Macro for catching exceptions at C++ -> C boundary.
This macro is intended for uniform handling of exceptions when C++ code is called from C code within Gromacs. Since most existing code is written using the assumption that fatal errors terminate the program, this macro implements this behavior for exceptions. It should only be used in cases where the error cannot be propagated upwards using return values or such.
Having this as a macro instead of having the same code in each place makes it easy to 1) find all such locations in the code, and 2) change the exact behavior if needed.
Usage:
#define GMX_DEFAULT_CONSTRUCTORS | ( | ClassName | ) |
Macro to declare default constructors.
Intended for copyable interfaces or bases classes which require to create custom destructor (e.g. protected or virtual) but need the default constructors.
#define GMX_DISALLOW_ASSIGN | ( | ClassName | ) | ClassName& operator=(const ClassName&) = delete |
Macro to declare a class non-assignable.
For consistency, should appear last in the class declaration.
#define GMX_DISALLOW_COPY_AND_ASSIGN | ( | ClassName | ) |
Macro to declare a class non-copyable and non-assignable.
For consistency, should appear last in the class declaration.
#define GMX_DISALLOW_COPY_MOVE_AND_ASSIGN | ( | ClassName | ) |
Macro to declare a class non-copyable, non-movable, non-copy-assignable and non-move-assignable.
For consistency, should appear last in the class declaration.
#define gmx_fmtstr |
MSVC like function format attribute.
Does type checking for printf like format strings in MSVC style. Attribute has to be placed before format string.
#define gmx_format | ( | archetype, | |
string_index, | |||
first_to_check | |||
) |
GCC like function format attribute.
The format attribute specifies that a function takes printf, scanf, ... style arguments that should be type-checked against a format string. The attribute has to be placed after the function. This attribute is only valid for function declarations and not function definitions (GCC limitation). For member functions the implicit this
pointer is included in the argument count.
#define GMX_IGNORE_RETURN_VALUE | ( | call | ) | ::gmx::internal::ignoreValueHelper(call) |
Macro to explicitly ignore a return value of a call.
Mainly meant for ignoring values of functions declared with __attribute__((warn_unused_return))
. Makes it easy to find those places if they need to be fixed, and document the intent in cases where the return value really can be ignored. It also makes it easy to adapt the approach so that they don't produce warnings. A cast to void doesn't remove the warning in gcc, while adding a dummy variable can cause warnings about an unused variable.
#define GMX_LOG | ( | logger | ) |
Helper to log information using gmx::MDLogger.
logger | LogLevelHelper instance to use for logging. |
Used as
and ensures that the code to format the output is only executed when the output goes somewhere.
See LogEntryWriter for functions that can be used with the macro (such as the appendText() in the example).
#define GMX_RELEASE_ASSERT | ( | condition, | |
msg | |||
) |
Macro for asserts that should also be present in the release version.
Regardless of NDEBUG, this macro checks condition
, and if it is not true, it calls the assert handler.
Although this macro currently calls abort() if the assertion fails, it should only be used in a context where it is safe to throw an exception to keep the option open.
#define GMX_THROW | ( | e | ) | throw(e) << gmx::ExceptionInfoLocation(gmx::ThrowLocation(GMX_CURRENT_FUNCTION, __FILE__, __LINE__)) |
Macro for throwing an exception.
[in] | e | Exception object to throw. |
Using this macro instead of throw
directly makes it possible to uniformly attach information into the exception objects. e
should evaluate to an instance of an object derived from GromacsException.
Basic usage:
#define GMX_THROW_WITH_ERRNO | ( | e, | |
syscall, | |||
err | |||
) |
Macro for throwing an exception based on errno.
[in] | e | Exception object to throw. |
[in] | syscall | Name of the syscall that returned the error. |
[in] | err | errno value returned by the syscall. |
This macro provides a convenience interface for throwing an exception to report an error based on a errno value. In addition to adding the necessary information to the exception object, the macro also ensures that errno
is evaluated before, e.g., the constructor of e
may call other functions that could overwrite the errno value. e
should evaluate to an instance of an object derived from GromacsException.
Typical usage (note that gmx::File wraps this particular case):
#define GMX_UNUSED_VALUE | ( | value | ) | (void)value |
Macro to explicitly ignore an unused value.
enum gmx::ErrorCode |
Possible error return codes from Gromacs functions.
Enumerator | |
---|---|
eeOK |
Zero for successful return. |
eeOutOfMemory |
Not enough memory to complete operation. |
eeFileNotFound |
Provided file could not be opened. |
eeFileIO |
System I/O error. |
eeInvalidInput |
Invalid user input (could not be understood). |
eeInconsistentInput |
Invalid user input (conflicting or unsupported settings). |
eeTolerance |
Requested tolerance cannot be achieved. |
eeInstability |
Simulation instability detected. |
eeNotImplemented |
Requested feature not yet implemented. |
eeInvalidValue |
Input value violates API specification. |
eeInvalidCall |
Invalid routine called or wrong calling sequence detected. |
eeInternalError |
Internal consistency check failed. |
eeAPIError |
API specification was violated. |
eeRange |
Range consistency check failed. |
eeParallelConsistency |
Parallel consistency check failed. |
eeModularSimulator |
Error specific for modular simulator. |
eeUnknownError |
Unknown error detected. |
|
inlinestatic |
Tests whether a string contains another as a substring.
[in] | str | String to process. |
[in] | substr | Substring to find. |
str
contains substr
.Does not throw.
|
inlinestatic |
Tests whether a string contains another as a substring.
[in] | str | String to process. |
[in] | substr | Substring to find. |
str
contains substr
.Does not throw.
std::vector<T> gmx::copyOf | ( | const ArrayRef< const T > & | arrayRef | ) |
Return a vector that is a copy of an ArrayRef.
This makes it convenient, clear, and performant (the compiler will either do RVO to elide the temporary, or invoke the move constructor taking the unnamed temporary) to write a declaration like
auto v = copyOf(arrayRef);
std::size_t gmx::countWords | ( | const char * | s | ) |
Returns number of space-separated words in zero-terminated char ptr.
s | Character pointer to zero-terminated, which will not be changed. |
std::size_t gmx::countWords | ( | const std::string & | str | ) |
Returns the number of space-separated words in a string object.
str | Reference to string object, which will not be changed. |
bool gmx::endsWith | ( | const char * | str, |
const char * | suffix | ||
) |
Tests whether a string ends with another string.
[in] | str | String to process. |
[in] | suffix | Suffix to find. |
str
ends with suffix
.Returns true if suffix
is NULL or empty. Does not throw.
|
inlinestatic |
Tests whether a string ends with another string.
[in] | str | String to process. |
[in] | suffix | Suffix to find. |
str
ends with suffix
.Returns true if suffix
is NULL or empty. Does not throw.
|
inlinestatic |
Tests whether a string ends with another string.
[in] | str | String to process. |
[in] | suffix | Suffix to find. |
str
ends with suffix
.Returns true if suffix
is NULL or empty. Does not throw.
bool gmx::equalCaseInsensitive | ( | const std::string & | source, |
const std::string & | target | ||
) |
Return whether two strings are equal, ignoring case.
Checks if two strings have the same length and if all characters in them match when compared case insensitive. Characters are converted by using std::tolower.
[in] | source | Search string to compare against target . |
[in] | target | String to be matched to source . |
bool gmx::equalCaseInsensitive | ( | const std::string & | source, |
const std::string & | target, | ||
size_t | maxLengthOfComparison | ||
) |
Checks if at most maxLengthOfComparison
characters of two strings match case insensitive.
The function tests two strings source
and target
to see if at most maxLengthOfComparison
characters match between the two. If fewer characters are present in source
, only the maximum number of characters in source
will be compared instead. In this case both source
and target
also need to have the same length, or the strings will compare as false, even if target
matches source
over the length of source
.
If maxLengthOfComparison
is 0, the function always returns true. Characters are converted by using std::tolower.
[in] | source | Search string to compare against target . |
[in] | target | String to be matched to source . |
[in] | maxLengthOfComparison | The maximum string length to compare. |
void gmx::finalize | ( | ) |
Deinitializes the GROMACS library.
Decrements the initialization counter, and calls MPI_Finalize() if GROMACS is compiled with MPI support and the counter has reached zero. In that case, it is not possible to reinitialize GROMACS after calling this function. Instead, call gmx::init() at a higher level, and note that calls to init can be nested safely.
std::string gmx::formatAndJoin | ( | InputIterator | begin, |
InputIterator | end, | ||
const char * | separator, | ||
const FormatterType & | formatter | ||
) |
Formats all the range as strings, and then joins them with a separator in between.
[in] | begin | Iterator the beginning of the range to join. |
[in] | end | Iterator the end of the range to join. |
[in] | separator | String to put in between the joined strings. |
[in] | formatter | Function object to format the objects in container as strings |
begin
to end
formatted as strings and concatenated with separator
between each pair. std::bad_alloc | if out of memory. |
std::string gmx::formatAndJoin | ( | const ContainerType & | container, |
const char * | separator, | ||
const FormatterType & | formatter | ||
) |
Formats all elements of the container as strings, and then joins them with a separator in between.
[in] | container | Objects to join. |
[in] | separator | String to put in between the joined strings. |
[in] | formatter | Function object to format the objects in container as strings |
container
formatted as strings and concatenated with separator
between each pair. std::bad_alloc | if out of memory. |
void gmx::formatExceptionMessageToFile | ( | FILE * | fp, |
const std::exception & | ex | ||
) |
Formats an error message for reporting an exception.
fp | File to write the message to. | |
[in] | ex | Exception to format. |
std::bad_alloc | if out of memory. |
std::string gmx::formatExceptionMessageToString | ( | const std::exception & | ex | ) |
Formats an error message for reporting an exception.
[in] | ex | Exception to format. |
ex
. std::bad_alloc | if out of memory. |
void gmx::formatExceptionMessageToWriter | ( | TextWriter * | writer, |
const std::exception & | ex | ||
) |
Formats an error message for reporting an exception.
writer | Writer to use for writing the message. | |
[in] | ex | Exception to format. |
std::bad_alloc | if out of memory. |
std::string gmx::formatString | ( | const char * | fmt, |
... | |||
) |
Formats a string (snprintf() wrapper).
std::bad_alloc | if out of memory. |
This function works like sprintf(), except that it returns an std::string instead of requiring a preallocated buffer. Arbitrary length output is supported.
std::string gmx::formatStringV | ( | const char * | fmt, |
va_list | ap | ||
) |
Formats a string (vsnprintf() wrapper).
std::bad_alloc | if out of memory. |
This function works like vsprintf(), except that it returns an std::string instead of requiring a preallocated buffer. Arbitrary length output is supported.
const char * gmx::getErrorCodeString | ( | int | errorcode | ) |
Returns a short string description of an error code.
[in] | errorcode | Error code to retrieve the string for. |
errorcode
.If errorcode
is not one of those defined for gmx::ErrorCode, the string corresponding to eeUnknownError is returned.
This function does not throw.
const DataFileFinder & gmx::getLibraryFileFinder | ( | ) |
Gets a finder for locating data files from share/top/.
If setLibraryFileFinder() has not been called (or a NULL
finder has been set), a default finder is returned. The default finder searches data files from the directory identified by the global program context; it does not respect GMXLIB environment variable. Calling initForCommandLine() sets a finder that respects GMXLIB.
Does not throw.
See setLibraryFileFinder() for thread safety.
const IProgramContext & gmx::getProgramContext | ( | ) |
Returns the global IProgramContext instance.
If nothing has been set with setProgramContext(), returns a default implementation that returns "GROMACS"
for the program and display names, and empty strings for other values. The default implementation never throws.
Does not throw.
See setProgramContext() for thread safety notes. You should not call this method in global deinitialization methods (e.g., destructors of global variables), since it is very difficult to clean up the state correctly in the presence of such calls. For example, initForCommandLine() assumes that such calls do not exist to be able to free the context before exiting.
std::string gmx_ctime_r | ( | const time_t * | clock | ) |
Portable version of ctime_r.
std::bad_alloc | when out of memory. |
std::string gmx_format_current_time | ( | ) |
Gets the current time as a string.
std::bad_alloc | when out of memory. |
int gmx_gethostname | ( | char * | buf, |
size_t | len | ||
) |
Gets the hostname as given by gethostname(), if available.
[out] | buf | Buffer to receive the hostname. |
[in] | len | Length of buffer buf (must be >= 8). |
If the value is not available, "unknown" is returned. name
should have at least size len
.
Does not throw.
int gmx_getpid | ( | ) |
Returns the process ID of the current process.
Does not throw.
int gmx_getuid | ( | ) |
Returns the current user ID, or -1 if not available.
Does not throw.
int gmx_getusername | ( | char * | buf, |
size_t | len | ||
) |
Gets the current user name, if available.
[out] | buf | Buffer to receive the username. |
[in] | len | Length of buffer buf (must be >= 8). |
Does not throw.
void gmx_is_double_precision | ( | ) |
Defined if libgromacs
has been compiled in double precision.
Allows detecting the compiled precision of the library through checking the presence of the symbol, e.g., from autoconf or other types of build systems.
void gmx_is_single_precision | ( | ) |
Defined if libgromacs
has been compiled in single/mixed precision.
Allows detecting the compiled precision of the library through checking the presence of the symbol, e.g., from autoconf or other types of build systems.
bool gmx_omp_check_thread_affinity | ( | char ** | message | ) |
Check for externally set thread affinity to avoid conflicts with GROMACS internal setting.
[out] | message | Receives the message to be shown to the user. |
true
if we can set thread affinity ourselves.The KMP_AFFINITY environment variable is used by Intel, GOMP_CPU_AFFINITY by the GNU compilers (Intel also honors it well). If any of the variables is set, we should honor it and disable the internal pinning.
If this function returns false
, the caller is responsible to disable the pinning, show the message from *message
to the user, and free the memory allocated for *message
. If the return value is true
, *message
is NULL.
int gmx_omp_get_max_threads | ( | ) |
Returns an integer equal to or greater than the number of threads that would be available if a parallel region without num_threads were defined at that point in the code.
Acts as a wrapper for omp_get_max_threads().
int gmx_omp_get_num_procs | ( | ) |
Returns the number of processors available when the function is called.
Acts as a wrapper around omp_get_num_procs().
int gmx_omp_get_thread_num | ( | ) |
Returns the thread number of the thread executing within its thread team.
Acts as a wrapper for omp_get_thread_num().
void gmx_omp_set_num_threads | ( | int | num_threads | ) |
Sets the number of threads in subsequent parallel regions, unless overridden by a num_threads clause.
Acts as a wrapper for omp_set_num_threads().
int gmx_set_nice | ( | int | level | ) |
Wrapper for nice().
Does not throw.
const char* gmx_version | ( | ) |
Version string, containing the version, date, and abbreviated hash.
This can be a plain version if git version info was disabled during the build. The returned string used to start with a literal word VERSION
before GROMACS 2016, but no longer does.
const char* gmx_version_git_central_base_hash | ( | ) |
Full git hash of the latest commit in a central GROMACS repository.
If git version info was disabled during the build, returns an empty string. Also, if the latest commit was from a central repository, the return value is an empty string.
const char* gmx_version_git_full_hash | ( | ) |
Full git hash of the latest commit.
If git version info was disabled during the build, returns an empty string.
void gmx::init | ( | int * | argc, |
char *** | argv | ||
) |
Initializes the GROMACS library.
argc
and argv
are the command line arguments passed to main(). They are allowed to be NULL if GROMACS is not compiled with MPI, MPI_Init() has already been called, or if the MPI library GROMACS is compiled against allows it.
Does not throw.
|
inlinestatic |
Tests whether a string is null or empty.
Does not throw.
std::string gmx::joinStrings | ( | InputIterator | begin, |
InputIterator | end, | ||
const char * | separator | ||
) |
Joins strings from a range with a separator in between.
[in] | begin | Iterator the beginning of the range to join. |
[in] | end | Iterator the end of the range to join. |
[in] | separator | String to put in between the joined strings. |
begin
, end
) concatenated with separator
between each pair. std::bad_alloc | if out of memory. |
std::string gmx::joinStrings | ( | const ContainerType & | container, |
const char * | separator | ||
) |
Joins strings from a container with a separator in between.
[in] | container | Strings to join. |
[in] | separator | String to put in between the joined strings. |
container
concatenated with separator
between each pair. std::bad_alloc | if out of memory. |
std::string gmx::joinStrings | ( | const char *const (&) | array[count], |
const char * | separator | ||
) |
Joins strings from an array with a separator in between.
[in] | array | Array of strings to join. |
[in] | separator | String to put in between the joined strings. |
count | Deduced number of elements in array . |
aray
concatenated with separator
between each pair. std::bad_alloc | if out of memory. |
|
inline |
Associates extra information with an exception.
Exception | Exception type (must be derived from GromacsException). |
Tag | ExceptionInfo tag. |
T | ExceptionInfo value type. |
[in,out] | ex | Exception to associate the information to. |
[in] | item | Information to associate. |
void gmx::printFatalErrorMessage | ( | FILE * | fp, |
const std::exception & | ex | ||
) |
Formats a standard fatal error message for reporting an exception.
[in] | fp | File to format the message to. |
[in] | ex | Exception to format. |
Does not throw. If memory allocation fails or some other error occurs while formatting the error, tries to print a reasonable alternative message.
Normal usage in Gromacs command-line programs is like this:
void gmx::processExceptionAsFatalError | ( | const std::exception & | ex | ) |
Helper function for terminating the program on an exception.
[in] | ex | Exception that is the cause for terminating the program. |
Does not throw, and does not return.
int gmx::processExceptionAtExit | ( | const std::exception & | ex | ) |
Handles an exception that is causing the program to terminate.
[in] | ex | Exception that is the cause for terminating the program. |
This method should be called as the last thing before terminating the program because of an exception. It exists to terminate the program as gracefully as possible in the case of MPI processing (but the current implementation always calls MPI_Abort()).
See printFatalErrorMessage() for example usage.
Does not throw.
std::string gmx::replaceAll | ( | const std::string & | input, |
const char * | from, | ||
const char * | to | ||
) |
Replace all occurrences of a string with another string.
[in] | input | Input string. |
[in] | from | String to find. |
[in] | to | String to use to replace from . |
input
with all occurrences of from
replaced with to
. std::bad_alloc | if out of memory. |
The replacement is greedy and not recursive: starting from the beginning of input
, each match of from
is replaced with to
, and the search for the next match begins after the end of the previous match.
Complexity is O(N), where N is length of output.
std::string gmx::replaceAll | ( | const std::string & | input, |
const std::string & | from, | ||
const std::string & | to | ||
) |
Replace all occurrences of a string with another string.
[in] | input | Input string. |
[in] | from | String to find. |
[in] | to | String to use to replace from . |
input
with all occurrences of from
replaced with to
. std::bad_alloc | if out of memory. |
The replacement is greedy and not recursive: starting from the beginning of input
, each match of from
is replaced with to
, and the search for the next match begins after the end of the previous match.
Complexity is O(N), where N is length of output.
std::string gmx::replaceAllWords | ( | const std::string & | input, |
const char * | from, | ||
const char * | to | ||
) |
Replace whole words with others.
[in] | input | Input string. |
[in] | from | String to find. |
[in] | to | String to use to replace from . |
input
with all from
words replaced with to
. std::bad_alloc | if out of memory. |
Works as replaceAll(), but a match is only considered if it is delimited by non-alphanumeric characters.
std::string gmx::replaceAllWords | ( | const std::string & | input, |
const std::string & | from, | ||
const std::string & | to | ||
) |
Replace whole words with others.
[in] | input | Input string. |
[in] | from | String to find. |
[in] | to | String to use to replace from . |
input
with all from
words replaced with to
. std::bad_alloc | if out of memory. |
Works as replaceAll(), but a match is only considered if it is delimited by non-alphanumeric characters.
void gmx::setProgramContext | ( | const IProgramContext * | context | ) |
Sets the global IProgramContext instance.
[in] | context | Program context to set (can be NULL to restore the default context). |
The library does not take ownership of context
. The provided object must remain valid until the global instance is changed by another call to setProgramContext().
This method is not thread-safe. It must be the first call to the library after gmx::init(), and multi-threaded access is only supported after the call completes. If GROMACS is getting called from multiple threads, or uses multiple threads simultaneously, changing the program context is not supported once it is set. If the context is cleared at the end of the program, the caller must ensure that all other threads have been terminated at this point. These constraints simplify the implementation significantly.
Does not throw.
std::vector< std::string > gmx::splitAndTrimDelimitedString | ( | const std::string & | str, |
char | delim | ||
) |
Splits str
to tokens separated by delimiter delim
. Removes leading and trailing whitespace from those strings with std::isspace.
[in] | str | String to process. |
[in] | delim | Delimiter to use for splitting. |
str
split into tokens at delimiter, with whitespace stripped. std::bad_alloc | if out of memory. |
Unlike splitString(), consecutive delimiters will generate empty tokens, as will leading or trailing delimiters. Empty input will return an empty vector. Input with only whitespace will return a vector of size 1, that contains an empty token.
std::vector< std::string > gmx::splitDelimitedString | ( | const std::string & | str, |
char | delim | ||
) |
Splits a string to tokens separated by a given delimiter.
[in] | str | String to process. |
[in] | delim | Delimiter to use for splitting. |
str
split into tokens at delimiter. std::bad_alloc | if out of memory. |
Unlike splitString(), consecutive delimiters will generate empty tokens, as will leading or trailing delimiters. Empty input will return an empty vector.
std::vector< std::string > gmx::splitString | ( | const std::string & | str | ) |
Splits a string to whitespace separated tokens.
[in] | str | String to process. |
str
split into tokens at each whitespace sequence. std::bad_alloc | if out of memory. |
This function works like split
in Python, i.e., leading and trailing whitespace is ignored, and consecutive whitespaces are treated as a single separator.
|
inlinestatic |
Tests whether a string starts with another string.
[in] | str | String to process. |
[in] | prefix | Prefix to find. |
str
starts with prefix
.Returns true if prefix
is empty. Does not throw.
|
inlinestatic |
Tests whether a string starts with another string.
[in] | str | String to process. |
[in] | prefix | Prefix to find. |
str
starts with prefix
.Returns true if prefix
is empty. Does not throw.
std::string gmx::stripString | ( | const std::string & | str | ) |
Removes leading and trailing whitespace from a string.
[in] | str | String to process. |
str
with leading and trailing whitespaces removed. std::bad_alloc | if out of memory. |
std::string gmx::stripSuffixIfPresent | ( | const std::string & | str, |
const char * | suffix | ||
) |
Removes a suffix from a string.
[in] | str | String to process. |
[in] | suffix | Suffix to remove. |
str
with suffix
removed, or str
unmodified if it does not end with suffix
. std::bad_alloc | if out of memory. |
Returns str
if suffix
is NULL or empty.
void gmx::swap | ( | ArrayRef< T > & | a, |
ArrayRef< T > & | b | ||
) |
Simple swap method for ArrayRef objects.
std::string gmx::toLowerCase | ( | const std::string & | text | ) |
Makes the string lowercase.
[in] | text | Input text. |
text
with all characters transformed to lowercase. std::bad_alloc | if out of memory. |
std::string gmx::toUpperCase | ( | const std::string & | text | ) |
Makes the string uppercase.
[in] | text | Input text. |
text
with all characters transformed to uppercase. std::bad_alloc | if out of memory. |