Gromacs  2016.4
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Classes | Macros | Typedefs | Enumerations | Functions | Directories | Files
Low-Level Utilities (utility)
+ Collaboration diagram for Low-Level Utilities (utility):

Description

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.

Error handling

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.

Basic file handling and streams

The header textstream.h declares interfaces for simple text format streams. Headers filestream.h and stringstream.h provide implementations for these streams for reading/writing files and for writing to in-memory strings.

The header fileredirector.h provides interfaces for redirecting file input and/or output to alternative streams, for use in testing, as well as default implementations for these interfaces that just use the file system.

The header textwriter.h provides gmx::TextWriter for more formatting support when writing to a text stream. Similarly, textreader.h provides more formatting support when reading from a text stream.

The header path.h declares helpers for manipulating paths as strings and for managing directories and files. The fate of this header depends on what is decided in Redmine issue #950.

Implementation helpers

The header basedefinitions.h contains common definitions and macros used throughout GROMACS. It includes fixed-width integer types (gmx_int64_t and friends), 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 implements a gmx::PrivateImplPointer template for easily writing classes that use the private implementation idiom. This header also declares GMX_DISALLOW_COPY_AND_ASSIGN and GMX_DISALLOW_ASSIGN macros for class declarations.

The header flags.h implements a gmx::FlagsTemplate template for better type safety when using bit flag fields.

Other functionality

The header init.h declares gmx::init() and gmx::finalize() for initializing and deinitializing the GROMACS library.

The header arrayref.h implements a gmx::ConstArrayRef 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.

The header gmxmpi.h abstracts away the mechanism of including either MPI or thread-MPI headers depending on compilation options. Similarly, gmxomp.h removes the need to use conditional compilation for code that needs to include omp.h for OpenMP functions.

The header gmxregex.h declares gmx::Regex and regexMatch() for basic regular expression matching using an interface similar to C++11.

The header messagestringcollector.h declares a gmx::MessageStringCollector class for composing messages with context information.

The header sysinfo.h declares gmx_getpid() for getting the current process id.

The header programcontext.h declares a gmx::IProgramContext that is used to initialize and access information about the running program, such as the name and path of the executable. This information is used, e.g., by the error handling code in formatting standard error messages.

The header qsort_threadsafe.h provides a guaranteed threadsafe implementation for qsort().

Author
Teemu Murtola teemu.nosp@m..mur.nosp@m.tola@.nosp@m.gmai.nosp@m.l.com

Classes

class  gmx::AlignedAllocator< T >
 Aligned memory allocator. More...
 
class  gmx::ArrayRef< T >
 STL-like container for an interface to a C array (or part of a std::vector). More...
 
class  gmx::ConstArrayRef< T >
 STL-like container for non-mutable interface to a C array (or part of a std::vector). More...
 
class  gmx::BinaryInformationSettings
 Settings for printBinaryInformation(). More...
 
class  gmx::PrivateImplPointer< Impl >
 Helper class to manage a pointer to a private implementation class. More...
 
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::DirectoryEnumerator
 Lists files in a directory. 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::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::NotImplementedError
 Exception class for use of an unimplemented feature. More...
 
class  gmx::IFileInputRedirector
 Allows overriding file existence checks from code that supports it. More...
 
class  gmx::IFileOutputRedirector
 Allows capturing stdout and file output from code that supports it. More...
 
class  gmx::StandardInputStream
 Text input stream implementation for reading from stdin. More...
 
class  gmx::TextInputFile
 Text input stream implementation for reading from a file. More...
 
class  gmx::TextOutputFile
 Text output stream implementation for writing to a file. More...
 
class  gmx::FlagsTemplate< FlagType >
 Template class for typesafe handling of combination of flags. More...
 
class  gmx::Regex
 Represents a regular expression. More...
 
class  gmx::MessageStringCollector
 Helper class for collecting message strings, optionally with context. More...
 
class  gmx::MessageStringContext
 Convenience class for creating a message context. More...
 
struct  gmx::no_delete< T >
 Deleter for std::shared_ptr that does nothing. 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::scoped_cptr< T, D >
 Stripped-down version of scoped_ptr that uses sfree() or custom deleter. More...
 
class  gmx::StringOutputStream
 Text output stream implementation for writing to an in-memory string. 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::TextLineWrapperSettings
 Stores settings for line wrapping. More...
 
class  gmx::TextLineWrapper
 Wraps lines to a predefined length. More...
 
