/** * @file include/ActivMiddleware/ActivBase/ActivBase.h * * @brief Global functions from ActivBase. * * ActivBase provides low-level os independent primitives. */ #if (!defined ACTIV_BASE_H) #define ACTIV_BASE_H #include "ActivMiddleware/ActivBase/External.h" #include "ActivMiddleware/ActivBase/StringConversion.h" #include "ActivMiddleware/CxxYZ/type_traits.h" #include "ActivMiddleware/CxxYZ/system_error.h" #include ACTIV_BOOST_INCLUDE(array.hpp) #include ACTIV_BOOST_INCLUDE(format.hpp) #include ACTIV_BOOST_INCLUDE(system/system_error.hpp) #include #include //! Activ namespace. namespace Activ { class MessageBuilder; // --------------------------------------------------------------------------------------------------------------------------------- /** * @brief Log type. */ typedef byte_t LogType; #define ACTIV_DECLARE_LOG_TYPE(value, id, name) const LogType id = value; /** * @brief Log types. * * These are network constant values. */ #define ACTIV_LOG_TYPE_LIST(d) \ d(0, LOG_TYPE_DEBUG, "Debug") \ d(1, LOG_TYPE_INFO, "Info") \ d(2, LOG_TYPE_WARNING, "Warning") \ d(3, LOG_TYPE_ERROR, "Error") /** * @brief Log type constants. */ ACTIV_LOG_TYPE_LIST(ACTIV_DECLARE_LOG_TYPE) const LogType LOG_TYPE_COUNT = 4; #undef ACTIV_DECLARE_LOG_TYPE /** * @brief Log a string. By default the output is sent to stdout, or stderr for LOG_TYPE_ERROR. * * @param type * @param pMessage string to log. */ ACTIV_BASE_API void LogMessage(const LogType type, const char *pMessage); /** * @brief Log a string. By default the output is sent to stdout, or stderr for LOG_TYPE_ERROR. * * @param type * @param message string to log. */ ACTIV_BASE_API void LogMessage(const LogType type, const String &message); /** * @brief Log a BoostFormat message. By default the output is sent to stdout, * or stderr for LOG_TYPE_ERROR. * * @param type * @param format reference to BoostFormat object containing the string to log. */ ACTIV_BASE_API void LogMessage(const LogType type, const BoostFormat &format); /** * @brief Return log type as a string. * * @param logType * * @return String representation of \a logType. */ ACTIV_BASE_API String LogTypeToString(const LogType logType); /** * @brief Return all log types as a pretty-printed string. * * @return All log types as a pretty-printed string. */ ACTIV_BASE_API const String LogTypesToString(); // --------------------------------------------------------------------------------------------------------------------------------- /** * @brief Alert type type. */ typedef byte_t AlertType; #define ACTIV_DECLARE_ALERT_TYPE(value, id, name) const AlertType id = value; /** * @brief Alert types. * * These are network constant values. */ #define ACTIV_ALERT_TYPE_LIST(d) \ d(0, ALERT_TYPE_ISOLATED, "Isolated") \ d(1, ALERT_TYPE_OPEN, "Open") \ d(2, ALERT_TYPE_UPDATE, "Update") \ d(3, ALERT_TYPE_CLOSE, "Close") /** * @brief Alert type constants. */ ACTIV_ALERT_TYPE_LIST(ACTIV_DECLARE_ALERT_TYPE) const AlertType ALERT_TYPE_COUNT = 4; #undef ACTIV_DECLARE_ALERT_TYPE /** * @brief Alert id type. */ typedef uint32_t AlertId; /** * @brief Alert a string. * * @param alertType * @param alertId * @param pMessage string to alert. */ ACTIV_BASE_API void AlertMessage(const AlertType alertType, const AlertId alertId, const char *pMessage); /** * @brief Alert a string. By default the output is sent to stderr. * * @param alertType * @param alertId * @param message string to alert. */ ACTIV_BASE_API void AlertMessage(const AlertType alertType, const AlertId alertId, const String &message); /** * @brief Alert a BoostFormat message. By default the output is sent to stderr. * * @param alertType * @param alertId * @param format reference to BoostFormat object containing the string to alert. */ ACTIV_BASE_API void AlertMessage(const AlertType alertType, const AlertId alertId, const BoostFormat &format); /** * @brief Return alert type as a string. * * @param alertType * * @return String representation of \a alertType. */ ACTIV_BASE_API const String AlertTypeToString(const AlertType alertType); /** * @brief Return alert id as a string. * * @param alertId * * @return String representation of \a alertId. */ ACTIV_BASE_API const String AlertIdToString(const AlertId alertId); // --------------------------------------------------------------------------------------------------------------------------------- //! Standard error category for StatusCodes. class StatusCodeCategoryImpl : public CxxYZ::error_category { public: ACTIV_BASE_API virtual const char *name() const ACTIV_BOOST_NOEXCEPT ACTIV_OVERRIDE; ACTIV_BASE_API virtual std::string message(int errorValue) const ACTIV_OVERRIDE; }; // --------------------------------------------------------------------------------------------------------------------------------- //! Get reference to StatusCodeCategory. ACTIV_BASE_API const CxxYZ::error_category &StatusCodeCategory(); // --------------------------------------------------------------------------------------------------------------------------------- inline CxxYZ::error_code make_error_code(StatusCodeErrc statusCode) { return CxxYZ::error_code(Boost::underlying_cast(statusCode), StatusCodeCategory()); } // --------------------------------------------------------------------------------------------------------------------------------- inline CxxYZ::error_condition make_error_condition(StatusCodeErrc statusCode) { return CxxYZ::error_condition(Boost::underlying_cast(statusCode), StatusCodeCategory()); } // --------------------------------------------------------------------------------------------------------------------------------- // Same again for Boost::system, for cases where Boost::system errors are used. Needs to be in a separate namespace, sadly. namespace BoostSystem { //! Standard error category for StatusCodes. class StatusCodeCategoryImpl : public Boost::system::error_category { public: ACTIV_BASE_API virtual const char *name() const ACTIV_BOOST_NOEXCEPT ACTIV_OVERRIDE; ACTIV_BASE_API virtual std::string message(int errorValue) const ACTIV_OVERRIDE; }; // --------------------------------------------------------------------------------------------------------------------------------- //! Get reference to StatusCodeCategory. ACTIV_BASE_API const Boost::system::error_category &StatusCodeCategory(); // --------------------------------------------------------------------------------------------------------------------------------- inline Boost::system::error_code make_error_code(StatusCodeErrc statusCode) { return Boost::system::error_code(Boost::underlying_cast(statusCode), StatusCodeCategory()); } // --------------------------------------------------------------------------------------------------------------------------------- inline Boost::system::error_condition make_error_condition(StatusCodeErrc statusCode) { return Boost::system::error_condition(Boost::underlying_cast(statusCode), StatusCodeCategory()); } } // namespace BoostSystem // --------------------------------------------------------------------------------------------------------------------------------- /** * @brief Convert a status code to a string. * * @param statusCode see StatusCodes.h. * * @return the string corresponding to @a statusCode. */ ACTIV_BASE_API const String &StatusCodeToString(const StatusCode statusCode); // --------------------------------------------------------------------------------------------------------------------------------- /** * @brief Get a string representation of an OS-dependent error code. * * @param errorCode * * @return A string representation of an os error. */ ACTIV_BASE_API String OsErrorToString(const uint32_t errorCode); /** * @brief Convert OS-dependent error code to Activ StatusCode. * * @param errorCode OS error code. * @param defaultStatusCode the Activ StatusCode to return if there is no suitable conversion of @a errorCode. * * @return Activ StatusCode matching the os error code, or @a defaultStatusCode if there is no mapping. */ ACTIV_BASE_API StatusCode OsErrorToStatusCode(const uint32_t errorCode, const StatusCode defaultStatusCode = STATUS_CODE_FAILURE); /** * @brief Get a string representation of a CRT ("errno") error code. * * @param errorCode * * @return A string representation of an os error. */ ACTIV_BASE_API String CrtErrorToString(const int errorCode); /** * @brief Convert CRT ("errno") error code to Activ StatusCode. * * @param errorCode OS error code. * @param defaultStatusCode the Activ StatusCode to return if there is no suitable conversion of @a errorCode. * * @return Activ StatusCode matching the os error code, or @a defaultStatusCode if there is no mapping. */ ACTIV_BASE_API StatusCode CrtErrorToStatusCode(const int errorCode, const StatusCode defaultStatusCode = STATUS_CODE_FAILURE); /** * @brief Safe sprintf-like function that will not overrun the supplied buffer, * and will always 0 terminate the formatted string. * * @param buff the pointer to the buffer to write the formatted string. * @param buffLen the total length of the buffer pointed to by \a buff (including space for a terminating 0). * @param format pointer to a sprintf-style format string. * @param ... variable arguments for the format string. * * @return the number of characters written to buff, excluding the terminating 0. */ ACTIV_PRINTF_FUNCTION(printf, 3, 4) ACTIV_BASE_API size_t Snprintf(char *buff, const size_t buffLen, const char *format, ...); /** * @brief Safe vsnprintf-like function that will not overrun the supplied buffer, * and will always 0 terminate the formatted string. * * @param buff the pointer to the buffer to write the formatted string. * @param buffLen the total length of the buffer pointed to by \a buff (including space for a terminating 0). * @param format pointer to a sprintf-style format string. * @param args variable arguments for the format string. * * @return the number of characters written to buff, excluding the terminating 0. */ ACTIV_PRINTF_FUNCTION(printf, 3, 0) ACTIV_BASE_API size_t Vsnprintf(char *buff, const size_t buffLen, const char *format, std::va_list args); /** * @brief Safe sprintf-like function that returns a Boost::array with the formatted string. * * Useful for initializing const c-string member variables: * * class SomeClass * { * const Boost::array m_name; * * SomeClass() : * m_name(SnprintfArray<256>("%s", "test")) * }; * * @param pFormat pointer to a sprintf-style format string. * @param ... variable arguments for the format string. * * @return Boost::array with the formatted string. */ template ACTIV_PRINTF_FUNCTION(printf, 1, 2) Boost::array SnprintfArray(const char *pFormat, ...); /** * @brief Make a single string from an array of c-strings. * * @param stringList the array of c-strings. * @param numberOfStrings the number of elements in the @a stringList array. * @param pFinalSeparator the separator to use between the final two elements, e.g. " and ". * * @return A nicely formatted string containing the members of @a stringList in the format: * "string1", "string2", "string3""pFinalSeparator""string4" */ ACTIV_BASE_API const String StringListToString(const char * const stringList[], const size_t numberOfStrings, const char * const pFinalSeparator); /** * @brief Make a single string from a vector of strings. * * @param stringList the vector of strings. * @param finalSeparator the separator to use between the final two elements, e.g. " and ". * * @return A nicely formatted string containing the members of @a stringList in the format: * "string1", "string2", "string3""pFinalSeparator""string4" */ ACTIV_BASE_API const String StringListToString(const std::vector &stringList, const String &finalSeparator = String("")); /** * @brief Build a hex dump of a byte buffer. * * @param pBuffer the pointer to the buffer to dump. * @param bufferLength size of the buffer to dump. * @param bytesPerLine number of bytes to output per line. * @param maxLines the maximum number of lines to output. * * @return Formatted hex dump of the input buffer. */ ACTIV_BASE_API String BufferToHexDumpString(const void * const pBuffer, const size_t bufferLength, const size_t bytesPerLine = 16, const size_t maxLines = 0); //! Get a string containing help text describing the supported hex dump formats of BufferToHexDumpString(). ACTIV_BASE_API String MakeBufferToHexDumpStringHelpText(); /** * @brief Build a hex dump of a byte buffer and write to an output stream. * * @param pBuffer the pointer to the buffer to dump. * @param bufferLength size of the buffer to dump. * @param outStream file stream to dump to. Default is standard out. */ ACTIV_BASE_API void HexDump(const void * const pBuffer, const size_t bufferLength, std::ostream &outStream = std::cout); /** * @brief Convert a hex dump (from BufferToHexDumpString()) to binary. * * @param hexDumpString * @param messageBuilder to append the binary to. * * @return STATUS_CODE_SUCCESS, or and error status. */ ACTIV_BASE_API StatusCode HexDumpStringToBuffer(const String &hexDumpString, MessageBuilder &messageBuilder); /** * @brief Hash a variable length key into a 32-bit value. * * Every bit of the key affects every bit of the return value. * Every 1-bit and 2-bit delta achieves avalanche. About 6*len+35 * instructions. The best hash table sizes are powers of 2. There * is no need to do mod a prime (mod is sooo slow!). If you need * less than 32 bits, use a bitmask. For example, if you need only * 10 bits, do h = (h & hashmask(10));, in which case, the hash table * should have hashsize(10) elements. If you are hashing n strings * (ub1 **)k, do it like this: * for (i=0, h=0; i Boost::array SnprintfArray(const char *pFormat, ...) { Boost::array array; std::va_list args; va_start(args, pFormat); (void) Vsnprintf(array.c_array(), N, pFormat, args); va_end(args); return array; } // --------------------------------------------------------------------------------------------------------------------------------- #if (defined ACTIV_PLATFORM_POSIX) /** * @brief A wrapper around fcntl() to set or clear individual fd flags/status bits. * * @param fd * @param command F_SETFL and F_SETFD are currently supported. * @param flag the flag to set or clear (e.g. O_NONBLOCK). * @param setOrClear true to set the flag, clear to clear it. * * @return fcntl() return values. */ ACTIV_BASE_API int SetOrClearFcntl(const int fd, const int command, const int flag, const bool setOrClear); // --------------------------------------------------------------------------------------------------------------------------------- /** * @brief Duplicate a file descriptor. Ensures close-on-exec is set. * * @param fd * * @return -1 on error (check errno) or the new file descriptor on success. */ ACTIV_BASE_API int DuplicateFd(const int fd); #endif // (defined ACTIV_PLATFORM_POSIX) // --------------------------------------------------------------------------------------------------------------------------------- /** * @brief Get the hostname and port from a string of the form "host:port". * * If there is no "port" portion of the input string, portNumber is reset. * * @param hostAndPort a string of the form "host:port". * @param host reference to a string to receive the host portion of the input string. * @param portNumber reference to a variable to receive the optional port number portion of the input string. * * @retval true. * @retval false hostAndPort could not be parsed. */ ACTIV_BASE_API bool GetHostAndPort(const String &hostAndPort, String &host, Boost::optional &portNumber); // --------------------------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------------------------- //! List of system object (endpoints, heaps) visibility types. #define ACTIV_BASE_TIMESTAMP_MODE(d) \ d(TIMESTAMP_MODE_OFF, "off") \ d(TIMESTAMP_MODE_SOFTWARE, "software") \ d(TIMESTAMP_MODE_HARDWARE, "hardware") //! TimestampMode enumeration. enum TimestampMode { ACTIV_BASE_TIMESTAMP_MODE(ACTIV_DECLARE_ELEMENT_1_WITH_COMMA) NUM_TIMESTAMP_MODES }; // --------------------------------------------------------------------------------------------------------------------------------- //! Convert a TimestampMode to a string. ACTIV_BASE_API String TimestampModeToString(const TimestampMode timestampMode); // --------------------------------------------------------------------------------------------------------------------------------- /** * @brief Convert a string to an TimestampMode. * * @param str * * @return The TimestampMode. * * @throw std::exception if the conversion wasn't possible. */ ACTIV_BASE_API TimestampMode StringToTimestampMode(const String &str); // --------------------------------------------------------------------------------------------------------------------------------- /** * @brief Get the RX timestamping mode. * * @return The TimestampMode * * @throw std::exception * @throw Exception */ ACTIV_BASE_API TimestampMode GetRxTimestampingMode(); } // namespace Activ // --------------------------------------------------------------------------------------------------------------------------------- #if (defined ACTIV_PLATFORM_SOLARIS) /** * @brief Fork and run in the background. * * The calling process will _exit(0) if forked successfully. * * @param nochdir if 0, the forked process will change its working directory to /. * @param noclose if 0, the forked process will redirect stdin, stdout and stderr to /dev/null. * * @return -1 on error. errno set appropriately. */ ACTIV_BASE_API int daemon(int nochdir, int noclose); #endif // (defined ACTIV_PLATFORM_SOLARIS) // --------------------------------------------------------------------------------------------------------------------------------- namespace ACTIV_BOOST_NAMESPACE { namespace system { template<> struct is_error_condition_enum : public ::Activ::CxxYZ::true_type { }; template<> struct is_error_code_enum : public ::Activ::CxxYZ::true_type { }; } // namespace system } // namespace ACTIV_BOOST_NAMESPACE #if (defined ACTIV_CXXYZ_SYSTEM_ERROR_STD_AVAILABLE) namespace std { template<> struct is_error_condition_enum : public ::Activ::CxxYZ::true_type { }; template<> struct is_error_code_enum : public ::Activ::CxxYZ::true_type { }; } // namespace std #endif // (defined ACTIV_CXXYZ_SYSTEM_ERROR_STD_AVAILABLE) #endif // (!defined ACTIV_BASE_H)