class  gmx::TextReader
 Reads text from a TextInputStream. More...
 
class  gmx::TextInputStream
 Interface for reading text. More...
 
class  gmx::TextOutputStream
 Interface for writing text. More...
 
class  gmx::TextWriter
 Writes text into a TextOutputStream. More...
 

Macros

#define asize(a)   ((int)(sizeof(a)/sizeof((a)[0])))
 Calculates the static number of elements in an array.
 
#define GMX_UNUSED_VALUE(value)   (void)value
 Macro to explicitly ignore an unused value.
 
#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_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
 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_qsort_threadsafe   qsort
 Threadsafe qsort(). 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::eeInstability, gmx::eeNotImplemented,
  gmx::eeInvalidValue, gmx::eeInvalidCall, gmx::eeInternalError, gmx::eeAPIError,
  gmx::eeRange, gmx::eeCommunication, gmx::eeUnknownError
}
 Possible error return codes from Gromacs functions. More...
 

Functions

template<typename T >
void gmx::swap (ArrayRef< T > &a, ArrayRef< T > &b)
 Simple swap method for ArrayRef objects. More...
 
template<typename T >
void gmx::swap (ConstArrayRef< T > &a, ConstArrayRef< T > &b)
 Simple swap method for ConstArrayRef objects. More...
 
const char * gmx_version (void)
 Version string, containing the version, date, and abbreviated hash. More...
 
const char * gmx_version_git_full_hash (void)
 Full git hash of the latest commit. More...
 
const char * gmx_version_git_central_base_hash (void)
 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...
 
const char * gmx::getErrorCodeString (int errorcode)
 Returns a short string description of an error code. More...
 
template<class Exception , class Tag , class T >
std::enable_if
< std::is_base_of
< GromacsException, Exception >
::value, const Exception & >
::type 
gmx::operator<< (const 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...
 
IFileInputRedirector & gmx::defaultFileInputRedirector ()
 Returns default implementation for IFileInputRedirector. More...
 
IFileOutputRedirector & gmx::defaultFileOutputRedirector ()
 Returns default implementation for IFileOutputRedirector. More...
 
const DataFileFinder & gmx::getLibraryFileFinder ()
 Gets a finder for locating data files from share/top/. More...
 
int gmx_omp_get_max_threads (void)
 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 (void)
 Returns the number of processors available when the function is called. More...
 
int gmx_omp_get_thread_num (void)
 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...
 
gmx_bool gmx_omp_check_thread_affinity (char **message)
 Check for externally set thread affinity to avoid conflicts with GROMACS internal setting. More...
 
static void gmx_pause ()
 Pause for use in a spin-wait loop.
 
bool gmx::regexMatch (const char *str, const Regex &regex)
 Matches a string with a regular expression. More...
 
void gmx::init (int *argc, char ***argv)
 Initializes the GROMACS library. More...
 
void gmx::finalize ()
 Deinitializes the GROMACS library. More...
 
const IProgramContext & gmx::getProgramContext ()
 Returns the global IProgramContext instance. More...
 
void gmx::setProgramContext (const IProgramContext *context)
 Sets the global IProgramContext instance. More...
 
void gmx_qsort (void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *))
 Portable threadsafe sort routine. 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...
 
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...
 
static const char * gmx::boolToString (bool value)
 Converts a boolean to a "true"/"false" string. More...
 
std::vector< std::string > gmx::splitString (const std::string &str)
 Splits a string to whitespace separated tokens. 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...
 
int gmx_gethostname (char *buf, size_t len)
 Gets the hostname as given by gethostname(), if available. More...
 
int gmx_getpid (void)
 Returns the process ID of the current process. More...
 
int gmx_getuid (void)
 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...
 
char * gmx_ctime_r (const time_t *clock, char *buf, size_t len)
 Portable version of ctime_r. More...
 
void gmx_format_current_time (char *buf, size_t len)
 Gets the current time as a string. More...
 
int gmx_set_nice (int level)
 Wrapper for nice(). More...
 

Directories

directory utility
 Low-Level Utilities (utility)
 
directory tests
 Unit tests for Low-Level Utilities (utility).
 

Files

file  alignedallocator.h
 Declares gmx::AlignedAllocator that is used to make standard library containers compatible with SIMD contents that require aligned load/store.
 
file  arrayref.h
 Declares gmx::ArrayRef and gmx::ConstArrayRef.
 
file  arraysize.h
 Provides asize() macro for calculating the static size of an array.
 
file  basedefinitions.h
 Basic types and macros used throughout GROMACS.
 
file  basenetwork.h
 Utility functions for basic MPI and network functionality.
 
file  baseversion.h
 Declares functions to get basic version information.
 
file  binaryinformation.h
 Helper functionality for information about the currently running binary.
 
file  bitmask.h
 Declares gmx_bitmask_t and associated functions.
 
file  classhelpers.h
 Declares common utility classes and macros.
 
file  coolstuff.h
 Functionality for printing cool strings.
 
file  cstringutil.h
 Generic C string handling functions.
 
file  current_function.h
 Declares GMX_CURRENT_FUNCTION for getting the current function name.
 
file  datafilefinder.h
 Declares gmx::DataFileFinder and related classes.
 
file  dir_separator.h
 Provides OS-specific directory-name separator.
 
file  directoryenumerator.h
 Declares gmx::DirectoryEnumerator.
 
file  errorcodes.h
 Declares error codes and related functions for fatal error handling.
 
file  exceptions.h
 Declares common exception classes and macros for fatal error handling.
 
file  fatalerror.h
 Declares fatal error handling and debugging routines for C code.
 
file  fileredirector.h
 Declares gmx::IFileOutputRedirector.
 
file  filestream.h
 Declares implementations for textstream.h interfaces for file input/output.
 
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  gmxmpi.h
 Wraps <mpi.h> usage in Gromacs.
 
file  gmxomp.h
 Declares OpenMP wrappers to avoid conditional compilation.
 
file  gmxregex.h
 Declares simple wrapper for regular expression functionality.
 
file  init.h
 Declares functions for initializing the GROMACS library.
 
file  int64_to_int.h
 Low-level utility for converting 64 bit int to int (the size of which is hardware dependent), printing a warning if an overflow will occur.
 
file  messagestringcollector.h
 Declares gmx::MessageStringCollector.
 
file  mutex.h
 Declares C++11-style basic threading primitives (gmx::Mutex, gmx::lock_guard).
 
file  nodelete.h
 Declares no_delete deleter for std::shared_ptr.
 
file  path.h
 Declares functions for OS-independent path handling.
 
file  pleasecite.h
 Declares please_cite() for printing out literature references.
 
file  programcontext.h
 Declares gmx::IProgramContext and related methods.
 
file  qsort_threadsafe.h
 Portable implementation of threadsafe quicksort.
 
file  real.h
 Declares real and related constants.
 
file  scoped_cptr.h
 Declares gmx::scoped_cptr and gmx::scoped_guard_sfree.
 
file  smalloc.h
 C memory allocation routines for GROMACS.
 
file  snprintf.h
 Provide snprintf symbol on all OS (for internal Gromacs use)
 
file  strdb.h
 Declares C functions for reading files with a list of strings.
 
file  stringstream.h
 Declares implementations for textstream.h interfaces for input/output to in-memory strings.
 
file  stringutil.h
 Declares common string utility and formatting routines.
 
file  sysinfo.h
 Declares functions for obtaining information about the operating environment and the current process.
 
file  textreader.h
 Declares gmx::TextReader.
 
file  textstream.h
 Declares interfaces for simple input/output streams.
 
file  textwriter.h
 Declares gmx::TextWriter.
 
file  txtdump.h
 Declares helper functions for dumping basic data structures as text.
 
file  utility.h
 Public API convenience header for low-level utilities.
 

Macro Definition Documentation

#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.

See Also
GMX_RELEASE_ASSERT
#define GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
Value:
catch (const std::exception &ex) { \
}
void processExceptionAsFatalError(const std::exception &ex)
Helper function for terminating the program on an exception.
Definition: exceptions.cpp:597

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)
Value:
ClassName &operator=(const ClassName &) = delete; \
ClassName(const ClassName &) = delete

Macro to declare a class non-copyable and non-assignable.

For consistency, should appear last in the class declaration.

#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_qsort_threadsafe   qsort

Threadsafe qsort().

Expands to gmx_qsort() if Gromacs is built with threading, or system qsort() otherwise.

#define GMX_RELEASE_ASSERT (   condition,
  msg 
)
Value:
((void) ((condition) ? (void)0 : \
::gmx::internal::assertHandler(#condition, msg, \
GMX_CURRENT_FUNCTION, __FILE__, __LINE__)))
#define GMX_CURRENT_FUNCTION
Expands to a string that provides the name of the current function.

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.

Parameters
[in]eException 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:

if (value < 0)
{
GMX_THROW(InconsistentUserInput("Negative values not allowed for value"));
}
#define GMX_THROW_WITH_ERRNO (   e,
  syscall,
  err 
)
Value:
do { \
int stored_errno_ = (err); \
GMX_THROW((e) << gmx::ExceptionInfoErrno(stored_errno_) \
} while (0)
#define GMX_THROW(e)
Macro for throwing an exception.
Definition: exceptions.h:544
Stores additional context information for exceptions.
Definition: exceptions.h:119

Macro for throwing an exception based on errno.

Parameters
[in]eException object to throw.
[in]syscallName of the syscall that returned the error.
[in]errerrno 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):

FILE *fp = fopen("filename.txt", "r");
if (fp == NULL)
{
GMX_THROW(FileIOError("Could not open file"), "fopen", errno);
}

Enumeration Type Documentation

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).

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.

eeCommunication 

Communication consistency check failed.

eeUnknownError 

Unknown error detected.

Function Documentation

static const char* gmx::boolToString ( bool  value)
inlinestatic

Converts a boolean to a "true"/"false" string.

Does not throw.

static bool gmx::contains ( const std::string &  str,
const char *  substr 
)
inlinestatic

Tests whether a string contains another as a substring.

Parameters
[in]strString to process.
[in]substrSubstring to find.
Returns
true if str contains substr.

Does not throw.

static bool gmx::contains ( const std::string &  str,
const std::string &  substr 
)
inlinestatic

Tests whether a string contains another as a substring.

Parameters
[in]strString to process.
[in]substrSubstring to find.
Returns
true if str contains substr.

Does not throw.

std::size_t gmx::countWords ( const char *  s)

Returns number of space-separated words in zero-terminated char ptr.

Parameters
sCharacter pointer to zero-terminated, which will not be changed.
Returns
number of words in string.
Note
This routine is mainly meant to support legacy code in GROMACS. For new source you should try hard to use C++ string objects instead.
std::size_t gmx::countWords ( const std::string &  str)

Returns the number of space-separated words in a string object.

Parameters
strReference to string object, which will not be changed.
Returns
number of words in string.
IFileInputRedirector & gmx::defaultFileInputRedirector ( )

Returns default implementation for IFileInputRedirector.

The returned implementation does not redirect anything, but just uses the file system normally.

Does not throw.

IFileOutputRedirector & gmx::defaultFileOutputRedirector ( )

Returns default implementation for IFileOutputRedirector.

The returned implementation does not redirect anything, but just opens the files at requested locations.

Does not throw.

bool gmx::endsWith ( const char *  str,
const char *  suffix 
)

Tests whether a string ends with another string.

Parameters
[in]strString to process.
[in]suffixSuffix to find.
Returns
true if str ends with suffix.

Returns true if suffix is NULL or empty. Does not throw.

static bool gmx::endsWith ( const std::string &  str,
const char *  suffix 
)
inlinestatic

Tests whether a string ends with another string.

Parameters
[in]strString to process.
[in]suffixSuffix to find.
Returns
true if str ends with suffix.

Returns true if suffix is NULL or empty. Does not throw.

static bool gmx::endsWith ( const std::string &  str,
const std::string &  suffix 
)
inlinestatic

Tests whether a string ends with another string.

Parameters
[in]strString to process.
[in]suffixSuffix to find.
Returns
true if str ends with suffix.

Returns true if suffix is NULL or empty. Does not throw.

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.

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.

Parameters
[in]beginIterator the beginning of the range to join.
[in]endIterator the end of the range to join.
[in]separatorString to put in between the joined strings.
[in]formatterFunction object to format the objects in container as strings
Returns
All objects in the range from begin to end formatted as strings and concatenated with separator between each pair.
Exceptions
std::bad_allocif out of memory.
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.

Parameters
[in]containerObjects to join.
[in]separatorString to put in between the joined strings.
[in]formatterFunction object to format the objects in container as strings
Returns
All objects from container formatted as strings and concatenated with separator between each pair.
Exceptions
std::bad_allocif out of memory.
void gmx::formatExceptionMessageToFile ( FILE *  fp,
const std::exception &  ex 
)

Formats an error message for reporting an exception.

Parameters
fpFile to write the message to.
[in]exException to format.
Exceptions
std::bad_allocif out of memory.
std::string gmx::formatExceptionMessageToString ( const std::exception &  ex)

Formats an error message for reporting an exception.

Parameters
[in]exException to format.
Returns
Formatted string containing details of ex.
Exceptions
std::bad_allocif out of memory.
void gmx::formatExceptionMessageToWriter ( TextWriter *  writer,
const std::exception &  ex 
)

Formats an error message for reporting an exception.

Parameters
writerWriter to use for writing the message.
[in]exException to format.
Exceptions
std::bad_allocif out of memory.
std::string gmx::formatString ( const char *  fmt,
  ... 
)

Formats a string (snprintf() wrapper).

Exceptions
std::bad_allocif 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.

const char * gmx::getErrorCodeString ( int  errorcode)

Returns a short string description of an error code.

Parameters
[in]errorcodeError code to retrieve the string for.
Returns
A constant string corresponding to 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/.

Returns
Finder set with setLibraryFileFinder(), or a default finder.

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.

Returns
The context set with setProgramContext().

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.

See Also
IProgramContext
char* gmx_ctime_r ( const time_t *  clock,
char *  buf,
size_t  len 
)

Portable version of ctime_r.

Does not throw.

void gmx_format_current_time ( char *  buf,
size_t  len 
)

Gets the current time as a string.

Parameters
[out]bufBuffer to receive the string.
[in]lenLength of buffer buf (26 characters should be sufficient).

Does not throw.

int gmx_gethostname ( char *  buf,
size_t  len 
)

Gets the hostname as given by gethostname(), if available.

Parameters
[out]bufBuffer to receive the hostname.
[in]lenLength of buffer buf (must be >= 8).
Returns
0 on success, -1 on error.

If the value is not available, "unknown" is returned. name should have at least size len.

Does not throw.

int gmx_getpid ( void  )

Returns the process ID of the current process.

Does not throw.

int gmx_getuid ( void  )

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.

Parameters
[out]bufBuffer to receive the username.
[in]lenLength of buffer buf (must be >= 8).
Returns
0 on success, -1 on error.

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.

gmx_bool gmx_omp_check_thread_affinity ( char **  message)

Check for externally set thread affinity to avoid conflicts with GROMACS internal setting.

Parameters
[out]messageReceives the message to be shown to the user.
Returns
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 ( void  )

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 ( void  )

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 ( void  )

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().

void gmx_qsort ( void *  base,
size_t  nmemb,
size_t  size,
int(*)(const void *, const void *)  compar 
)

Portable threadsafe sort routine.

Parameters
basePointer to first element in list to sort
nmembNumber of elements in list
sizeSize in bytes of each element
comparComparison function that takes two pointers to elements being compared as arguments. The function should return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
int gmx_set_nice ( int  level)

Wrapper for nice().

Does not throw.

const char* gmx_version ( void  )

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 ( void  )

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 ( void  )

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.

Parameters
[in]argcargc value passed to main().
[in]argvargv array passed to main().

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.

static bool gmx::isNullOrEmpty ( const char *  str)
inlinestatic

Tests whether a string is null or empty.

Does not throw.

template<typename InputIterator >
std::string gmx::joinStrings ( InputIterator  begin,
InputIterator  end,
const char *  separator 
)

Joins strings from a range with a separator in between.

Parameters
[in]beginIterator the beginning of the range to join.
[in]endIterator the end of the range to join.
[in]separatorString to put in between the joined strings.
Returns
All strings from (begin, end) concatenated with separator between each pair.
Exceptions
std::bad_allocif out of memory.
template<typename ContainerType >
std::string gmx::joinStrings ( const ContainerType &  container,
const char *  separator 
)

Joins strings from a container with a separator in between.

Parameters
[in]containerStrings to join.
[in]separatorString to put in between the joined strings.
Returns
All strings from container concatenated with separator between each pair.
Exceptions
std::bad_allocif out of memory.
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.

Parameters
[in]arrayArray of strings to join.
[in]separatorString to put in between the joined strings.
Template Parameters
countDeduced number of elements in array.
Returns
All strings from aray concatenated with separator between each pair.
Exceptions
std::bad_allocif out of memory.
template<class Exception , class Tag , class T >
std::enable_if<std::is_base_of<GromacsException, Exception>::value, const Exception &>::type gmx::operator<< ( const Exception &  ex,
const ExceptionInfo< Tag, T > &  item 
)
inline

Associates extra information with an exception.

Template Parameters
ExceptionException type (must be derived from GromacsException).
TagExceptionInfo tag.
TExceptionInfo value type.
Parameters
[in,out]exException to associate the information to.
[in]itemInformation to associate.
void gmx::printFatalErrorMessage ( FILE *  fp,
const std::exception &  ex 
)

Formats a standard fatal error message for reporting an exception.

Parameters
[in]fpFile to format the message to.
[in]exException 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:

int main(int argc, char *argv[])
{
gmx::init(&argc, &argv);
try
{
// The actual code for the program
return 0;
}
catch (const std::exception &ex)
{
}
}
void gmx::processExceptionAsFatalError ( const std::exception &  ex)

Helper function for terminating the program on an exception.

Parameters
[in]exException 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.

Parameters
[in]exException that is the cause for terminating the program.
Returns
Return code to return from main().

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.

bool gmx::regexMatch ( const char *  str,
const Regex &  regex 
)

Matches a string with a regular expression.

Parameters
[in]strString to match.
[in]regexRegular expression to match.
Returns
true if regex matches the whole str.

Does not throw currently, but this is subject to change if/when better error handling is implemented (currently, it returns false if the matching fails, e.g., because of out-of-memory).

std::string gmx::replaceAll ( const std::string &  input,
const char *  from,
const char *  to 
)

Replace all occurrences of a string with another string.

Parameters
[in]inputInput string.
[in]fromString to find.
[in]toString to use to replace from.
Returns
Copy of input with all occurrences of from replaced with to.
Exceptions
std::bad_allocif 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.

Compexity is O(N), where N is length of output.

See Also
replaceAllWords()
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.

Parameters
[in]inputInput string.
[in]fromString to find.
[in]toString to use to replace from.
Returns
Copy of input with all occurrences of from replaced with to.
Exceptions
std::bad_allocif 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.

Compexity is O(N), where N is length of output.

See Also
replaceAllWords()
std::string gmx::replaceAllWords ( const std::string &  input,
const char *  from,
const char *  to 
)

Replace whole words with others.

Parameters
[in]inputInput string.
[in]fromString to find.
[in]toString to use to replace from.
Returns
Copy of input with all from words replaced with to.
Exceptions
std::bad_allocif out of memory.

Works as replaceAll(), but a match is only considered if it is delimited by non-alphanumeric characters.

See Also
replaceAll()
std::string gmx::replaceAllWords ( const std::string &  input,
const std::string &  from,
const std::string &  to 
)

Replace whole words with others.

Parameters
[in]inputInput string.
[in]fromString to find.
[in]toString to use to replace from.
Returns
Copy of input with all from words replaced with to.
Exceptions
std::bad_allocif out of memory.

Works as replaceAll(), but a match is only considered if it is delimited by non-alphanumeric characters.

See Also
replaceAll()
void gmx::setProgramContext ( const IProgramContext *  context)

Sets the global IProgramContext instance.

Parameters
[in]contextProgram 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.

See Also
IProgramContext
std::vector< std::string > gmx::splitString ( const std::string &  str)

Splits a string to whitespace separated tokens.

Parameters
[in]strString to process.
Returns
str split into tokens at each whitespace sequence.
Exceptions
std::bad_allocif 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.

static bool gmx::startsWith ( const std::string &  str,
const std::string &  prefix 
)
inlinestatic

Tests whether a string starts with another string.

Parameters
[in]strString to process.
[in]prefixPrefix to find.
Returns
true if str starts with prefix.

Returns true if prefix is empty. Does not throw.

static bool gmx::startsWith ( const char *  str,
const char *  prefix 
)
inlinestatic

Tests whether a string starts with another string.

Parameters
[in]strString to process.
[in]prefixPrefix to find.
Returns
true if 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.

Parameters
[in]strString to process.
Returns
str with leading and trailing whitespaces removed.
Exceptions
std::bad_allocif out of memory.
std::string gmx::stripSuffixIfPresent ( const std::string &  str,
const char *  suffix 
)

Removes a suffix from a string.

Parameters
[in]strString to process.
[in]suffixSuffix to remove.
Returns
str with suffix removed, or str unmodified if it does not end with suffix.
Exceptions
std::bad_allocif out of memory.

Returns str if suffix is NULL or empty.

template<typename T >
void gmx::swap ( ArrayRef< T > &  a,
ArrayRef< T > &  b 
)

Simple swap method for ArrayRef objects.

See Also
ArrayRef::swap()
template<typename T >
void gmx::swap ( ConstArrayRef< T > &  a,
ConstArrayRef< T > &  b 
)

Simple swap method for ConstArrayRef objects.

See Also
ConstArrayRef::swap()