Remove Activ libs and includes

This commit is contained in:
John Colvin committed 2023-12-15 13:15:08 -05:00
1 parent 28ed30c944
commit 4b718994be
10967 files changed
-2306716

No files matched your search

@@ -1,181 +0,0 @@
/**
* @file include/ActivMiddleware/ActivAgentApplication/AgentApplication.h
*
* @brief Header file for agent application class.
*/
#if (!defined ACTIV_AGENT_APPLICATION_AGENT_APPLICATION_H)
#define ACTIV_AGENT_APPLICATION_AGENT_APPLICATION_H
#include "ActivMiddleware/ActivAgentApplication/External.h"
#include "ActivMiddleware/ActivAgentApplication/TimerService.h"
#include "ActivMiddleware/ActivAgentApplication/LoggerService.h"
#include "ActivMiddleware/ActivAgentApplication/PubSubService.h"
#include "ActivMiddleware/ActivAgentApplication/MonitorService.h"
#include "ActivMiddleware/ActivAgentApplication/DirectoryService.h"
#include "ActivMiddleware/ActivAgentApplication/UiService.h"
#include "ActivMiddleware/ActivAgentApplication/LicenseService.h"
#include "ActivMiddleware/ActivBase/CommandLineParser.h"
#include "ActivMiddleware/ActivFramework/RouterService.h"
#include ACTIV_BOOST_INCLUDE(scoped_ptr.hpp)
//! Activ namespace.
namespace Activ
{
class UiMainComponent;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Agent application class.
*
* The AgentApplication class should be used when creating a shared memory system or stand alone process.
* It provides always on timer, logger, directory, router and pub-sub services.
*/
class AgentApplication : public Application
{
public:
//! Agent settings.
class Settings : public Application::Settings
{
public:
//! Default constructor.
ACTIV_AGENT_APPLICATION_API Settings();
//! Destructor.
ACTIV_AGENT_APPLICATION_API ~Settings();
/**
* @brief Read settings from an ini file.
*
* @param iniFileParser already parsed ini file to get settings from.
*
* @throw Exception
*/
ACTIV_AGENT_APPLICATION_API void Read(const IniFileParser &iniFileParser);
//! Modes for the UiService.
enum UiServiceMode
{
UI_SERVICE_MODE_OFF, ///< No UiService.
UI_SERVICE_MODE_NO_MENU, ///< On, but don't provide a main menu.
UI_SERVICE_MODE_EXTENDED_SHUTDOWN, ///< Regular main menu with shutdown validation.
UI_SERVICE_MODE_QUICK_SHUTDOWN, ///< Regular main menu with no shutdown validation.
UI_SERVICE_MODE_LITE ///< "Lite" main menu.
};
String m_systemVersion; ///< Optional version of the system.
IHeap::Settings m_systemHeapSettings; ///< Properties of the system heap.
String m_serviceLocationIniFile; ///< Service location ini file.
String m_processStartupIniFile; ///< Ini file for processes to launch.
bool m_createSystemLog; ///< Whether to create system log.
UInt m_maxTotalSizeOfBackupFiles; ///< Maximum total size of all system log backup files.
UInt m_systemLogSplitFileSize; ///< Position at which system log should split and move to new file.
UInt m_systemLogNumberOfBackups; ///< Number of past increments (days) for which to keep backup system log files.
bool m_enableTerminateProcessShutdown; ///< Initiate shutdown if SIGTERM/CTRL_CLOSE_EVENT received? Default: false.
UiServiceMode m_uiServiceMode; ///< Mode to run the UiService in.
bool m_isUiRestartEnabled; ///< Show restart option in ui.
// Core service settings.
TimerService::Settings m_timerServiceSettings; ///< Settings for timer service.
LoggerService::Settings m_loggerServiceSettings; ///< Settings for logger service.
RouterService::Settings m_routerServiceSettings; ///< Settings for router service.
PubSubService::Settings m_pubSubServiceSettings; ///< Pubsub service settings.
MonitorService::Settings m_monitorServiceSettings; ///< Monitor service settings.
DirectoryService::Settings m_directoryServiceSettings; ///< Settings for directory service.
UiService::Settings m_uiServiceSettings; ///< Settings for ui service.
LicenseService::Settings m_licenseServiceSettings; ///< Settings for license service.
};
//! Agent command line parser. Provides a common command line parser for ACTIV AgentApplications.
class AgentCommandLineParser : public CommandLineParser
{
public:
//! Default constructor.
ACTIV_AGENT_APPLICATION_API AgentCommandLineParser();
String m_iniFileName; ///< Default: <empty>. Configured file to use.
String m_userName; ///< Default: <empty>. Switch to this user context prior to constructing the AgentApplication (POSIX only).
String m_pidFile; ///< Default: <empty>. File to write the process pid to (POSIX ONLY).
bool m_isDaemon; ///< Default: false. If true start the process as a daemon (POSIX ONLY).
String m_cpuSet; ///< Default: "root". On start attempt to move the process to this cpuset.
bool m_isPrivate; ///< Default: false. If true use MEMORY_MODEL_PRIVATE instead of MEMORY_MODEL_SHARED.
bool m_shouldDisplayVersion; ///< Default: false. If true display ACTIV_MIDDLEWARE_VERSION_STRING and exit.
String m_startCommand; ///< Default: <empty>. The command to use to restart the process if requested.
String m_userContext; ///< Default: <empty>. Context string provided in the system ui field 'User context'.
size_t m_uptimeMilliseconds; ///< Default: 0. If non-zero, shutdown (or restart) the application after this time has elapsed.
String m_uiServiceUrl; ///< Default: UiService::Settings::defaultAccessPoint. The ui service access point to use.
bool m_isRestartEnabled; ///< Default: false. If true process will be restarted on exit.
};
/**
* @brief Create a system.
*
* @param settings agent settings.
* @param componentId the component id.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API AgentApplication(const Settings &settings = Settings(),
const String &componentId = defaultComponentId);
//! Destructor.
ACTIV_AGENT_APPLICATION_API virtual ~AgentApplication() ACTIV_OVERRIDE;
/**
* @brief Configure the default Agent settings used by ACTIV AgentApplications.
*
* @param settings agent settings.
* @param commandLineParser
*
* @throw Exception
* @throw std::exception
* @throw Boost::exception
*/
ACTIV_AGENT_APPLICATION_API static void ConfigureAgentSettings(Settings &settings,
const AgentCommandLineParser &commandLineParser);
/**
* @brief Configure Agent environment used by ACTIV AgentApplications.
*
* @param settings agent settings.
* @param commandLineParser
*
* @throw Exception
* @throw std::exception
* @throw Boost::exception
*/
ACTIV_AGENT_APPLICATION_API static void ConfigureAgentEnvironment(Settings &settings,
const AgentCommandLineParser &commandLineParser);
/**
* @brief Process Agent restart.
*
* @param isRestartEnabled
* @param restartCommand
*/
ACTIV_AGENT_APPLICATION_API static void ProcessAgentRestart(const bool isRestartEnabled, const String &restartCommand);
class Private;
protected:
ACTIV_AGENT_APPLICATION_API virtual StatusCode OnMessage(HeapMessage &message) ACTIV_OVERRIDE;
ACTIV_AGENT_APPLICATION_API virtual StatusCode OnRequest(HeapMessage &request) ACTIV_OVERRIDE;
ACTIV_AGENT_APPLICATION_API virtual void OnCtrlEvent(const CtrlHandler::EventType eventType) ACTIV_OVERRIDE;
ACTIV_AGENT_APPLICATION_API virtual bool CanThreadExit() ACTIV_OVERRIDE;
private:
class UiFunctionality;
Boost::scoped_ptr<Private> m_pPrivate; ///< Hidden implementation details
friend class UiMainComponent;
};
} // namespace Activ
#endif // (!defined ACTIV_AGENT_APPLICATION_AGENT_APPLICATION_H)
@@ -1,110 +0,0 @@
/**
* @file include/ActivMiddleware/ActivAgentApplication/DirectoryService.h
*
* @brief Header file for directory service class.
*/
#if (!defined ACTIV_AGENT_APPLICATION_DIRECTORY_SERVICE_H)
#define ACTIV_AGENT_APPLICATION_DIRECTORY_SERVICE_H
#include "ActivMiddleware/ActivAgentApplication/External.h"
#include "ActivMiddleware/ActivFramework/Service.h"
#include ACTIV_BOOST_INCLUDE(scoped_ptr.hpp)
//! Activ namespace.
namespace Activ
{
//! DirectoryService.
class DirectoryService : private ManagedEndPoint
{
public:
//! Settings.
class Settings
{
public:
//! Default constructor.
ACTIV_AGENT_APPLICATION_API Settings();
/**
* @brief Read settings from an ini file section.
*
* @param sectionIterator iterator to an ini file section.
*
* @throw Exception
*/
ACTIV_AGENT_APPLICATION_API void Read(const IniFileParser::ConstSectionIterator &sectionIterator);
bool m_shouldEnablePubSubMulticast; ///< Default: true. Whether pub-sub over multicast is enabled.
std::vector<String> m_pubSubMulticastAddressList; ///< Default: 233.58.54.255. Comma separated list of pub-sub multicast addresses.
IHeap::Settings m_heapSettings; ///< Heap properties for directory service, default buckets above.
ManagedEndPoint::Settings m_managedEndPointSettings;
String m_serviceAttributes; ///< Attributes for service when publishing existence of this DirectoryService.
std::vector<uint16_t> m_servicePortList; ///< List of TCP ports to attempt to listen on. The list will be randomized and then iterated until a free port is found.
// Discovery of other DirectoryServices.
std::vector<String> m_discoveryAttributeQueryList; ///< Only interested in other DirectoryServices which advertise with attributes that match one of these queries.
size_t m_cleanupServicesTimeout; ///< How long after the connection to a DirectoryService is lost to remove its services, in seconds.
size_t m_ttl; ///< TTL of discovery multicast. Default: 3.
ServiceInstanceList m_remoteDirectoryServiceInstanceList; ///< Configured list of remote directory services to add, pub-sub over multicast must be disabled.
// Conversion of hostnames in attributes.
std::vector<String> m_hostConversionAttributeKeyList; ///< List of attribute keys that might contain hostnames that need converting to ip addresses for remote directories.
std::vector<String> m_urlConversionAttributeKeyList; ///< List of attribute keys that might contain URLs that contain hostnames that need converting to ip addresses for remote directories.
};
//! Ui component.
class UiComponent ACTIV_FINAL : public Activ::UiComponent
{
public:
/**
* @brief Constructor.
*
* @param directoryService object to show menu for.
* @param uiServiceName name of the ui service.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API UiComponent(DirectoryService &directoryService, const String &uiServiceName);
private:
virtual void Run(UiUser &uiUser) ACTIV_OVERRIDE;
DirectoryService & m_directoryService;
// Last member.
Component::Enabler m_componentEnabler;
};
/**
* @brief Constructor.
*
* @param application Application object to attach to.
* @param serviceName name of the service.
* @param settings settings for directory service.
* @param serviceLocationIniFile filename of ini file containing static services.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API DirectoryService(Application &application, const String &serviceName, const Settings &settings,
const String &serviceLocationIniFile);
//! Destructor.
ACTIV_AGENT_APPLICATION_API ~DirectoryService();
class Impl;
private:
static CxxYZ::unique_ptr<DirectoryService::Impl> MakeImpl(DirectoryService &directoryService,
const String &serviceName, const Settings &settings, const String &serviceLocationIniFile);
CxxYZ::unique_ptr<Impl> m_pImpl;
};
} // namespace Activ
#endif // (!defined ACTIV_AGENT_APPLICATION_DIRECTORY_SERVICE_H)
@@ -1,20 +0,0 @@
/**
* @file include/ActivMiddleware/ActivAgentApplication/External.h
*
* @brief Import rules for AgentApplication exports.
*/
#if (!defined ACTIV_AGENT_APPLICATION_EXTERNAL_H)
#define ACTIV_AGENT_APPLICATION_EXTERNAL_H
#if (!defined ACTIV_AGENT_APPLICATION_API)
# if (!defined ACTIV_STATIC)
# define ACTIV_AGENT_APPLICATION_API ACTIV_IMPORT_DLL
# else
# define ACTIV_AGENT_APPLICATION_API ACTIV_IMPORT_LIB
# endif // (!defined ACTIV_STATIC)
#endif // (!defined ACTIV_AGENT_APPLICATION_API)
#include "ActivMiddleware/ActivFramework/ActivFramework.h"
#endif // (!defined ACTIV_AGENT_APPLICATION_EXTERNAL_H)
@@ -1,116 +0,0 @@
/**
* @file include/ActivMiddleware/ActivAgentApplication/LicenseService.h
*
* @brief Header file for the license service class.
*/
#if (!defined ACTIV_AGENT_APPLICATION_LICENSE_SERVICE_H)
#define ACTIV_AGENT_APPLICATION_LICENSE_SERVICE_H
#include "ActivMiddleware/ActivAgentApplication/External.h"
#include <set>
//! Activ namespace.
namespace Activ
{
//! License service class.
class LicenseService : private ManagedEndPoint, public Component
{
public:
using Component::GetApplication;
//! Settings.
class Settings
{
public:
//! Default constructor.
ACTIV_AGENT_APPLICATION_API Settings();
//! Destructor.
ACTIV_AGENT_APPLICATION_API ~Settings();
/**
* @brief Read settings from an ini file section.
*
* @param sectionIterator iterator to an ini file section.
*
* @throw Exception
*/
ACTIV_AGENT_APPLICATION_API void Read(const IniFileParser::ConstSectionIterator &sectionIterator);
typedef std::set<String> SystemNameSet; ///< System name set type.
typedef std::set<String> MacAddressSet; ///< Mac address set type.
typedef std::set<String> ComponentLicenseIdFilterSet; ///< Component license id filter set type.
ACTIV_AGENT_APPLICATION_API static const String defaultLicenseFileName;
String m_licenseFileName; ///< License file name, if exists it is read and overrides all license settings.
IHeap::Settings m_heapSettings; ///< Heap properties for service.
ManagedEndPoint::Settings m_managedEndPointSettings;
// License details, these will not be read from an ini file. They will be overridden if a license file is found.
String m_licenseeName; ///< Licensee name.
SystemNameSet m_systemNameSet; ///< system name set.
MacAddressSet m_macAddressSet; ///< Mac address set.
String m_ipAddress; ///< Ip address.
String m_hostName; ///< Host name.
String m_validFrom; ///< Valid from date.
String m_validTo; ///< Valid to date.
String m_maximumUpTime; ///< Maximum up time.
String m_maximumUpTimeDays; ///< Maximum up time days.
ComponentLicenseIdFilterSet m_componentLicenseIdFilterSet; ///< Component license id filter set.
String m_signature; ///< Digital signature.
};
//! License service ui component.
class UiComponent ACTIV_FINAL : public Activ::UiComponent
{
public:
/**
* @brief Constructor.
*
* @param licenseService the license service to have the ui.
* @param uiServiceName name of the ui service.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API UiComponent(LicenseService &licenseService, const String &uiServiceName);
private:
virtual void Run(UiUser &uiUser) ACTIV_OVERRIDE;
LicenseService & m_licenseService; ///< License service.
// Last member.
Component::Enabler m_componentEnabler;
};
/**
* @brief Constructor.
*
* The constructor creates an endpoint and heap in the system and runs a single thread.
*
* @param application the application the service is to run in.
* @param serviceName the name of the license service.
* @param settings settings for the license service.
*
* @throw Exception
*/
ACTIV_AGENT_APPLICATION_API LicenseService(Application &application, const String &serviceName, const Settings &settings);
//! Destructor.
ACTIV_AGENT_APPLICATION_API ~LicenseService();
class Impl;
private:
ACTIV_AGENT_APPLICATION_API virtual StatusCode OnRequest(HeapMessage &request) ACTIV_OVERRIDE;
Boost::scoped_ptr<Impl> m_pImpl;
};
} // namespace Activ
#endif // (!defined ACTIV_AGENT_APPLICATION_LICENSE_SERVICE_H)
@@ -1,112 +0,0 @@
/**
* @file include/ActivMiddleware/ActivAgentApplication/LoggerService.h
*
* @brief Header file for the logger service class.
*/
#if (!defined ACTIV_AGENT_APPLICATION_LOGGER_SERVICE_H)
#define ACTIV_AGENT_APPLICATION_LOGGER_SERVICE_H
#include "ActivMiddleware/ActivAgentApplication/External.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Logger service class.
*/
class LoggerService : private ManagedEndPoint, public Component
{
public:
using Component::GetApplication;
/**
* @brief Settings.
*/
class Settings
{
public:
/**
* @brief Default constructor.
*/
ACTIV_AGENT_APPLICATION_API Settings();
/**
* @brief Destructor.
*/
ACTIV_AGENT_APPLICATION_API ~Settings();
/**
* @brief Read settings from an ini file section.
*
* @param sectionIterator iterator to an ini file section.
*
* @throw Exception
*/
ACTIV_AGENT_APPLICATION_API void Read(const IniFileParser::ConstSectionIterator &sectionIterator);
IHeap::Settings m_heapSettings; ///< Heap properties for logger service, default buckets above.
ManagedEndPoint::Settings m_managedEndPointSettings;
String m_defaultLogDirectory; ///< Directory to put logs in if none specified, default current.
size_t m_systemLogHistorySize; ///< Number of system log entries to cache.
size_t m_numberOfInactiveDaysBeforeLogPurge; ///< Number of days before an inactive log is cleared.
std::vector<LogType> m_publishLogTypeList; ///< Publish log messages with any of these LogTypes.
};
/**
* @brief Logger service ui component.
*/
class UiComponent ACTIV_FINAL : public Activ::UiComponent
{
public:
/**
* @brief Constructor.
*
* @param loggerService the logger service to have the ui.
* @param uiServiceName name of the ui service.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API UiComponent(LoggerService &loggerService, const String &uiServiceName);
private:
virtual void Run(UiUser &uiUser) ACTIV_OVERRIDE;
LoggerService & m_loggerService;
// Last member.
Component::Enabler m_componentEnabler;
};
/**
* @brief Constructor.
*
* @param application the application the endpoint is running in.
* @param serviceName the name of the logger service.
* @param settings settings for the service.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API LoggerService(Application &application, const String &serviceName, const Settings &settings);
/**
* @brief Destructor.
*/
ACTIV_AGENT_APPLICATION_API ~LoggerService();
class Impl;
protected:
ACTIV_AGENT_APPLICATION_API virtual bool CanThreadExit() ACTIV_OVERRIDE;
ACTIV_AGENT_APPLICATION_API virtual StatusCode OnRequest(HeapMessage &request) ACTIV_OVERRIDE;
ACTIV_AGENT_APPLICATION_API virtual StatusCode OnMessage(HeapMessage &message) ACTIV_OVERRIDE;
private:
Boost::scoped_ptr<Impl> m_pImpl;
};
} // namespace Activ
#endif // (!defined ACTIV_AGENT_APPLICATION_LOGGER_SERVICE_H)
@@ -1,141 +0,0 @@
/**
* @file include/ActivMiddleware/ActivAgentApplication/MonitorService.h
*
* @brief Header file for the monitor service class.
*/
#if (!defined ACTIV_AGENT_APPLICATION_MONITOR_SERVICE_H)
#define ACTIV_AGENT_APPLICATION_MONITOR_SERVICE_H
#include "ActivMiddleware/ActivAgentApplication/External.h"
#include ACTIV_BOOST_INCLUDE(scoped_ptr.hpp)
//! Activ namespace.
namespace Activ
{
/**
* @brief Monitor service class.
*/
class MonitorService : private ManagedEndPoint, public Component
{
public:
using Component::GetApplication;
/**
* @brief Settings.
*/
class Settings
{
public:
/**
* @brief System monitor modes.
*/
enum SystemMonitorMode
{
SYSTEM_MONITOR_MODE_OFF, ///< Disable system monitor.
SYSTEM_MONITOR_MODE_ON, ///< Enable system monitor.
SYSTEM_MONITOR_MODE_ON_WITH_LOG ///< Enable system monitor & generate log file.
};
/**
* @brief Default constructor.
*/
ACTIV_AGENT_APPLICATION_API Settings();
/**
* @brief Destructor.
*/
ACTIV_AGENT_APPLICATION_API ~Settings();
/**
* @brief Read settings from an ini file section.
*
* @param sectionIterator iterator to an ini file section.
*
* @throw Exception
*/
ACTIV_AGENT_APPLICATION_API void Read(const IniFileParser::ConstSectionIterator &sectionIterator);
IHeap::Settings m_heapSettings; ///< Properties of heap to create for monitor service.
ManagedEndPoint::Settings m_managedEndPointSettings; ///< ManagedEndPoint settings for the main thread.
ManagedEndPoint::Settings m_pingerManagedEndPointSettings; ///< ManagedEndPoint settings for the pinger thread.
std::vector<String> m_diskMonitorList; ///< List of disks to monitor (default is disk containing working directory).
SystemMonitorMode m_systemMonitorMode; ///< Default: SYSTEM_MONITOR_MODE_ON.
bool m_enableHeapStatsLog; ///< Default: false.
bool m_enableDetailedHeapStatsLog; ///< Default: false. If true the heap stats log file will include bucket level stats.
bool m_enableEndPointStatsLog; ///< Default: false.
size_t m_systemStatsTimerInterval; ///< Default: 1000ms. How often to generate system / process stats.
size_t m_statsTimer; ///< Default: 5000ms. How often to generate endpoint / heap stats.
size_t m_threadStatsMonitorTimerInterval; ///< Default: 10000ms. How often to generate ThreadStatsMessages.
size_t m_endPointPingTimer; ///< Default: 2ms. Timer for dispatching endpoint pings which are sent in groups to cut down cpu spiking.
size_t m_endPointPingInterval; ///< Default: 50ms. How often to ping endpoints, in ms.
size_t m_endPointListUpdateInterval; ///< Default: 1000ms. How often to update the list of endpoint being pinged in ms.
size_t m_numberOfLogBackups; ///< Default: 40. Previous days logs to keep.
byte_t m_heapFreePublishPercent; ///< Default: 25. % free messages at which to publish heap stats.
byte_t m_totalHeapSizeAlertThresholdPercent; ///< Default: 88. 0 to disable. Generate an alert if total heap size / physical memory is greater than this threshold.
};
/**
* @brief Monitor service ui component.
*/
class UiComponent ACTIV_FINAL : public Activ::UiComponent
{
public:
/**
* @brief Constructor.
*
* @param monitorService the monitor service to have the ui.
* @param uiServiceName name of the ui service.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API UiComponent(MonitorService &monitorService, const String &uiServiceName);
private:
virtual void Run(UiUser &uiUser) ACTIV_OVERRIDE;
MonitorService & m_monitorService;
// Last member.
Component::Enabler m_componentEnabler;
};
/**
* @brief Constructor.
*
* @param application the application the service will be linked to.
* @param serviceName name of the service.
* @param settings settings for the service.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API MonitorService(Application &application, const String &serviceName, const Settings &settings);
/**
* @brief Destructor.
*/
ACTIV_AGENT_APPLICATION_API ~MonitorService();
/**
* @brief Get the number of processes being monitored.
*
* @return The number of processes.
*/
ACTIV_AGENT_APPLICATION_API size_t GetNumberOfProcesses() const;
protected:
ACTIV_AGENT_APPLICATION_API virtual StatusCode OnMessage(HeapMessage &message) ACTIV_OVERRIDE;
ACTIV_AGENT_APPLICATION_API virtual StatusCode OnRequest(HeapMessage &request) ACTIV_OVERRIDE;
private:
class Impl;
Boost::scoped_ptr<Impl> m_pImpl;
};
} // namespace Activ
#endif // (!defined ACTIV_AGENT_APPLICATION_MONITOR_SERVICE_H)
@@ -1,150 +0,0 @@
/**
* @file include/ActivMiddleware/ActivAgentApplication/PubSubService.h
*
* @brief Header file for pubsub service.
*/
#if (!defined ACTIV_AGENT_APPLICATION_PUB_SUB_SERVICE_H)
#define ACTIV_AGENT_APPLICATION_PUB_SUB_SERVICE_H
#include "ActivMiddleware/ActivAgentApplication/External.h"
#include "ActivMiddleware/ActivFramework/PubSubServiceApi.h"
#include <map>
//! Activ namespace.
namespace Activ
{
/**
* @brief Publish-subscribe service class.
*/
class PubSubService : private ManagedEndPoint, public Component
{
public:
using Component::GetApplication;
/**
* @brief Settings.
*/
class Settings
{
public:
/**
* @brief Republish settings.
*
* This describes a mapping from subject -> set of multicast outputs for that subject.
*/
class Republish
{
public:
typedef std::vector<String> MulticastNameList;
String m_subject; ///< (Partial) subject to match on
MulticastNameList m_multicastNameList; ///< List of multicast groups to output on
};
/**
* @brief Default constructor.
*/
ACTIV_AGENT_APPLICATION_API Settings();
/**
* @brief Destructor.
*/
ACTIV_AGENT_APPLICATION_API ~Settings();
/**
* @brief Read settings from an ini file section.
*
* @param sectionIterator iterator to an ini file section.
*
* @throw Exception
*/
ACTIV_AGENT_APPLICATION_API void Read(const IniFileParser::ConstSectionIterator &sectionIterator);
typedef std::map<String, PubSubServiceApi::Multicast> MulticastMap;
typedef std::vector<Republish> RepublishList;
IHeap::Settings m_heapSettings; ///< Properties of the service heap.
ManagedEndPoint::Settings m_managedEndPointSettings;
MulticastMap m_multicastMap; ///< Map of multicast outputs.
RepublishList m_republishList; ///< List of subjects to write to multicast outputs.
private:
/**
* @brief Process multicast section in the ini file.
*
* @param sectionIterator iterator to an ini file section.
*
* @throw Exception
*/
void ProcessMulticastSection(const IniFileParser::ConstSectionIterator &sectionIterator);
/**
* @brief Process republish section in the ini file.
*
* @param sectionIterator iterator to an ini file section.
*
* @throw Exception
*/
void ProcessRepublishSection(const IniFileParser::ConstSectionIterator &sectionIterator);
};
/**
* @brief Message broker service ui component.
*/
class UiComponent ACTIV_FINAL : public Activ::UiComponent
{
public:
/**
* @brief Constructor.
*
* @param pubSubService service to show menu for.
* @param uiServiceName name of the ui service.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API UiComponent(PubSubService &pubSubService, const String &uiServiceName);
private:
virtual void Run(UiUser &uiUser) ACTIV_OVERRIDE;
PubSubService & m_pubSubService;
// Last member.
Component::Enabler m_componentEnabler;
};
/**
* @brief Constructor.
*
* @param application the application the service will be linked to.
* @param serviceName name of the service.
* @param settings settings for the service.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API PubSubService(Application &application, const String &serviceName, const Settings &settings);
/**
* @brief Destructor.
*/
ACTIV_AGENT_APPLICATION_API ~PubSubService();
class Impl;
protected:
virtual bool CanThreadExit() ACTIV_OVERRIDE;
virtual StatusCode OnRequest(HeapMessage &request) ACTIV_OVERRIDE;
virtual StatusCode OnMessage(HeapMessage &message) ACTIV_OVERRIDE;
private:
const Boost::scoped_ptr<Impl> m_pImpl; ///< Implementation.
};
} // namespace Activ
#endif // (!defined ACTIV_AGENT_APPLICATION_PUB_SUB_SERVICE_H)
@@ -1,138 +0,0 @@
/**
* @file include/ActivMiddleware/ActivAgentApplication/TimerService.h
*
* @brief Header file for the timer service class.
*/
#if (!defined ACTIV_AGENT_APPLICATION_TIMER_SERVICE_H)
#define ACTIV_AGENT_APPLICATION_TIMER_SERVICE_H
#include "ActivMiddleware/ActivAgentApplication/External.h"
//! Activ namespace.
namespace Activ
{
class TimerServiceImpl;
/**
* @brief Timer service class.
*/
class TimerService : private ManagedEndPoint, public Component
{
public:
using Component::GetApplication;
/**
* @brief Settings.
*/
class Settings
{
public:
/**
* @brief Default constructor.
*/
ACTIV_AGENT_APPLICATION_API Settings();
/**
* @brief Destructor.
*/
ACTIV_AGENT_APPLICATION_API ~Settings();
/**
* @brief Read settings from an ini file section.
*
* @param sectionIterator iterator to an ini file section.
*
* @throw Exception
*/
ACTIV_AGENT_APPLICATION_API void Read(const IniFileParser::ConstSectionIterator &sectionIterator);
/**
* @brief Heap properties for timer service, default buckets above.
*/
IHeap::Settings m_heapSettings;
/**
* @brief For TimerServiceApi::AdjustSystemTime(), threshold in milliseconds at which to set
* absolute time rather than adjust gradually. Default 60000.
*/
uint32_t m_adjustSystemTimeThreshold;
/**
* @brief Tick timeout; how often to check timers in microseconds.
*/
UInt m_tickTimeoutUs;
/**
* @brief Initial tick chime adjustment threshold; the threshold below which tick chimes will have a randomized start
* tick (milliseconds). Default 10000.
*/
uint64_t m_initialTickChimeAdjustmentThreshold;
/**
* @brief ManagedEndPoint settings for the service.
*/
ManagedEndPoint::Settings m_managedEndPointSettings;
};
/**
* @brief Timer service ui component.
*/
class UiComponent ACTIV_FINAL : public Activ::UiComponent
{
public:
/**
* @brief Constructor.
*
* @param timerService the timer service to have the ui.
* @param uiServiceName name of the ui service.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API UiComponent(TimerService &timerService, const String &uiServiceName);
private:
virtual void Run(UiUser &uiUser) ACTIV_OVERRIDE;
TimerService & m_timerService;
// Last member.
Component::Enabler m_componentEnabler;
};
/**
* @brief Constructor.
*
* The constructor creates an endpoint and heap in the system and runs a single thread.
*
* @param application the application the service is to run in.
* @param serviceName the name of the timer service.
* @param settings settings for the timer service.
*
* @throw Exception
*/
ACTIV_AGENT_APPLICATION_API TimerService(Application &application, const String &serviceName, const Settings &settings);
/**
* @brief Destructor.
*/
ACTIV_AGENT_APPLICATION_API ~TimerService();
protected:
ACTIV_AGENT_APPLICATION_API virtual bool CanThreadExit() ACTIV_OVERRIDE;
ACTIV_AGENT_APPLICATION_API virtual StatusCode OnRequest(HeapMessage &request) ACTIV_OVERRIDE;
ACTIV_AGENT_APPLICATION_API virtual StatusCode OnMessage(HeapMessage &message) ACTIV_OVERRIDE;
// ManagedEndPoint overrides
ACTIV_AGENT_APPLICATION_API virtual void Process() ACTIV_OVERRIDE;
private:
Boost::scoped_ptr<TimerServiceImpl> m_pImpl;
friend class TimerServiceImpl;
};
} // namespace Activ
#endif // (!defined ACTIV_AGENT_APPLICATION_TIMER_SERVICE_H)
@@ -1,63 +0,0 @@
/**
* @file include/ActivMiddleware/ActivAgentApplication/UiLiteMainComponent.h
*
* @brief Header file for lite-style main ui component.
*/
#if (!defined ACTIV_AGENT_APPLICATION_UI_LITE_MAIN_COMPONENT_H)
#define ACTIV_AGENT_APPLICATION_UI_LITE_MAIN_COMPONENT_H
#include "ActivMiddleware/ActivAgentApplication/External.h"
#include "ActivMiddleware/ActivAgentApplication/UiMainComponent.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief "Lite" main ui component.
*/
class UiLiteMainComponent : public UiMainComponent
{
public:
/**
* @brief Lite main menu.
*/
class UiMenu : public UiMainComponent::UiMenu
{
public:
/**
* @brief Constructor.
*
* @param uiComponent
* @param name
* @param uiUser
*/
ACTIV_AGENT_APPLICATION_API UiMenu(UiMainComponent &uiComponent, const String &name, UiUser &uiUser);
protected:
ACTIV_AGENT_APPLICATION_API virtual void DisplayTitle(const UiIo &uiIo) const ACTIV_OVERRIDE;
};
/**
* @brief Constructor.
*
* @param application AgentApplication to attach to.
* @param managedEndPoint endpoint to attach to - must be singly threaded.
* @param uiComponentName name of the ui component. This name is used to register the component with the main menu.
* @param uiServiceName name of the ui service.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API UiLiteMainComponent(AgentApplication &application, ManagedEndPoint &managedEndPoint,
const String &uiComponentName, const String &uiServiceName = Application::GetUiServiceName());
ACTIV_AGENT_APPLICATION_API virtual void Run(UiUser &uiUser) ACTIV_OVERRIDE;
protected:
ACTIV_AGENT_APPLICATION_API virtual bool IsValidRegistrationType(const UnderlyingType type) const ACTIV_OVERRIDE;
};
} // namespace Activ
#endif // (!defined ACTIV_AGENT_APPLICATION_UI_LITE_MAIN_COMPONENT_H)
@@ -1,276 +0,0 @@
/**
* @file include/ActivMiddleware/ActivAgentApplication/UiMainComponent.h
*
* @brief Header file for the main ui component class.
*/
#if (!defined ACTIV_AGENT_APPLICATION_UI_MAIN_COMPONENT_H)
#define ACTIV_AGENT_APPLICATION_UI_MAIN_COMPONENT_H
#include "ActivMiddleware/ActivAgentApplication/External.h"
#include "ActivMiddleware/ActivAgentApplication/AgentApplication.h"
#include "ActivMiddleware/ActivFramework/UiComponent.h"
#include "ActivMiddleware/ActivFramework/UiMenu.h"
#include ACTIV_BOOST_INCLUDE(scoped_ptr.hpp)
//! Activ namespace.
namespace Activ
{
class UiIo;
class UiComponentInfo;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Main ui component.
*
* The main ui component acts as the main, or master, menu of a ui service (the first menu clients will see).
* It also maintains a list of other ui components in the system that can be communicated with.
*/
class UiMainComponent : public UiComponent
{
public:
/**
* @brief Main menu.
*/
class UiMenu : public Activ::UiMenu
{
public:
/**
* @brief Constructor.
*
* @param uiComponent
* @param name
* @param uiUser
*/
ACTIV_AGENT_APPLICATION_API UiMenu(UiMainComponent &uiComponent, const String &name, UiUser &uiUser);
protected:
ACTIV_AGENT_APPLICATION_API virtual StatusCode GetOption(const UiIo &uiIo, const TimeoutPeriod timeoutPeriod,
String &optionString) const ACTIV_OVERRIDE;
ACTIV_AGENT_APPLICATION_API virtual StatusCode ProcessOption(const UiIo &uiIo, const String &optionString) ACTIV_OVERRIDE;
/**
* @brief Display internal system menu.
*
* @param uiIo
*/
void DisplayInternalMenu(const UiIo &uiIo);
UiMainComponent &m_uiComponent;
};
/**
* @brief Constructor.
*
* @param application AgentApplication to attach to.
* @param managedEndPoint endpoint to attach to - must be singly threaded.
* @param uiComponentName name of the ui component. This name is used to register the component with the main menu.
* @param uiServiceName name of the ui service.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API UiMainComponent(AgentApplication &application, ManagedEndPoint &managedEndPoint,
const String &uiComponentName, const String &uiServiceName = Application::GetUiServiceName());
/**
* @brief Destructor.
*/
ACTIV_AGENT_APPLICATION_API ~UiMainComponent();
/**
* @brief Display system menu.
*
* @param uiIo
*/
ACTIV_AGENT_APPLICATION_API void UiDisplaySystemMenu(const UiIo &uiIo);
/**
* @brief Display process menu.
*
* @param uiIo
*/
ACTIV_AGENT_APPLICATION_API void UiDisplayProcessMenu(const UiIo &uiIo);
/**
* @brief Open command prompt within the ui session.
*
* @param uiIo for i/o with ui user.
*/
ACTIV_AGENT_APPLICATION_API void UiCommandPrompt(const UiIo &uiIo) const;
/**
* @brief Initiate system shutdown option.
*
* @param uiIo
*/
ACTIV_AGENT_APPLICATION_API void UiShutdownSystem(const UiIo &uiIo);
/**
* @brief Display ui components.
*
* @param uiIo for i/o with ui user.
*/
ACTIV_AGENT_APPLICATION_API void UiDisplayAvailableUiComponents(const UiIo &uiIo) const;
/**
* @brief Display ui components for middleware components only.
*
* @param uiIo for i/o with ui user.
*/
ACTIV_AGENT_APPLICATION_API void UiDisplayAvailableMiddlewareUiComponents(const UiIo &uiIo) const;
/**
* @brief Menu option to display list of available ui components.
*
* @param uiIo to read / write to / from the user.
* @param type type of ui component to display.
*/
ACTIV_AGENT_APPLICATION_API void UiDisplayAvailableUiComponentsByType(const UiIo &uiIo, const Type type) const;
/**
* @brief Display system info.
*
* @param uiIo for i/o with ui user.
*/
ACTIV_AGENT_APPLICATION_API void UiDisplaySystemInfo(const UiIo &uiIo) const;
protected:
ACTIV_AGENT_APPLICATION_API virtual bool IsValidRegistrationType(const UnderlyingType type) const ACTIV_OVERRIDE;
AgentApplication & m_agentApplication;
private:
/**
* @brief User has entered an option.
*
* @param uiIo to read / write to / from the user.
* @param optionString the option string.
*/
StatusCode OnOption(const UiIo &uiIo, const String &optionString);
// Display CPU topology.
void UiDisplayCpuTopology(const UiIo &uiIo) const;
/**
* @brief Display network interfaces.
*
* @param uiIo for i/o with ui user.
*/
static void UiDisplayNetworkInterfaces(const UiIo &uiIo);
/**
* @brief Display a network interface.
*
* @param uiIo for i/o with ui user.
* @param interfaceInfo
*/
static void UiDisplayNetworkInterfaceInfo(const UiIo &uiIo, const IpManager::InterfaceInfo &interfaceInfo);
/**
* @brief Display hosts file.
*
* @param uiIo for i/o with ui user.
*/
static void UiDisplayHostsFile(const UiIo &uiIo);
/**
* @brief Resolve hostname.
*
* @param uiIo for i/o with ui user.
*/
static void UiResolveHostname(const UiIo &uiIo);
/**
* @brief Display open processes' state.
*
* @param uiIo for i/o with ui user.
*/
void UiDisplayAllProcessesState(const UiIo &uiIo) const;
/**
* @brief Display open processes' context.
*
* @param uiIo for i/o with ui user.
*/
void UiDisplayAllProcessesContext(const UiIo &uiIo) const;
/**
* @brief Display process affinities.
*
* @param uiIo for i/o with ui user.
*/
void UiDisplayProcessAffinities(const UiIo &uiIo) const;
/**
* @brief Display more detailed info for a single process.
*
* @param uiIo for i/o with ui user.
*/
void UiDisplayProcess(const UiIo &uiIo) const;
/**
* @brief Watch summary endpoint stats.
*
* @param uiIo for i/o with ui user.
*/
void UiWatchEndPointStatsSummary(const UiIo &uiIo) const;
/**
* @brief Display components on an endpoint.
*
* @param uiIo for i/o with ui user.
*/
void UiDisplayComponents(const UiIo &uiIo) const;
/**
* @brief Reset endpoint high counts.
*
* @param uiIo for i/o with ui user.
*/
void UiResetEndPointHighs(const UiIo &uiIo);
/**
* @brief Watch summary heap stats.
*
* @param uiIo for i/o with ui user.
*/
void UiWatchHeapStatsSummary(const UiIo &uiIo) const;
/**
* @brief Reset heap stats.
*
* @param uiIo for i/o with ui user.
*/
void UiResetHeapStats(const UiIo &uiIo);
/**
* @brief Display heap request distribution.
*
* @param uiIo for i/o with ui user.
*/
void UiDisplayHeapRequestDistribution(const UiIo &uiIo);
/**
* @brief Force a dump file generation for a process.
*
* @param uiIo for i/o with ui user.
*/
void UiDumpProcess(const UiIo &uiIo) const;
/**
* @brief Shutdown a process cleanly.
*
* @param uiIo for i/o with ui user.
*/
void UiShutdownProcess(const UiIo &uiIo);
ScopedSubscription m_endPointSubject;
};
} // namespace Activ
#endif // (!defined ACTIV_AGENT_APPLICATION_UI_MAIN_COMPONENT_H)
@@ -1,164 +0,0 @@
/**
* @file include/ActivMiddleware/ActivAgentApplication/UiService.h
*
* @brief Header file for the ui service class.
*/
#if (!defined ACTIV_AGENT_APPLICATION_UI_SERVICE_H)
#define ACTIV_AGENT_APPLICATION_UI_SERVICE_H
#include "ActivMiddleware/ActivAgentApplication/External.h"
#include ACTIV_BOOST_INCLUDE(scoped_ptr.hpp)
#include <map>
//! Activ namespace.
namespace Activ
{
/**
* @brief Ui service class.
*
* A ui service requires the address of the ui component that is to act as the main menu of the service,
* which exists on a separate endpoint. A heap with the same name as this service must have been created
* before construction of this object.
*/
class UiService : private ManagedEndPoint, public Service
{
public:
using Service::GetApplication;
typedef String UserId; ///< Type of user id.
typedef String UserPassword; ///< Type of user password.
/**
* @brief User info.
*/
class UserInfo
{
public:
UserId m_id; ///< Id of user.
UserPassword m_password; ///< Password of user.
UiPermissions m_uiPermissions; ///< Ui permissions of user.
};
typedef std::map<UserId, UserInfo> UserInfoMap; ///< Type of user info map.
/**
* @brief Settings.
*/
class Settings
{
public:
/**
* @brief Default constructor.
*/
ACTIV_AGENT_APPLICATION_API Settings();
/**
* @brief Destructor.
*/
ACTIV_AGENT_APPLICATION_API ~Settings();
/**
* @brief Read settings from an ini file section.
*
* @param sectionIterator iterator to an ini file section.
*
* @throw Exception
*/
ACTIV_AGENT_APPLICATION_API void Read(const IniFileParser::ConstSectionIterator &sectionIterator);
//! Options for behavior of local console access to UiService.
enum ConsoleMode
{
CONSOLE_MODE_OFF, ///< No local console session to ui service.
CONSOLE_MODE_RESTART_TELNET_ON_CLOSE, ///< Local telnet session to ui service. Restart session if closed.
CONSOLE_MODE_SHUTDOWN_SYSTEM_ON_CLOSE ///< Local telnet session to ui service. Shutdown system if closed.
};
//! Settings for ui tunnelling.
class Tunnel
{
public:
String m_serviceId; ///< Service id for the tunnel service.
ServiceAccessPointList m_serviceAccessPointList; ///< Server-side access points. None by default.
String m_serviceAttributes; ///< Attributes for the tunnel service.
bool m_isClient; ///< Whether to attempt to connect to a tunnel service.
};
/**
* @brief Default UiService port. Append this to m_serviceAccessPointList if required.
*/
ACTIV_AGENT_APPLICATION_API static const ServiceAccessPoint defaultAccessPoint;
IHeap::Settings m_heapSettings; ///< Heap properties. Default buckets, see above.
ManagedEndPoint::Settings m_managedEndPointSettings;
ConsoleMode m_consoleMode; ///< Console client mode. Dflt CONSOLE_MODE_SHUTDOWN_SYSTEM_ON_CLOSE.
bool m_enableLogOutput; ///< Enable log output? Default == true.
bool m_enableAnonymousAccess; ///< Enable view-only anonymous user? Default == true.
UiPermissions m_anonymousAccessPermissions; ///< Anonymous access permissions.
ServiceAccessPointList m_serviceAccessPointList; ///< Access points. Default is empty; creates only a loopback server.
UserInfoMap m_userInfoMap; ///< Info about users.
Tunnel m_tunnel; ///< Tunnelling settings.
bool m_enableLog; ///< Log file to log user's input and output. Default == false.
};
/**
* @brief Ui service ui component.
*/
class UiComponent ACTIV_FINAL : public Activ::UiComponent
{
public:
/**
* @brief Constructor.
*
* @param uiService the ui service to have the ui.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API UiComponent(UiService &uiService);
private:
virtual void Run(UiUser &uiUser) ACTIV_OVERRIDE;
UiService & m_uiService;
// Last member.
Component::Enabler m_componentEnabler;
};
/**
* @brief Constructor.
*
* @param application Application object to attach to.
* @param serviceName name of the service.
* @param settings settings for the service.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API UiService(Application &application, const String &serviceName, const Settings &settings);
/**
* @brief Destructor.
*/
ACTIV_AGENT_APPLICATION_API ~UiService();
class Impl;
protected:
ACTIV_AGENT_APPLICATION_API virtual bool CanThreadExit() ACTIV_OVERRIDE;
ACTIV_AGENT_APPLICATION_API virtual StatusCode OnMessage(HeapMessage &message) ACTIV_OVERRIDE;
ACTIV_AGENT_APPLICATION_API virtual StatusCode OnAccept(HeapMessage &acceptMessage) ACTIV_OVERRIDE;
private:
static const ServiceId m_serviceId; ///< Id of the ui service.
Boost::scoped_ptr<Impl> m_pImpl; ///< Implementation.
};
} // namespace Activ
#endif // (!defined ACTIV_AGENT_APPLICATION_UI_SERVICE_H)
@@ -1,65 +0,0 @@
/**
* @file include/ActivMiddleware/ActivAgentApplication/UiStandardMainComponent.h
*
* @brief Header file for standard-style main ui component.
*/
#if (!defined ACTIV_AGENT_APPLICATION_UI_STANDARD_MAIN_COMPONENT_H)
#define ACTIV_AGENT_APPLICATION_UI_STANDARD_MAIN_COMPONENT_H
#include "ActivMiddleware/ActivAgentApplication/External.h"
#include "ActivMiddleware/ActivAgentApplication/UiMainComponent.h"
#include "ActivMiddleware/ActivAgentApplication/AgentApplication.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Standard main menu component.
*/
class UiStandardMainComponent : public Activ::UiMainComponent
{
public:
/**
* @brief Lite main menu.
*/
class UiMenu : public UiMainComponent::UiMenu
{
public:
/**
* @brief Constructor.
*
* @param uiComponent
* @param name
* @param uiUser
*/
ACTIV_AGENT_APPLICATION_API UiMenu(UiMainComponent &uiComponent, const String &name, UiUser &uiUser);
protected:
ACTIV_AGENT_APPLICATION_API virtual void DisplayFooter(const UiIo &uiIo) const ACTIV_OVERRIDE;
};
/**
* @brief Constructor.
*
* @param application AgentApplication to attach to.
* @param managedEndPoint endpoint to attach to - must be singly threaded.
* @param uiComponentName name of the ui component. This name is used to register the component with the main menu.
* @param uiServiceName name of the ui service.
*
* @throw Exception.
*/
ACTIV_AGENT_APPLICATION_API UiStandardMainComponent(AgentApplication &application, ManagedEndPoint &managedEndPoint,
const String &uiComponentName, const String &uiServiceName = Application::GetUiServiceName());
ACTIV_AGENT_APPLICATION_API virtual void Run(UiUser &uiUser) ACTIV_OVERRIDE;
protected:
ACTIV_AGENT_APPLICATION_API virtual bool IsValidRegistrationType(const UnderlyingType type) const ACTIV_OVERRIDE;
};
} // namespace Activ
#endif // (!defined ACTIV_AGENT_APPLICATION_UI_STANDARD_MAIN_COMPONENT_H)
@@ -1,589 +0,0 @@
/**
* @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 "ActivMiddleware/Misc/StringView.h"
#include ACTIV_BOOST_INCLUDE(array.hpp)
#include ACTIV_BOOST_INCLUDE(optional/optional.hpp)
#include ACTIV_BOOST_INCLUDE(system/system_error.hpp)
#include <iostream>
#include <cstdarg>
//! 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 message string to log.
* @param messageLength length of @message.
*/
ACTIV_BASE_API void LogMessage(const LogType type, const char *pMessage, const size_t messageLength);
/**
* @brief Log a string. By default the output is sent to stdout, or stderr for LOG_TYPE_ERROR.
*
* @tparam T a string type convertable to CxxYZ::string_view using ToStringType.
*
* @param type
* @param message string to log.
*/
template<typename T>
void LogMessage(const LogType type, const T &message)
{
const CxxYZ::string_view logMessage(ToStringType<CxxYZ::string_view>(message));
LogMessage(type, logMessage.data(), logMessage.size());
}
/**
* @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.
* @param messageLength length of @message.
*/
ACTIV_BASE_API void AlertMessage(const AlertType alertType, const AlertId alertId, const char *pMessage, const size_t messageLength);
/**
* @brief Alert a string. By default the output is sent to stderr.
*
* @tparam T a string type convertable to CxxYZ::string_view using ToStringType.
*
* @param alertType
* @param alertId
* @param message string to alert.
*/
template<typename T>
void AlertMessage(const AlertType alertType, const AlertId alertId, const T &message)
{
const CxxYZ::string_view logMessage(ToStringType<CxxYZ::string_view>(message));
AlertMessage(alertType, alertId, logMessage.data(), logMessage.size());
}
/**
* @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<int>(statusCode), StatusCodeCategory());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline CxxYZ::error_condition make_error_condition(StatusCodeErrc statusCode)
{
return CxxYZ::error_condition(Boost::underlying_cast<int>(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<int>(statusCode), StatusCodeCategory());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Boost::system::error_condition make_error_condition(StatusCodeErrc statusCode)
{
return Boost::system::error_condition(Boost::underlying_cast<int>(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<char, 256> 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<char, N> with the formatted string.
*/
template<size_t N>
ACTIV_PRINTF_FUNCTION(printf, 1, 2)
Boost::array<char, N> 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<String> &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<n; ++i) h = hash( k[i], len[i], h);
* By Bob Jenkins, 1996. bob_jenkins@burtleburtle.net. You may use
* this code any way you wish, private, educational, or commercial. It's free.
* See http://burtleburtle.net/bob/evahash.html
* Use for hash table lookup, or anything where one collision in 2^^32 is
* acceptable. Do NOT use for cryptographic purposes.
*
* @param pKeyBuffer the key buffer to hash.
* @param keyLength the length of the key buffer.
* @param initialValue the initial value of the hash.
*
* @return the calculated hash value.
*/
ACTIV_BASE_API uint32_t GenericHash(const void *pKeyBuffer, const size_t keyLength, const uint32_t initialValue);
// ---------------------------------------------------------------------------------------------------------------------------------
template<size_t N>
Boost::array<char, N> SnprintfArray(const char *pFormat, ...)
{
Boost::array<char, N> 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<uint16_t> &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<ACTIV_BOOST_SCOPED_ENUM_NATIVE(::Activ::StatusCodeErrc)> : public ::Activ::CxxYZ::true_type { };
template<>
struct is_error_code_enum<ACTIV_BOOST_SCOPED_ENUM_NATIVE(::Activ::StatusCodeErrc)> : 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<ACTIV_BOOST_SCOPED_ENUM_NATIVE(::Activ::StatusCodeErrc)> : public ::Activ::CxxYZ::true_type { };
template<>
struct is_error_code_enum<ACTIV_BOOST_SCOPED_ENUM_NATIVE(::Activ::StatusCodeErrc)> : public ::Activ::CxxYZ::true_type { };
} // namespace std
#endif // (defined ACTIV_CXXYZ_SYSTEM_ERROR_STD_AVAILABLE)
#endif // (!defined ACTIV_BASE_H)
@@ -1,106 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/ActivFileTypes.h
*
* @brief Global functions from ActivFileTypes.
*/
#if (!defined ACTIV_BASE_ACTIV_FILE_TYPES_H)
#define ACTIV_BASE_ACTIV_FILE_TYPES_H
#include "ActivMiddleware/ActivBase/External.h"
/**
* @brief The list of file types.
*
* TYPE enumeration value of the file type.
* CLASS_NAME The concrete class name of the file type.
*
* TYPE CLASS_NAME
*/
#ifndef ACTIV_LITE_FRAMEWORK
#define ACTIV_FILE_TYPE_LIST(d) \
d(ZLIB, ZlibFile) \
d(ZSTD, ZstdFile)
#endif
// Element accessors.
#define ACTIV_FILE_TYPE_GET_TYPE(type, className) ACTIV_JOIN(FILE_TYPE_, type)
#define ACTIV_FILE_TYPE_GET_NAME(type, className) className
//! Activ namespace.
namespace Activ
{
#define DECLARE_CASE(type, className) ACTIV_FILE_TYPE_GET_TYPE(type, className),
//! Enumeration of all field types.
enum FileType
{
#ifndef ACTIV_LITE_FRAMEWORK
ACTIV_FILE_TYPE_LIST(DECLARE_CASE)
#endif
FILE_TYPE_NORMAL,
NUMBER_OF_FILE_TYPES
};
#undef DECLARE_CASE
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
#ifndef ACTIV_LITE_FRAMEWORK
/**
* @brief Get the name of the file type.
*
* @param fileType the file type.
*
* @return the name of the file type.
*/
ACTIV_BASE_API const String &FileTypeToString(const FileType fileType);
/**
* @brief Get the file extension.
*
* @param fileType the file type.
*
* @return the file extension for the type.
*/
ACTIV_BASE_API const String &FileTypeToFileExtension(const FileType fileType);
/**
* @brief Get the file type from the extension.
*
* @param fileExtension the file extension.
*
* @return the file type for the extension.
*/
ACTIV_BASE_API FileType FileExtensionToFileType(const String &fileExtension);
/**
* @brief Get the file type based on the file header.
*
* @param fileName the name of the file.
* @param fileType the returned file type.
*
* @retval STATUS_CODE_SUCCESS.
* @retval ...
*/
ACTIV_BASE_API StatusCode GetFileTypeFromFile(const String &fileName, FileType &fileType);
/**
* @brief Get the file type based on the file header.
*
* @param fileName the name of the file.
*
* @return the file type.
*
* @throws StatusCodeException
*/
ACTIV_BASE_API FileType GetFileTypeFromFile(const String &fileName);
#endif
} // namespace Activ
#endif // (!defined ACTIV_BASE_ACTIV_FILE_TYPES_H)
@@ -1,59 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/AlertMessageException.h
*
* @brief Header file for the AlertMessageException class.
*/
#if (!defined ACTIV_BASE_ALERT_MESSAGE_EXCEPTION_H)
#define ACTIV_BASE_ALERT_MESSAGE_EXCEPTION_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/ActivBase.h"
#include ACTIV_BOOST_INCLUDE(exception/all.hpp)
//! Activ namespace.
namespace Activ
{
/**
* @brief AlertMessage exception class.
*
* Calls AlertMessage() with the provided string. Useful to both alert and throw an error.
*/
class AlertMessageException : public virtual Boost::exception, public virtual std::exception
{
public:
/**
* @brief Constructor.
*
* @param alertType
* @param alertId
* @param pMessage string to alert.
*/
ACTIV_BASE_API AlertMessageException(const AlertType alertType, const AlertId alertId, const char * const pMessage);
/**
* @brief Constructor.
*
* @param alertType
* @param alertId
* @param message string to alert.
*/
ACTIV_BASE_API AlertMessageException(const AlertType alertType, const AlertId alertId, const String &message);
/**
* @brief Destructor.
*/
ACTIV_BASE_API ~AlertMessageException() throw();
// std::exception overrides.
ACTIV_BASE_API virtual const char *what() const throw() ACTIV_OVERRIDE;
private:
const String m_message;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_ALERT_MESSAGE_EXCEPTION_H)
@@ -1,70 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/BaseException.h
*
* @brief Header file for the base exception class.
*/
#if (!defined ACTIV_BASE_BASE_EXCEPTION_H)
#define ACTIV_BASE_BASE_EXCEPTION_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Exception.h"
/**
* @brief The list of possible errors and their strings.
*
* Note this list is converted to an enum using the ACTIV_DECLARE_ELEMENT_1 macro in ActivMiddleware.h,
* and the strings are unpicked using ACTIV_DECLARE_ELEMENT_2.
*/
#define ACTIV_BASE_EXCEPTION_LIST(d) \
d(ERROR_INVALID_REGISTRY_VALUE_TYPE, "invalid registry value type") \
d(ERROR_FAILED_TO_ALLOC_SHARED_MUTEX, "failed to allocate shared mutex") \
d(ERROR_FAILED_TO_ALLOC_PRIVATE_MUTEX, "failed to allocate private mutex") \
d(ERROR_FAILED_TO_INIT_PRIVATE_MUTEX, "failed to initialize private mutex") \
d(ERROR_FAILED_TO_ALLOC_SHARED_EVENT, "failed to allocate shared event") \
d(ERROR_FAILED_TO_ALLOC_PRIVATE_EVENT, "failed to allocate private event") \
d(ERROR_FAILED_TO_ALLOC_VERSION, "failed to allocate version") \
d(ERROR_FAILED_TO_ALLOC_SHARED_MEMORY, "failed to allocate shared memory") \
d(ERROR_FAILED_TO_ALLOC_METERED_SECTION, "failed to allocate metered section") \
d(ERROR_FAILED_TO_ALLOC_UUID, "failed to allocate Uuid") \
d(ERROR_THREAD_ALREADY_STARTED, "thread already started")
//! Activ namespace.
namespace Activ
{
/**
* @brief ActivBase exception class.
*
* An exception of class BaseException is thrown only by classes inside ActivBase.
*/
class BaseException : public Exception
{
public:
/**
* @brief Enumeration of all BaseException errors.
*/
enum
{
ACTIV_BASE_EXCEPTION_LIST(ACTIV_DECLARE_ELEMENT_1_WITH_COMMA)
NUM_ERRORS
};
/**
* @brief Constructor.
*
* @param file the file which raised the exception.
* @param function the function which raised the exception.
* @param line the line number which raised the exception.
* @param errorCode the exception specific error code.
* @param message the exception message.
*/
ACTIV_BASE_API BaseException(const char *file, const char *function, const uint_fast32_t line, const uint_fast32_t errorCode,
const String &message = "");
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_BASE_EXCEPTION_H)
@@ -1,234 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/CommandLineParser.h
*
* @brief Header file for a command line parser class.
*/
#if (!defined ACTIV_BASE_COMMAND_LINE_PARSER_H)
#define ACTIV_BASE_COMMAND_LINE_PARSER_H
#include "ActivMiddleware/ActivBase/Detail/CommandLineParserDetail.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Command line parser class.
*
* This is a wrapper over the more complete Boost::program_options library.
*
* "help" (short form '?') and "version" switches are implictly added.
*/
class CommandLineParser : private Boost::noncopyable
{
public:
/**
* @brief Default constructor.
*/
ACTIV_BASE_API CommandLineParser();
/**
* @brief Destructor.
*/
ACTIV_BASE_API virtual ~CommandLineParser();
/**
* @brief Process a command line.
*
* @param argc as passed to main().
* @param argv as passed to main().
* @param outStream iostream to print usage or version to, default std::cout.
*
* @retval true command line parsed.
* @retval false help or version switch was passed. PrintUsage() or PrintVersion() has been called.
*
* @throw Exception.
* @throw Boost::program_options::error.
*/
ACTIV_BASE_API bool Process(const int argc, char *argv[], std::ostream &outStream = std::cout);
/**
* @brief Print usage display.
*
* @param argv0 argv[0] from main().
* @param outStream iostream to print usage to.
*/
ACTIV_BASE_API virtual void PrintUsage(const String &argv0, std::ostream &outStream) const;
/**
* @brief Print version.
*
* @param outStream iostream to print version to.
*/
ACTIV_BASE_API virtual void PrintVersion(std::ostream &outStream) const;
/**
* @brief Determines if the element has been set to a default value or from the command line.
*
* @param name is the string to check if it is defaulted or not. This string must match the long name of the
* Parameter, Switch etc... that you wish to check.
*
* @return true if it is defaulted.
*/
ACTIV_BASE_API bool IsDefaultValue(const String &name) const;
/**
* @brief Get object to help with appending descriptions.
*
* @return DescriptionAppender helper object reference.
*/
ACTIV_BASE_API CommandLineParserDetail::DescriptionAppender &AddDescriptions();
/**
* @brief Helper function to construct a mandatory parameter description with default store action.
*
* @param name name of the parameter.
* @param description descriptive text of the parameter.
* @param value location to store the parameter's value.
*/
template<typename T>
static CommandLineParserDetail::MandatoryParameterDescription<T> Parameter(const String &name,
const String &description, T &value)
{
return CommandLineParserDetail::MandatoryParameterDescription<T>(name, description,
CommandLineParserDetail::ValueStore<T>(value));
}
/**
* @brief Helper function to construct a mandatory parameter description with arbitrary action.
*
* @param name name of the parameter.
* @param description descriptive text of the parameter.
* @param notifier function to invoke with the parameter's value.
*/
template<typename T, typename F>
static CommandLineParserDetail::MandatoryParameterDescription<T> Parameter(const String &name,
const String &description, const F &notifier)
{
return CommandLineParserDetail::MandatoryParameterDescription<T>(name, description, notifier);
}
/**
* @brief Helper function to construct an optional parameter description with default value and store action.
*
* @param name name of the parameter.
* @param description descriptive text of the parameter.
* @param defaultValue the default value to assign for this parameter if none is provided.
* @param value location to store the parameter's value.
*/
template<typename T>
static CommandLineParserDetail::OptionalParameterDescription<T> Parameter(const String &name,
const String &description, const T &defaultValue, T &value)
{
return CommandLineParserDetail::OptionalParameterDescription<T>(name, description, defaultValue,
CommandLineParserDetail::ValueStore<T>(value));
}
/**
* @brief Helper function to construct an optional parameter description with a default value and arbitrary action.
*
* @param name name of the parameter.
* @param description descriptive text of the parameter.
* @param defaultValue the default value to assign for this parameter if none is provided.
* @param notifier function to invoke with the parameter's value.
*/
template<typename T, typename F>
static CommandLineParserDetail::OptionalParameterDescription<T> Parameter(const String &name,
const String &description, const T &defaultValue, const F &notifier)
{
return CommandLineParserDetail::OptionalParameterDescription<T>(name, description, defaultValue, notifier);
}
/**
* @brief Helper function to construct a mandatory switch description with default store action.
*
* @param name name of the switch.
* @param description descriptive text of the switch.
* @param value location to store the switch's value.
*/
template<typename T>
static CommandLineParserDetail::MandatorySwitchDescription<T> Switch(const String &name,
const String &description, T &value)
{
return CommandLineParserDetail::MandatorySwitchDescription<T>(name, description,
CommandLineParserDetail::ValueStore<T>(value));
}
/**
* @brief Helper function to construct a mandatory switch description with arbitrary action.
*
* @param name name of the switch.
* @param description descriptive text of the switch.
* @param notifier function to invoke with the switch's value.
*/
template<typename T, typename F>
static CommandLineParserDetail::MandatorySwitchDescription<T> Switch(const String &name, const String &description,
const F &notifier)
{
return CommandLineParserDetail::MandatorySwitchDescription<T>(name, description, notifier);
}
/**
* @brief Helper function to construct an optional switch description with default value and default store action.
*
* @param name name of the switch.
* @param description descriptive text of the switch.
* @param defaultValue the default value to assign for this switch if none is provided.
* @param value location to store the switch's value.
*/
template<typename T>
static CommandLineParserDetail::OptionalSwitchDescription<T> Switch(const String &name,
const String &description, const T &defaultValue, T &value)
{
return CommandLineParserDetail::OptionalSwitchDescription<T>(name, description, defaultValue,
CommandLineParserDetail::ValueStore<T>(value));
}
/**
* @brief Helper function to construct an optional switch description with default value and arbitrary action.
*
* @param name name of the switch.
* @param description descriptive text of the switch.
* @param defaultValue the default value to assign for this switch if none is provided.
* @param notifier function to invoke with the switch's value.
*/
template<typename T, typename F>
static CommandLineParserDetail::OptionalSwitchDescription<T> Switch(const String &name,
const String &description, const T &defaultValue, const F &notifier)
{
return CommandLineParserDetail::OptionalSwitchDescription<T>(name, description, defaultValue, notifier);
}
/**
* @brief Helper function to construct a boolean switch description and default store action.
*
* @param name name of the switch.
* @param description descriptive text of the switch.
* @param value
*/
ACTIV_BASE_API static CommandLineParserDetail::BooleanSwitchDescription BooleanSwitch(const String &name,
const String &description, bool &value);
/**
* @brief Helper function to construct a boolean switch description and arbitrary action.
*
* @param name name of the switch.
* @param description descriptive text of the switch.
* @param notifier function to invoke with the switch's value.
*/
template<typename F>
static CommandLineParserDetail::BooleanSwitchDescription BooleanSwitch(const String &name,
const String &description, const F &notifier)
{
return CommandLineParserDetail::BooleanSwitchDescription(name, description, notifier);
}
private:
CommandLineParserDetail::CommandLineParserImpl m_commandLineParserImpl;
CommandLineParserDetail::DescriptionAppender m_descriptionAppender;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_COMMAND_LINE_PARSER_H)
@@ -1,218 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/CompartmentalizedMessageRateThrottler.h
*
* @brief Header file for the message rate throttler class.
*/
#if (!defined ACTIV_BASE_COMPARTMENTALIZED_MESSAGE_RATE_THROTTLER_H)
#define ACTIV_BASE_COMPARTMENTALIZED_MESSAGE_RATE_THROTTLER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/IntervalTimer.h"
#include "ActivMiddleware/CxxYZ/chrono.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Compartmentalized message rate throttler class.
*
* This class should be used when wishing to throttle a message rate, but do other work than sleep when it is not
* presently possible to send.
*
* For example:
*
* CompartmentalizedMessageRateThrottler m_compartmentalizedMessageRateThrottler;
* ...
* while (true)
* {
* if (0 == m_compartmentalizedMessageRateThrottler.GetInactivityPeriod())
* {
* // Send a message.
* MyPostMessage();
* m_compartmentalizedMessageRateThrottler.Complete();
* }
* else
* {
* // Do some other work for a while.
* ...
* }
* }
*/
class CompartmentalizedMessageRateThrottler
{
public:
//! Period length type.
typedef CxxYZ::chrono::microseconds PeriodLength;
/**
* @brief Constructor.
*
* @param messagesPerSecond the message rate per second, or 0 for no throttle.
*/
ACTIV_BASE_API CompartmentalizedMessageRateThrottler(const size_t messagesPerSecond);
/**
* @brief Constructor.
*
* Deprecated, use the constructor taking a @a PeriodLength instead.
*
* @param messagesPerSecond the message rate per second, or 0 for no throttle.
* @param periodLengthInMs the period length (in milliseconds) to throttle over.
*
* @throw StatusCodeException
*/
ACTIV_BASE_API CompartmentalizedMessageRateThrottler(const size_t messagesPerSecond, const size_t periodLengthInMs);
/**
* @brief Constructor.
*
* @param messagesPerSecond the message rate per second, or 0 for no throttle.
* @param periodLength the period length to throttle over.
* @param totalThrottleLength the total throttle length over all periods, must be between 1 and 100 times @a periodLength.
*
* @throw StatusCodeException
*/
ACTIV_BASE_API CompartmentalizedMessageRateThrottler(const size_t messagesPerSecond, const PeriodLength periodLength,
const PeriodLength totalThrottleLength);
/**
* @brief Initialize.
*
* @param messagesPerSecond the message rate per second, or 0 for no throttle.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API StatusCode Initialize(const size_t messagesPerSecond);
/**
* @brief Initialize.
*
* Deprecated, use the method taking a @a PeriodLength instead.
*
* @param messagesPerSecond the message rate per second, or 0 for no throttle.
* @param periodLengthInMs the period length (in milliseconds) to throttle over.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API StatusCode Initialize(const size_t messagesPerSecond, const size_t periodLengthInMs);
/**
* @brief Initialize.
*
* @param messagesPerSecond the message rate per second, or 0 for no throttle.
* @param periodLength the period length to throttle over.
* @param totalThrottleLength the total throttle length over all periods, must be between 1 and 100 times @a periodLength.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API StatusCode Initialize(const size_t messagesPerSecond, const PeriodLength periodLength,
const PeriodLength totalThrottleLength);
/**
* @brief Get the message rate.
*
* @return The message rate in messages per second.
*/
ACTIV_BASE_API size_t GetMessageRate() const;
/**
* @brief Get the period length.
*
* @return The period length.
*/
ACTIV_BASE_API PeriodLength GetPeriodLength() const;
/**
* @brief Reset.
*/
ACTIV_BASE_API void Reset();
/**
* @brief Can we send a message right now?
*
* @return 0 if we can send a message right now, else a value representing the time that we can't send a message for.
* Can be passed to the Sleep() method if we wish to sleep, rather than doing some other work.
*/
ACTIV_BASE_API uint64_t GetInactivityPeriod();
/**
* @brief Sleep for some time period.
*
* @param period as returned by GetInactivityPeriod(), for instance.
*/
#if (!defined ACTIV_LITE_FRAMEWORK)
ACTIV_BASE_API void Sleep(const uint64_t period) const;
#endif
/**
* @brief After getting a 0 return value from GetInactivityPeriod(), and sending a message,
* this should be called to update internal state.
*/
ACTIV_BASE_API void Complete();
/**
* @brief Convert a period (in system dependent units) to milliseconds.
*
* The period will be rounded by to the nearest millisecond.
*
* @param period as returned by GetInactivityPeriod().
*
* @return @a period in milliseconds, rounded up to the nearest millisecond.
*/
ACTIV_BASE_API size_t ConvertPeriodToMilliseconds(const uint64_t period) const;
private:
class PeriodInfo
{
public:
size_t m_idealNumberOfMessages;
size_t m_currentNumberOfMessages;
size_t m_maxNumberOfMessages;
};
typedef std::vector<PeriodInfo> PeriodInfoList;
/**
* @brief Set current period.
*
* @param period
* @param timeStamp
* @param allowedOverrunThisPeriod messages to allow in addition to the ideal in this period.
*/
void SetPeriod(const size_t period, const uint64_t timeStamp, const size_t allowedOverrunThisPeriod);
/**
* @brief Move to the next period.
*/
void SetNextPeriod();
/**
* @brief Get the next period given a period index.
*
* @return New period index.
*/
size_t GetNextPeriod(const size_t period);
static const size_t MILLISECONDS_PER_SECOND = 1000; ///< The number of milliseconds in a second.
static const size_t MICROSECONDS_PER_SECOND = 1000000; ///< The number of microseconds in a second.
const uint64_t m_intervalTimerFrequency; ///< The IntervalTimer frequency.
size_t m_messagesPerSecond; ///< The message rate.
uint64_t m_periodTimeStamp; ///< The throttle period in IntervalTimer timestamp units.
size_t m_numberOfPeriods; ///< The number of periods.
PeriodInfoList m_periodInfoList;
size_t m_currentPeriod; ///< Index into m_periodInfoList of current period.
size_t m_lastResetPeriod; ///< The last period we reset to after a period of inactivity.
uint64_t m_currentPeriodStartTimeStamp;
uint64_t m_nextPeriodStartTimeStamp;
uint64_t m_nextNextPeriodStartTimeStamp;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_COMPARTMENTALIZED_MESSAGE_RATE_THROTTLER_H)
@@ -1,261 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Compress/ICompressor.h
*
* @brief Interface for various compression algorithms.
*/
#if (!defined ACTIV_BASE_COMPRESS_ICOMPRESSOR_H)
#define ACTIV_BASE_COMPRESS_ICOMPRESSOR_H
#include "ActivMiddleware/ActivBase/External.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Calculate size of destination buffer needed to compress a buffer of length sourceLength.
*
* To support Zlib, destination buffer must be at least 0.1% + 12 bytes the size of the source buffer.
* To support lz4, destination buffer must be at least 0.4% + 16 bytes the size of the source buffer.
*
* @param sourceLength length of the source buffer.
*
* @return size of destination buffer needed.
*/
#define ACTIV_COMPRESS_GET_DESTINATION_BUFFER_LENGTH(sourceLength) \
(static_cast<size_t>(((static_cast<uint64_t>((sourceLength)) * UINT64_C(1004)) / UINT64_C(1000)) + 16))
// ---------------------------------------------------------------------------------------------------------------------------------
//! Abstract base block compression and decompression class.
class ICompressor : private Boost::noncopyable
{
public:
//! Compression type enumeration.
enum Type
{
TYPE_NULL = 0,
TYPE_RDC = 1,
TYPE_ZLIB = 2,
TYPE_LZ4 = 3,
TYPE_ZSTD = 4,
NUM_TYPES
};
//! Compression and decompression statistics class.
class Stats
{
public:
//! Default constructor.
Stats();
/**
* @brief Update compression or decompression statistics.
*
* @param inputBytes number of input bytes.
* @param outputBytes number of output bytes.
*/
void UpdateStats(const uint64_t inputBytes, const uint64_t outputBytes);
//! Clear compression or decompression statistics.
void ClearStats();
uint64_t m_apiCount; ///< Number of API calls made.
uint64_t m_inputBytes; ///< Total number of input bytes.
uint64_t m_outputBytes; ///< Total number of output bytes.
};
//! Destructor.
ACTIV_BASE_API
virtual ~ICompressor() = 0;
//! Get the compressor type.
Type GetType() const;
/**
* @brief Compress a buffer.
*
* @param pDestination the resultant compressed buffer.
* @param destinationLength the length of the destination buffer.
* @param pSource the buffer to be compressed.
* @param sourceLength length of the source buffer.
* @param compressedLength the number of bytes used in the destination buffer.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_BUFFER_OVERFLOW
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_INVALID_FORMAT
* @retval STATUS_CODE_HEAP_EMPTY
*/
StatusCode Compress(void *pDestination, const size_t destinationLength, const void *pSource, const size_t sourceLength,
size_t &compressedLength);
/**
* @brief Decompress a buffer.
*
* @param pDestination the resultant decompressed buffer.
* @param destinationLength the length of the destination buffer.
* @param pSource the buffer to be decompressed.
* @param sourceLength length of the source buffer.
* @param decompressedLength the number of bytes used in the destination buffer.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_BUFFER_OVERFLOW
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_INVALID_FORMAT
* @retval STATUS_CODE_HEAP_EMPTY
*/
StatusCode Decompress(void *pDestination, const size_t destinationLength, const void *pSource,
const size_t sourceLength, size_t &decompressedLength);
/**
* @brief Compress a buffer.
*
* @param pDestination the resultant compressed buffer.
* @param destinationLength the length of the destination buffer.
* @param pSource the buffer to be compressed.
* @param sourceLength length of the source buffer.
* @param compressedLength the number of bytes used in the destination buffer.
* @param stats compression stats to update.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_BUFFER_OVERFLOW
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_INVALID_FORMAT
* @retval STATUS_CODE_HEAP_EMPTY
*/
virtual StatusCode Compress(void *pDestination, const size_t destinationLength, const void *pSource, const size_t sourceLength,
size_t &compressedLength, Stats &stats) = 0;
/**
* @brief Decompress a buffer.
*
* @param pDestination the resultant decompressed buffer.
* @param destinationLength the length of the destination buffer.
* @param pSource the buffer to be decompressed.
* @param sourceLength length of the source buffer.
* @param decompressedLength the number of bytes used in the destination buffer.
* @param stats decompression stats to update.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_BUFFER_OVERFLOW
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_INVALID_FORMAT
* @retval STATUS_CODE_HEAP_EMPTY
*/
virtual StatusCode Decompress(void *pDestination, const size_t destinationLength, const void *pSource,
const size_t sourceLength, size_t &decompressedLength, Stats &stats) = 0;
//! Get compress statistics.
const Stats &GetCompressStats() const;
//! Get decompress statistics.
const Stats &GetDecompressStats() const;
//! Clear compress statistics.
void ClearCompressStats();
//! Clear decompress statistics.
void ClearDecompressStats();
//! Get the type as a string.
ACTIV_BASE_API
static const char *TypeToString(const Type type);
protected:
/**
* @brief Constructor.
*
* @param type
*/
ACTIV_BASE_API
ICompressor(const Type type);
const Type m_type;
Stats m_compressStats; ///< Compression statistics.
Stats m_decompressStats; ///< Decompression statistics.
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline ICompressor::Type ICompressor::GetType() const
{
return m_type;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode ICompressor::Compress(void *pDestination, const size_t destinationLength, const void *pSource,
const size_t sourceLength, size_t &compressedLength)
{
return Compress(pDestination, destinationLength, pSource, sourceLength, compressedLength, m_compressStats);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode ICompressor::Decompress(void *pDestination, const size_t destinationLength, const void *pSource,
const size_t sourceLength, size_t &decompressedLength)
{
return Decompress(pDestination, destinationLength, pSource, sourceLength, decompressedLength, m_decompressStats);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const ICompressor::Stats &ICompressor::GetCompressStats() const
{
return m_compressStats;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const ICompressor::Stats &ICompressor::GetDecompressStats() const
{
return m_decompressStats;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void ICompressor::ClearCompressStats()
{
m_compressStats.ClearStats();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void ICompressor::ClearDecompressStats()
{
m_decompressStats.ClearStats();
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline ICompressor::Stats::Stats() :
m_apiCount(0),
m_inputBytes(0),
m_outputBytes(0)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void ICompressor::Stats::UpdateStats(const uint64_t inputBytes, const uint64_t outputBytes)
{
++m_apiCount;
m_inputBytes += inputBytes;
m_outputBytes += outputBytes;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void ICompressor::Stats::ClearStats()
{
m_apiCount = 0;
m_inputBytes = 0;
m_outputBytes = 0;
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_COMPRESS_ICOMPRESSOR_H)
@@ -1,42 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Compress/Lz4Compressor.h
*
* @brief Header file for lz4 compression class.
*/
#if (!defined ACTIV_COMPRESS_LZ4_COMPRESSOR_H)
#define ACTIV_COMPRESS_LZ4_COMPRESSOR_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Compress/ICompressor.h"
//! Activ namespace.
namespace Activ
{
//! Lz4 compression and decompression class (see http://code.google.com/p/lz4/).
class Lz4Compressor : public ICompressor
{
public:
//! Default constructor.
ACTIV_BASE_API
Lz4Compressor();
//! Destructor.
ACTIV_BASE_API
virtual ~Lz4Compressor() ACTIV_OVERRIDE;
// ICompressor interface.
using ICompressor::Compress;
using ICompressor::Decompress;
ACTIV_BASE_API
virtual StatusCode Compress(void *pDestination, const size_t destinationLength, const void *pSource, const size_t sourceLength,
size_t &compressedLength, Stats &stats) ACTIV_OVERRIDE;
ACTIV_BASE_API
virtual StatusCode Decompress(void *pDestination, const size_t destinationLength, const void *pSource,
const size_t sourceLength, size_t &decompressedLength, Stats &stats) ACTIV_OVERRIDE;
};
} // namespace Activ
#endif // (!defined ACTIV_COMPRESS_LZ4_COMPRESSOR_H)
@@ -1,42 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Compress/NullCompressor.h
*
* @brief Header file for no-op compression class.
*/
#if (!defined ACTIV_BASE_COMPRESS_NULL_COMPRESSOR_H)
#define ACTIV_BASE_COMPRESS_NULL_COMPRESSOR_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Compress/ICompressor.h"
//! Activ namespace.
namespace Activ
{
//! Null compression and decompression class.
class NullCompressor : public ICompressor
{
public:
//! Default constructor.
ACTIV_BASE_API
NullCompressor();
//! Destructor.
ACTIV_BASE_API
virtual ~NullCompressor() ACTIV_OVERRIDE;
// ICompressor interface.
using ICompressor::Compress;
using ICompressor::Decompress;
ACTIV_BASE_API
virtual StatusCode Compress(void *pDestination, const size_t destinationLength, const void *pSource, const size_t sourceLength,
size_t &compressedLength, Stats &stats) ACTIV_OVERRIDE;
ACTIV_BASE_API
virtual StatusCode Decompress(void *pDestination, const size_t destinationLength, const void *pSource,
const size_t sourceLength, size_t &decompressedLength, Stats &stats) ACTIV_OVERRIDE;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_COMPRESS_NULL_COMPRESSOR_H)
@@ -1,45 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Compress/RdcCompressor.h
*
* @brief Header file for RDC compression.
*/
#if (!defined ACTIV_BASE_COMPRESS_RDC_COMPRESSOR_H)
#define ACTIV_BASE_COMPRESS_RDC_COMPRESSOR_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Compress/ICompressor.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief RDC compression and decompression class (see code archive of Oct '92 edition of CUJ at
* http://www.ddj.com/dept/cpp/184402606).
*/
class RdcCompressor : public ICompressor
{
public:
//! Default constructor.
ACTIV_BASE_API
RdcCompressor();
//! Destructor.
ACTIV_BASE_API
virtual ~RdcCompressor() ACTIV_OVERRIDE;
// ICompressor interface.
using ICompressor::Compress;
using ICompressor::Decompress;
ACTIV_BASE_API
virtual StatusCode Compress(void *pDestination, const size_t destinationLength, const void *pSource, const size_t sourceLength,
size_t &compressedLength, Stats &stats) ACTIV_OVERRIDE;
ACTIV_BASE_API
virtual StatusCode Decompress(void *pDestination, const size_t destinationLength, const void *pSource,
const size_t sourceLength, size_t &decompressedLength, Stats &stats) ACTIV_OVERRIDE;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_COMPRESS_RDC_COMPRESSOR_H)
@@ -1,42 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Compress/ZlibCompressor.h
*
* @brief Header file for zlib compression.
*/
#if (!defined ACTIV_COMPRESS_ZLIB_COMPRESSOR_H)
#define ACTIV_COMPRESS_ZLIB_COMPRESSOR_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Compress/ICompressor.h"
//! Activ namespace.
namespace Activ
{
//! Zlib compression and decompression class (see http://www.gzip.org/zlib/).
class ZlibCompressor : public ICompressor
{
public:
//! Default constructor.
ACTIV_BASE_API
ZlibCompressor();
//! Destructor.
ACTIV_BASE_API
virtual ~ZlibCompressor() ACTIV_OVERRIDE;
// ICompressor interface.
using ICompressor::Compress;
using ICompressor::Decompress;
ACTIV_BASE_API
virtual StatusCode Compress(void *pDestination, const size_t destinationLength, const void *pSource, const size_t sourceLength,
size_t &compressedLength, Stats &stats) ACTIV_OVERRIDE;
ACTIV_BASE_API
virtual StatusCode Decompress(void *pDestination, const size_t destinationLength, const void *pSource,
const size_t sourceLength, size_t &decompressedLength, Stats &stats) ACTIV_OVERRIDE;
};
} // namespace Activ
#endif // (!defined ACTIV_COMPRESS_ZLIB_COMPRESSOR_H)
@@ -1,65 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Compress/ZstdCompressor.h
*
* @brief Header file for zstd compression class.
*/
#if (!defined ACTIV_COMPRESS_ZSTD_COMPRESSOR_H)
#define ACTIV_COMPRESS_ZSTD_COMPRESSOR_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Compress/ICompressor.h"
#include "ActivMiddleware/CxxYZ/memory.h"
//! Necessary Zstd stream forward declarations.
struct ZSTD_CCtx_s;
typedef struct ZSTD_CCtx_s ZSTD_CCtx;
struct ZSTD_DCtx_s;
typedef struct ZSTD_DCtx_s ZSTD_DCtx;
//! Activ namespace.
namespace Activ
{
//! Zstd compression and decompression class
class ZstdCompressor : public ICompressor
{
public:
//! Default constructor.
ACTIV_BASE_API
ZstdCompressor();
//! Destructor.
ACTIV_BASE_API
virtual ~ZstdCompressor() ACTIV_OVERRIDE;
// ICompressor interface.
using ICompressor::Compress;
using ICompressor::Decompress;
ACTIV_BASE_API
virtual StatusCode Compress(void *pDestination, const size_t destinationLength, const void *pSource, const size_t sourceLength,
size_t &compressedLength, Stats &stats) ACTIV_OVERRIDE;
ACTIV_BASE_API
virtual StatusCode Decompress(void *pDestination, const size_t destinationLength, const void *pSource,
const size_t sourceLength, size_t &decompressedLength, Stats &stats) ACTIV_OVERRIDE;
private:
//! The zstd context custom deleter class.
class ZstdContextDeleter
{
public:
void operator()(ZSTD_CCtx * const pCompressionStream) const;
void operator()(ZSTD_DCtx * const pDecompressionStream) const;
};
typedef CxxYZ::unique_ptr<ZSTD_CCtx, ZstdContextDeleter> CCtxPtr; ///< The compression context pointer type definition.
typedef CxxYZ::unique_ptr<ZSTD_DCtx, ZstdContextDeleter> DCtxPtr; ///< The decompression context pointer type definition.
CCtxPtr m_pCompressionContext; ///< The compression context pointer.
DCtxPtr m_pDecompressionContext; ///< The decompression context pointer.
};
} // namespace Activ
#endif // (!defined ACTIV_COMPRESS_ZSTD_COMPRESSOR_H)
@@ -1,316 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/ConsoleWindow.h
*
* @brief Header file for console window.
*/
#if (!defined ACTIV_BASE_CONSOLE_WINDOW_H)
#define ACTIV_BASE_CONSOLE_WINDOW_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/Misc/TypeSafeFlags.h"
#if (defined ACTIV_PLATFORM_POSIX)
#include "ActivMiddleware/CxxYZ/mutex.h"
extern "C" typedef struct _win_st WINDOW;
#endif
//! Activ namespace.
namespace Activ
{
class MessageBuilder;
class MessageValidator;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Console window class.
*/
class ConsoleWindow : private Boost::noncopyable
{
public:
/**
* @brief Cursor coordinate.
*/
class Coord
{
public:
/**
* @brief Default constructor. x & y coordinates set to 0.
*/
Coord();
/**
* @brief Constructor.
*
* @param x coordinate.
* @param y coordinate.
*/
Coord(const int16_t x, const int16_t y);
/**
* @brief Equality operator.
*
* @param rhs to compare with.
*
* @return boolean.
*/
bool operator==(const Coord &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs to compare with.
*
* @return boolean.
*/
bool operator!=(const Coord &rhs) const;
/**
* @brief Serialize to a MessageBuilder.
*
* @param messageBuilder to serialize into.
*
* @return STATUS_CODE_SUCCESS or an error code.
*/
ACTIV_BASE_API StatusCode Serialize(MessageBuilder &messageBuilder) const;
/**
* @brief Deserialize from a MessageValidator into this object.
*
* @param messageValidator to deserialize from.
*
* @return STATUS_CODE_SUCCESS or an error code.
*/
ACTIV_BASE_API StatusCode Deserialize(MessageValidator &messageValidator);
int16_t m_x;
int16_t m_y;
};
//! Flags.
class Flags : public TypeSafeFlags::Underlying<uint32_t>
{
public:
typedef TypeSafeFlags::Value<Flags, 0x00000000> None;
typedef TypeSafeFlags::Value<Flags, 0x00000001> NoAutoscroll; ///< Don't scroll the window when output reaches the bottom
typedef TypeSafeFlags::Value<Flags, 0x00000002> ImmediateRefresh; ///< Refresh display immediately after a write
typedef TypeSafeFlags::Type<Flags, None> Type;
};
/**
* @brief Constructor.
*
* @param flags flags defining console behaviour.
*/
ACTIV_BASE_API ConsoleWindow(const Flags::Type flags = Flags::Type());
/**
* @brief Destructor.
*/
ACTIV_BASE_API ~ConsoleWindow();
/**
* @brief Wait for input on the console.
*
* Note the resolution of the timeout on Win32 is around 10ms, and on Linux is 100ms.
*
* @param timeoutPeriod how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS there is input queued on the console.
* @retval STATUS_CODE_TIMEOUT no input queued in the timeout period.
* @retval STATUS_CODE_FAILURE an error occured.
*/
ACTIV_BASE_API StatusCode WaitForInput(const TimeoutPeriod timeoutPeriod = 100) const;
/**
* @brief Read a complete line from the console. Note returned buffer will not contain terminating
* cr / lf characters. This is a blocking call.
*
* @param input reference to a string to receive input.
*
* @retval STATUS_CODE_SUCCESS.
* @retval ... did not read a complete line.
*/
ACTIV_BASE_API StatusCode ReadLine(String &input) const;
/**
* @brief Get the visible console display size.
*
* @param size to receive the size.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode GetDisplaySize(Coord &size) const;
/**
* @brief Set the visible console display size.
*
* If the current buffer size is smaller in either dimension than the requested display size, it is increased.
*
* @param size the new size.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode SetDisplaySize(const Coord &size);
/**
* @brief Get the console buffer size. The buffer size may be larger than the visible display.
*
* @param size to receive the size.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode GetBufferSize(Coord &size) const;
/**
* @brief Set the console buffer size. The buffer size may be larger than the visible display.
*
* If the requested console buffer size is smaller in either dimension than the current display size, it is increased.
*
* @param size the new size.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode SetBufferSize(const Coord &size);
/**
* @brief Get the current cursor position.
*
* @param coord to receive the cursor position.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode GetCursorPosition(Coord &coord) const;
/**
* @brief Set the cursor position.
*
* @param coord the position to place the cursor.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode SetCursorPosition(const Coord &coord);
/**
* @brief Set the cursor visibility.
*
* @param isVisible true to make cursor visible, false to make invisible.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode SetCursorVisibility(const bool isVisible);
/**
* @brief Clear the console from a coordinate to the end.
*
* Note the current cursor position will not be altered by this call.
*
* @param coord the coordinate to clear from.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode ClearFrom(const Coord &coord);
/**
* @brief Write a string beginning at a specified coordinate.
*
* Note the current cursor position will not be altered by this call.
*
* @param coord the coordinate to start writing from.
* @param pStr the string to write.
* @param length number of characters in \a string to write, default is all.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode WriteAt(const Coord &coord, const char * const pStr, const size_t length = 0);
/**
* @brief Write formatted output to the console from the current cursor position.
*
* @param pStr the format string.
* @param ... args.
*/
ACTIV_PRINTF_FUNCTION(printf, 2, 3)
ACTIV_BASE_API void Printf(const char * const pStr, ...) const;
/**
* @brief Set title of console.
*
* @param title
*/
ACTIV_BASE_API static void SetTitle(const String &title);
private:
//! Platform-common construction.
void CommonCtor();
//! Platform-common destruction.
void CommonDtor();
#if (defined ACTIV_PLATFORM_WINDOWS)
const HANDLE m_outputHandle; ///< Console output handle.
const HANDLE m_inputHandle; ///< Console input handle.
DWORD m_initialMode; ///< Initial console mode settings.
#elif (defined ACTIV_PLATFORM_POSIX)
WINDOW * const m_pWindow; ///< ncurses WINDOW.
mutable CxxYZ::mutex m_mutex;
Coord m_displaySize; ///< To keep track of current display size.
#else
#error Configure for this platform
#endif
bool m_initialIsCursorVisible; ///< Initial cursor visibility.
Coord m_initialDisplaySize; ///< Initial display size.
Coord m_initialBufferSize; ///< Initial buffer size.
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline ConsoleWindow::Coord::Coord() :
m_x(0),
m_y(0)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline ConsoleWindow::Coord::Coord(const int16_t x, const int16_t y) :
m_x(x),
m_y(y)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool ConsoleWindow::Coord::operator==(const Coord &rhs) const
{
return (m_x == rhs.m_x) && (m_y == rhs.m_y);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool ConsoleWindow::Coord::operator!=(const Coord &rhs) const
{
return !operator==(rhs);
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_CONSOLE_WINDOW_H)
@@ -1,57 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/CpuDetail.h
*
* @brief Header file for the cpu detail class.
*/
#if (!defined ACTIV_BASE_CPU_DETAIL_H)
#define ACTIV_BASE_CPU_DETAIL_H
#include "ActivMiddleware/ActivMiddleware.h"
//! Activ namespace.
namespace Activ
{
//! Cpu detail class.
class CpuDetail
{
public:
//! Default constructor.
CpuDetail();
typedef uint16_t CoreId; ///< The CoreId type definition.
static const uint32_t UNKNOWN_NUMA_NODE = Boost::integer_traits<uint32_t>::const_max;
CoreId m_osCoreId; ///< The os core id for this logical core.
CoreId m_orderedCoreId; ///< An artificially generated system wide logical core id.
uint32_t m_packageId; ///< The package id for this core.
uint32_t m_numaNode; ///< The numa node of this core.
CoreId m_packageCoreId; ///< The physical core id for this physical core within the package.
CoreId m_coreThreadId; ///< The thread Id for this logical core within the physical core.
CoreId m_osPackageCoreId; ///< The core id within this package as seen by the OS.
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline CpuDetail::CpuDetail() :
m_osCoreId(0),
m_orderedCoreId(0),
m_packageId(0),
m_numaNode(UNKNOWN_NUMA_NODE),
m_packageCoreId(0),
m_coreThreadId(0),
m_osPackageCoreId(0)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
typedef std::vector<CpuDetail> CpuDetailList; ///< Cpu detail list.
} // namespace Activ
#endif // (!defined ACTIV_BASE_CPU_DETAIL_H)
@@ -1,137 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Crc32Generator.h
*
* @brief Header file for crc32 generator class.
*/
#if (!defined ACTIV_BASE_CRC32_GENERATOR_H)
#define ACTIV_BASE_CRC32_GENERATOR_H
#include "ActivMiddleware/ActivBase/External.h"
#if (defined ACTIV_PROCESSOR_X86_64)
# if (defined ACTIV_COMPILER_GCC) || (defined ACTIV_COMPILER_VISUAL_C)
# define ACTIV_CRC32_INTRINSICS
# endif
#elif (defined ACTIV_PROCESSOR_ARM64)
# if (defined ACTIV_COMPILER_GCC)
# define ACTIV_CRC32_INTRINSICS
# endif
#endif
//! Activ namespace.
namespace Activ
{
/*
* @brief Crc32Generator
*
* @tparam If true use the standard (ethernet) polynomial else use Castognoli. Only Castognoli is compatible with SSE4.2.
*/
template<bool USE_STANDARD_LOOKUP_TABLE = false>
class Crc32Generator
{
public:
//! Default constructor
ACTIV_BASE_API Crc32Generator();
//! Is Crc32 intrinsic supported.
ACTIV_BASE_API static bool IsCrc32IntrinsicSupported();
/**
* @brief Function operator.
*
* @param string
*
* @return The calculated crc32.
*/
uint32_t operator()(const String &string) const;
/**
* @brief Function operator.
*
* @param pData
* @param dataLength
* @param initialCrc
*
* @return The calculated crc32.
*/
uint32_t operator()(const void *pData, const size_t dataLength, const uint32_t initialCrc) const;
/**
* @brief Calculate the crc32 of the provided data using the standard algorithm.
*
* @param pData
* @param dataLength
* @param initialCrc
*
* @return The calculated crc32.
*/
ACTIV_BASE_API static uint32_t CalculateUsingStandardAlgorithm(const void *pData, const size_t dataLength,
const uint32_t initialCrc);
/**
* @brief Calculate the crc32 of the provided data using the splice by 8 algorithm.
*
* @param pData
* @param dataLength
* @param initialCrc
*
* @return The calculated crc32.
*/
ACTIV_BASE_API static uint32_t CalculateUsingSpliceBy8Algorithm(const void *pData, const size_t dataLength,
const uint32_t initialCrc);
#if (defined ACTIV_CRC32_INTRINSICS)
/**
* @brief Calculate the crc32 of the provided data using the crc32 cpu instruction.
*
* @param pData
* @param dataLength
* @param initialCrc
*
* @return The calculated crc32.
*/
ACTIV_BASE_API static uint32_t CalculateUsingIntrinsic(const void *pData, const size_t dataLength,
const uint32_t initialCrc);
#endif
/**
* @brief Calculate the crc32 of the provided data using a simple endian safe algorithm.
*
* @param pData
* @param dataLength
* @param initialCrc
*
* @return The calculated crc32.
*/
ACTIV_BASE_API static uint32_t CalculateUsingSimpleAlgorithm(const void *pData, const size_t dataLength,
const uint32_t initialCrc);
private:
typedef uint32_t (*CrcFunction)(const void *, const size_t, const uint32_t);
const CrcFunction crcFunction;
};
// ---------------------------------------------------------------------------------------------------------------------------------
template<bool USE_STANDARD_LOOKUP_TABLE>
ACTIV_FORCE_INLINE uint32_t Crc32Generator<USE_STANDARD_LOOKUP_TABLE>::operator()(const String &string) const
{
return operator() (string.data(), string.length(), 0);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<bool USE_STANDARD_LOOKUP_TABLE>
ACTIV_FORCE_INLINE uint32_t Crc32Generator<USE_STANDARD_LOOKUP_TABLE>::operator()(const void * pData, const size_t dataLength,
const uint32_t initialCrc) const
{
return crcFunction(pData, dataLength, initialCrc);
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_CRC32_GENERATOR_H)
@@ -1,41 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/CrtException.h
*
* @brief Header file for c runtime exception class.
*/
#if (!defined ACTIV_BASE_CRT_EXCEPTION_H)
#define ACTIV_BASE_CRT_EXCEPTION_H
#include "ActivMiddleware/ActivBase/Exception.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief C runtime exception class.
*
* CrtException encapsulates errors from c run time library calls.
*/
class CrtException : public Exception
{
public:
/**
* @brief Default constructor.
*
* @param file the file which raised the exception.
* @param function the function which raised the exception.
* @param line the line number which raised the exception.
* @param errorCode the exception specific error code.
* @param message the exception message.
*/
ACTIV_BASE_API CrtException(const char *file, const char *function, uint_fast32_t line, const uint_fast32_t errorCode,
const String &message = "");
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_CRT_EXCEPTION_H)
@@ -1,168 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/CtrlHandler.h
*
* @brief Header file for the CtrlHandler class.
*/
#if (!defined ACTIV_BASE_CTRL_HANDLER_H)
#define ACTIV_BASE_CTRL_HANDLER_H
#include "ActivMiddleware/ActivBase/External.h"
#if (ACTIV_PLATFORM_LINUX_HAS_MIN_GLIBC(2, 9))
#define ACTIV_BASE_CTRL_HANDLER_USE_SIGNAL_FD
#endif
#include "ActivMiddleware/CxxYZ/atomic.h"
#if (defined ACTIV_BASE_CTRL_HANDLER_USE_SIGNAL_FD)
#include "ActivMiddleware/ActivBase/EventManagee.h"
#include "ActivMiddleware/Misc/ScopedHelper.h"
#endif
#if (defined ACTIV_PLATFORM_POSIX)
#include "ActivMiddleware/CxxYZ/thread.h"
#include ACTIV_BOOST_INCLUDE(scoped_ptr.hpp)
#include <signal.h>
#endif
//! Activ namespace.
namespace Activ
{
/**
* @brief Ctrl handler class.
*
* Note only one instance of CtrlHandler is allowed on the Windows platform (per process).
*/
class CtrlHandler : private Boost::noncopyable
{
public:
/**
* @brief List of ctrl event types.
*/
enum EventType
{
CTRL_C,
CTRL_BREAK,
CTRL_EXIT_PROCESS,
CTRL_LOGOFF_USER,
CTRL_SHUTDOWN_MACHINE,
CTRL_UNKNOWN
};
#if (defined ACTIV_BASE_CTRL_HANDLER_USE_SIGNAL_FD)
/**
* @brief Constructor.
*
* This constructor (if available with recent enough glibc) does not incur the cost of an additional thread, by
* using signalfd and receiving signal notifications via the provided EventManager. As such, the OnEvent() callback
* will be invoked in the context of the EventManager's thread.
*
* @param eventManager
*
* @throw Exception if the handler could not be installed.
*/
ACTIV_BASE_API CtrlHandler(EventManager &eventManager);
#endif
/**
* @brief Constructor.
*
* On Posix, this constructor creates a thread to sigwait() for signals. As such, the OnEvent() callback is invoked
* from the context of this thread.
*
* @throw Exception if the handler could not be installed.
*/
ACTIV_BASE_API CtrlHandler();
//! Destructor.
ACTIV_BASE_API virtual ~CtrlHandler();
protected:
/**
* @brief Callback when a ctrl event occurs.
*
* No guarantees are provided about which thread will invoke this callback - unless
* ACTIV_BASE_CTRL_HANDLER_USE_SIGNAL_FD is defined, in which case it will be a thread running the EventManager provided
* to the constructor.
*
* @param eventType the type of ctrl event that has occured.
*
* @retval true if the event has been handled.
* @retval false if the event has not been handled.
*/
ACTIV_BASE_API virtual bool OnEvent(const EventType eventType);
private:
#if (defined ACTIV_PLATFORM_WINDOWS)
static CxxYZ::atomic<CtrlHandler *> m_pCtrlHandler; ///< Can only have one ctrl handler per process.
static BOOL WINAPI HandlerFunction(DWORD ctrlType);
#elif (defined ACTIV_PLATFORM_POSIX)
class SignalMask
{
public:
SignalMask();
~SignalMask();
sigset_t m_originalSigSet;
sigset_t m_blockSigSet;
};
const SignalMask m_signalMask;
#endif
#if (defined ACTIV_BASE_CTRL_HANDLER_USE_SIGNAL_FD)
class SignalFd
{
public:
SignalFd(const sigset_t &sigset);
~SignalFd();
const int m_fd;
};
//! EventManagee to receive signalfd events.
class EventManagee : public Activ::EventManagee
{
public:
EventManagee(CtrlHandler &ctrlHandler, EventManager &eventManager);
~EventManagee();
protected:
virtual void OnEvents(const Events events) ACTIV_OVERRIDE;
private:
CtrlHandler &m_ctrlHandler;
};
Boost::scoped_ptr<const SignalFd> m_pSignalFd;
Boost::scoped_ptr<EventManagee> m_pEventManagee;
#endif
#if (defined ACTIV_PLATFORM_POSIX)
void ThreadFunction();
CxxYZ::atomic_bool m_isShuttingDown;
CxxYZ::thread m_thread; ///< Thread waiting for signals.
#elif (!defined ACTIV_PLATFORM_WINDOWS)
#error Configure for this platform
#endif
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_CTRL_HANDLER_H)
@@ -1,585 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Detail/CommandLineParserDetail.h
*
* @brief Implementation details for CommandLineParser.
*/
#if (!defined ACTIV_BASE_DETAIL_COMMAND_LINE_PARSER_DETAIL_H)
#define ACTIV_BASE_DETAIL_COMMAND_LINE_PARSER_DETAIL_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#include ACTIV_BOOST_INCLUDE(any.hpp)
#include ACTIV_BOOST_INCLUDE(optional/optional.hpp)
#include ACTIV_BOOST_INCLUDE(optional/optional_io.hpp)
#include <iostream>
#include ACTIV_BOOST_INCLUDE(program_options.hpp)
//! Activ namespace.
namespace Activ
{
class CommandLineParser;
namespace CommandLineParserDetail
{
/**
* @brief Default action to take for a command line value.
*/
template<typename T>
class ValueStore
{
public:
/**
* @brief Constructor.
*
* @param value where to store the value.
*/
ValueStore(T &value) :
m_value(value)
{
}
/**
* @brief Function operator.
*
* @param value value to store in the location provided to the constructor.
*/
void operator()(const T &value)
{
m_value = value;
}
private:
T &m_value; ///< location to store value from command line
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Description of a command line parameter/switch.
*/
template<typename T>
class Description
{
public:
/**
* @brief Constructor.
*
* @param name name of the parameter/switch.
* @param description descriptive text of the parameter/switch.
* @param notifier action to take when parameter/switch is seen on the command line.
*/
Description(const String &name, const String &description, const CxxYZ::function<void (const T &)> &notifier) :
m_name(name),
m_description(description),
m_notifier(notifier)
{
}
const String m_name; ///< name of the parameter/switch
const String m_description; ///< descriptive text of the parameter/switch
const CxxYZ::function<void (const T &)> m_notifier; ///< action to take when parameter/switch is seen on the command line
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Description of a command line parameter/switch with default value.
*/
template<typename T>
class DefaultDescription : public Description<T>
{
public:
/**
* @brief Constructor.
*
* @param name name of the parameter/switch.
* @param description descriptive text of the parameter/switch.
* @param defaultValue the default value to use if not provided on the command line.
* @param notifier action to take when parameter/switch is seen on the command line.
*/
DefaultDescription(const String &name, const String &description, const T &defaultValue,
const CxxYZ::function<void (const T &)> &notifier) :
Description<T>(name, description, notifier),
m_defaultValue(defaultValue)
{
}
const T m_defaultValue; ///< the default value to use if not provided on the command line
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Description of a mandatory command line parameter.
*/
template<typename T>
class MandatoryParameterDescription : public Description<T>
{
public:
/**
* @brief Constructor.
*
* @param name name of the parameter.
* @param description descriptive text of the parameter.
* @param notifier action to take when parameter is seen on the command line.
*/
MandatoryParameterDescription(const String &name, const String &description,
const CxxYZ::function<void (const T &)> &notifier) :
Description<T>(name, description, notifier)
{
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Description of an optional command line parameter.
*/
template<typename T>
class OptionalParameterDescription : public DefaultDescription<T>
{
public:
/**
* @brief Constructor.
*
* @param name name of the parameter.
* @param description descriptive text of the parameter.
* @param defaultValue the default value to use if not provided on the command line.
* @param notifier action to take when parameter is seen on the command line.
*/
OptionalParameterDescription(const String &name, const String &description, const T &defaultValue,
const CxxYZ::function<void (const T &)> &notifier) :
DefaultDescription<T>(name, description, defaultValue, notifier)
{
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Description of a mandatory command line switch.
*/
template<typename T>
class MandatorySwitchDescription : public Description<T>
{
public:
/**
* @brief Constructor.
*
* @param name name of the switch.
* @param description descriptive text of the switch.
* @param notifier action to take when switch is seen on the command line.
*/
MandatorySwitchDescription(const String &name, const String &description, const CxxYZ::function<void (const T &)> &notifier) :
Description<T>(name, description, notifier)
{
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Description of an optional command line switch.
*/
template<typename T>
class OptionalSwitchDescription : public DefaultDescription<T>
{
public:
/**
* @brief Constructor.
*
* @param name name of the switch.
* @param description descriptive text of the switch.
* @param defaultValue the default value to use if not provided on the command line.
* @param notifier action to take when switch is seen on the command line.
*/
OptionalSwitchDescription(const String &name, const String &description, const T &defaultValue,
const CxxYZ::function<void (const T &)> &notifier) :
DefaultDescription<T>(name, description, defaultValue, notifier)
{
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Description of a boolean command line switch.
*/
class BooleanSwitchDescription : public Description<bool>
{
public:
/**
* @brief Constructor.
*
* @param name name of the switch.
* @param description descriptive text of the switch.
* @param notifier action to take when switch is seen on the command line.
*/
BooleanSwitchDescription(const String &name, const String &description, const CxxYZ::function<void (const bool &)> &notifier) :
Description<bool>(name, description, notifier)
{
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
class DescriptionAppender;
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Implementation details of CommandLineParser.
*/
class CommandLineParserImpl : private Boost::noncopyable
{
public:
/**
* @brief Constructor.
*
* @param commandLineParser
*/
CommandLineParserImpl(CommandLineParser &commandLineParser);
/**
* @brief Process a command line.
*
* @param argc as passed to main(),
* @param argv as passed to main().
* @param outStream iostream to print usage or version to.
*
* @retval true command line parsed.
* @retval false help or version switch was passed. PrintUsage() or PrintVersion() has been called.
*
* @throw Exception.
* @throw Boost::program_options::error.
*/
bool Process(const int argc, char *argv[], std::ostream &outStream);
/**
* @brief Print usage display.
*
* @param argv0 argv[0] from main().
* @param outStream iostream to print usage to.
*/
void PrintUsage(const String &argv0, std::ostream &outStream) const;
/**
* @brief Print version.
*
* @param outStream iostream to print version to.
*/
void PrintVersion(std::ostream &outStream) const;
/**
* @brief Determines if the element has been set to a default value or from the command line.
*
* @param name is the string to check if it is defaulted or not. This string must match the long name of the
* Parameter, Switch etc... that you wish to check.
*
* @return true if it is defaulted.
*/
bool IsDefaultValue(const String &name) const;
private:
/**
* @brief Get the program name.
*
* @brief argv0 argv[0] as provided to main().
*
* @return The program name.
*/
static String GetProgramName(const String &argv0);
/**
* @brief Get the display width.
*
* @return The display width.
*/
static uint32_t GetLineLength();
CommandLineParser & m_commandLineParser;
const uint32_t m_lineLength;
Boost::program_options::options_description m_mandatoryParameterDescriptions;
Boost::program_options::options_description m_optionalParameterDescriptions;
Boost::program_options::positional_options_description m_positionalDescriptions;
Boost::program_options::options_description m_mandatorySwitchDescriptions;
Boost::program_options::options_description m_optionalSwitchDescriptions;
Boost::program_options::variables_map m_variablesMap;
friend class DescriptionAppender;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Helper class to build description.
*/
class DescriptionAppender
{
public:
/**
* @brief Constructor.
*
* @param commandLineParserImpl CommandLineParserImpl to append descriptions to.
*/
DescriptionAppender(CommandLineParserImpl &commandLineParserImpl);
/**
* @brief Append a mandatory parameter description.
*
* @param parameterDescription ParameterDescription to append.
*
* @return *this.
*/
template<typename T>
DescriptionAppender &operator()(const MandatoryParameterDescription<T> &parameterDescription)
{
if (parameterDescription.m_name.empty())
ACTIV_THROW(StatusCodeException, STATUS_CODE_INVALID_FORMAT);
m_commandLineParserImpl.m_mandatoryParameterDescriptions.add_options()
(
parameterDescription.m_name.c_str(),
Boost::program_options::value<T>()->notifier(parameterDescription.m_notifier),
parameterDescription.m_description.c_str()
);
m_commandLineParserImpl.m_positionalDescriptions.add(parameterDescription.m_name.c_str(), 1);
return *this;
}
/**
* @brief Append a mandatory parameter list description.
*
* @param parameterDescription ParameterDescription to append.
*
* @return *this.
*/
template<typename T>
DescriptionAppender &operator()(const MandatoryParameterDescription<std::vector<T> > &parameterDescription)
{
if (parameterDescription.m_name.empty())
ACTIV_THROW(StatusCodeException, STATUS_CODE_INVALID_FORMAT);
m_commandLineParserImpl.m_mandatoryParameterDescriptions.add_options()
(
parameterDescription.m_name.c_str(),
Boost::program_options::value<std::vector<T> >()->composing()->notifier(parameterDescription.m_notifier),
parameterDescription.m_description.c_str()
);
m_commandLineParserImpl.m_positionalDescriptions.add(parameterDescription.m_name.c_str(), -1);
return *this;
}
/**
* @brief Append an optional parameter description.
*
* @param parameterDescription OptionalParameterDescription to append.
*
* @return *this.
*/
template<typename T>
DescriptionAppender &operator()(const OptionalParameterDescription<T> &parameterDescription)
{
if (parameterDescription.m_name.empty())
ACTIV_THROW(StatusCodeException, STATUS_CODE_INVALID_FORMAT);
// disallow short options
if (String::npos != parameterDescription.m_name.find_first_of(','))
ACTIV_THROW(StatusCodeException, STATUS_CODE_INVALID_FORMAT);
m_commandLineParserImpl.m_optionalParameterDescriptions.add_options()
(
parameterDescription.m_name.c_str(),
Boost::program_options::value<T>()->default_value(parameterDescription.m_defaultValue)->notifier(
parameterDescription.m_notifier),
parameterDescription.m_description.c_str()
);
m_commandLineParserImpl.m_positionalDescriptions.add(parameterDescription.m_name.c_str(), 1);
return *this;
}
/**
* @brief Append an optional parameter list description.
*
* @param parameterDescription OptionalParameterDescription to append.
*
* @return *this.
*/
template<typename T>
DescriptionAppender &operator()(const OptionalParameterDescription<std::vector<T> > &parameterDescription)
{
if (parameterDescription.m_name.empty())
ACTIV_THROW(StatusCodeException, STATUS_CODE_INVALID_FORMAT);
// disallow short options
if (String::npos != parameterDescription.m_name.find_first_of(','))
ACTIV_THROW(StatusCodeException, STATUS_CODE_INVALID_FORMAT);
m_commandLineParserImpl.m_optionalParameterDescriptions.add_options()
(
parameterDescription.m_name.c_str(),
Boost::program_options::value<std::vector<T> >()->default_value(parameterDescription.m_defaultValue, "")->
composing()->notifier(parameterDescription.m_notifier),
parameterDescription.m_description.c_str()
);
m_commandLineParserImpl.m_positionalDescriptions.add(parameterDescription.m_name.c_str(), -1);
return *this;
}
/**
* @brief Append a mandatory switch description.
*
* @param switchDescription MandatorySwitchDescription to append.
*
* @return *this.
*/
template<typename T>
DescriptionAppender &operator()(const MandatorySwitchDescription<T> &switchDescription)
{
m_commandLineParserImpl.m_mandatorySwitchDescriptions.add_options()
(
switchDescription.m_name.c_str(),
Boost::program_options::value<T>()->notifier(switchDescription.m_notifier),
switchDescription.m_description.c_str()
);
return *this;
}
/**
* @brief Append a mandatory switch list description.
*
* @param switchDescription MandatorySwitchDescription to append.
*
* @return *this.
*/
template<typename T>
DescriptionAppender &operator()(const MandatorySwitchDescription<std::vector<T> > &switchDescription)
{
m_commandLineParserImpl.m_mandatorySwitchDescriptions.add_options()
(
switchDescription.m_name.c_str(),
Boost::program_options::value<std::vector<T> >()->composing()->notifier(switchDescription.m_notifier),
switchDescription.m_description.c_str()
);
return *this;
}
/**
* @brief Append an optional switch description with default value.
*
* @param switchDescription OptionalSwitchDescription to append.
*
* @return *this.
*/
template<typename T>
DescriptionAppender &operator()(const OptionalSwitchDescription<T> &switchDescription)
{
m_commandLineParserImpl.m_optionalSwitchDescriptions.add_options()
(
switchDescription.m_name.c_str(),
Boost::program_options::value<T>()->default_value(switchDescription.m_defaultValue)->
notifier(switchDescription.m_notifier),
switchDescription.m_description.c_str()
);
return *this;
}
/**
* @brief Overload of OptionalSwitchDescription for handling Strings.
*
* @param switchDescription OptionalSwitchDescription of type String to append.
*
* @return *this.
*/
DescriptionAppender& operator()(const OptionalSwitchDescription<String> &switchDescription)
{
m_commandLineParserImpl.m_optionalSwitchDescriptions.add_options()
(
switchDescription.m_name.c_str(),
Boost::program_options::value<String>()->default_value(switchDescription.m_defaultValue)->
notifier(switchDescription.m_notifier),
switchDescription.m_description.c_str()
);
return *this;
}
/**
* @brief Append an optional switch list description with default value.
*
* @param switchDescription OptionalSwitchDescription to append.
*
* @return *this.
*/
template<typename T>
DescriptionAppender &operator()(const OptionalSwitchDescription<std::vector<T> > &switchDescription)
{
m_commandLineParserImpl.m_optionalSwitchDescriptions.add_options()
(
switchDescription.m_name.c_str(),
Boost::program_options::value<std::vector<T> >()->default_value(switchDescription.m_defaultValue, "")->composing()->
notifier(switchDescription.m_notifier),
switchDescription.m_description.c_str()
);
return *this;
}
/**
* @brief Append a boolean switch description.
*
* @param booleanSwitchDescription BooleanSwitchDescription to append.
*
* @return *this.
*/
DescriptionAppender &operator()(const BooleanSwitchDescription &booleanSwitchDescription)
{
m_commandLineParserImpl.m_optionalSwitchDescriptions.add_options()
(
booleanSwitchDescription.m_name.c_str(),
Boost::program_options::bool_switch()->notifier(booleanSwitchDescription.m_notifier),
booleanSwitchDescription.m_description.c_str()
);
return *this;
}
private:
CommandLineParserImpl & m_commandLineParserImpl;
};
} // namespace CommandLineParserDetail
} // namespace Activ
#endif // (!defined ACTIV_BASE_DETAIL_COMMAND_LINE_PARSER_DETAIL_H)
@@ -1,325 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Detail/IntrusiveSetHelperDetail.h
*
* @brief Header file for implementation details for intrusive set helper.
*/
#if (!defined ACTIV_BASE_INTRUSIVE_SET_HELPER_DETAIL_H)
#define ACTIV_BASE_INTRUSIVE_SET_HELPER_DETAIL_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Crc32Generator.h"
#include ACTIV_BOOST_INCLUDE(intrusive/set.hpp)
#include ACTIV_BOOST_INCLUDE(intrusive/unordered_set.hpp)
#include ACTIV_BOOST_INCLUDE(type_traits/conditional.hpp)
//! Activ namespace.
namespace Activ
{
namespace IntrusiveSetHelper
{
namespace Detail
{
//! The default link mode used for the set and unordered set.
typedef Boost::intrusive::link_mode<Boost::intrusive::normal_link> DefaultLinkMode;
typedef Boost::intrusive::link_mode<Boost::intrusive::safe_link> SafeLinkMode;
typedef Boost::intrusive::link_mode<Boost::intrusive::auto_unlink> AutoUnlinkMode;
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! Unordered base set hook helper class.
template<bool STORE_HASH>
class UnorderedSetBaseHookHelper : public
Boost::intrusive::make_unordered_set_base_hook<DefaultLinkMode, Boost::intrusive::store_hash<STORE_HASH> >::type
{
public:
static const bool StoreHash = STORE_HASH;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
// The delete disposer object function.
template<typename T>
class DeleteDisposer
{
public:
void operator()(T *pT)
{
delete pT;
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! Hash selector class. Selects the most appropriate hash function based on the type of KEY.
template<typename T, typename KEY, typename GET_KEY_FUNC>
class HashSelector
{
private:
//! Crc32 hash.
class Crc32Hash
{
public:
/**
* @brief Function operator.
*
* @param key
*
* @return The hash of the key.
*/
size_t operator()(const KEY &key) const
{
return static_cast<size_t>(m_crc32Generator(key));
}
/**
* @brief Function operator. Assumes T has a member function GetKey().
*
* @param t
*
* @return The hash of the objects key.
*/
size_t operator()(const T &t) const
{
return operator()(GET_KEY_FUNC()(t));
}
private:
Crc32Generator<> m_crc32Generator;
};
//! Boost hash
class BoostHash
{
public:
/**
* @brief Function operator.
*
* @param key
*
* @return The hash of the key.
*/
size_t operator()(const KEY &key) const
{
return static_cast<size_t>(Boost::hash<KEY>()(key));
}
/**
* @brief Function operator. Assumes T has a member function GetKey().
*
* @param t
*
* @return The hash of the objects key.
*/
size_t operator()(const T &t) const
{
return operator()(GET_KEY_FUNC()(t));
}
};
public:
typedef typename Boost::conditional<
Boost::is_integral<KEY>::value,
BoostHash,
Crc32Hash>::type type;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! Bucket manager class.
template<typename SET>
class BucketManager
{
public:
typedef typename SET::bucket_traits BucketTraits;
/**
* @brief Constructor.
*
* @param initialNumberOfBuckets
* @param bucketGrowFillPercent
* @param bucketShrinkFillPercent
*/
BucketManager(const size_t initialNumberOfBuckets, const uint16_t bucketGrowFillPercent,
const uint16_t bucketShrinkFillPercent);
//! Get number of buckets.
size_t GetSize() const;
//! Get bucket traits.
BucketTraits GetBucketTraits();
//! Get the bucket grow fill percent.
uint16_t GetBucketGrowFillPercent() const;
//! Set the bucket grow fill percent.
void SetBucketGrowFillPercent(const uint16_t bucketGrowFillPercent);
//! Set bucket fill thresholds.
void SetBucketFillThresholds();
//! Set a new bucket count, rehashes if different.
void SetBucketCount(SET &Set, const size_t newBucketCount);
/**
* @brief Check rehash on insert.
*
* @param set
*
* @return true if the set was rehashed.
*/
bool CheckRehashOnInsert(SET &set);
/**
* @brief Check rehash on erase.
*
* @param set
*/
void CheckRehashOnErase(SET &set);
private:
typedef std::vector<typename SET::bucket_type> BucketTypeList;
const size_t m_initialNumberOfBuckets;
double m_bucketGrowFillPercent;
size_t m_bucketGrowFillThreshold;
const double m_bucketShrinkFillPercent;
size_t m_bucketShrinkFillThreshold;
BucketTypeList m_buckets;
};
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename SET>
BucketManager<SET>::BucketManager(const size_t initialNumberOfBuckets, const uint16_t bucketGrowFillPercent,
const uint16_t bucketShrinkFillPercent) :
m_initialNumberOfBuckets(initialNumberOfBuckets),
m_bucketGrowFillPercent(bucketGrowFillPercent / 100.0),
m_bucketShrinkFillPercent(bucketShrinkFillPercent / 100.0),
m_buckets(initialNumberOfBuckets)
{
SetBucketFillThresholds();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename SET>
inline size_t BucketManager<SET>::GetSize() const
{
return m_buckets.size();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename SET>
inline typename BucketManager<SET>::BucketTraits BucketManager<SET>::GetBucketTraits()
{
return BucketTraits(&m_buckets[0], m_buckets.size());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename SET>
inline uint16_t BucketManager<SET>::GetBucketGrowFillPercent() const
{
return static_cast<uint16_t>(m_bucketGrowFillPercent * 100);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename SET>
inline void BucketManager<SET>::SetBucketGrowFillPercent(const uint16_t bucketGrowFillPercent)
{
m_bucketGrowFillPercent = bucketGrowFillPercent / 100.0;
SetBucketFillThresholds();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename SET>
inline void BucketManager<SET>::SetBucketFillThresholds()
{
m_bucketGrowFillThreshold = static_cast<size_t>(m_bucketGrowFillPercent * m_buckets.size());
m_bucketShrinkFillThreshold = static_cast<size_t>(m_bucketShrinkFillPercent * m_buckets.size());
if (m_bucketShrinkFillThreshold < m_initialNumberOfBuckets)
m_bucketShrinkFillThreshold = m_initialNumberOfBuckets;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename SET>
inline void BucketManager<SET>::SetBucketCount(SET &set, const size_t newBucketCount)
{
if (m_buckets.size() == newBucketCount)
return;
BucketTypeList newBuckets(newBucketCount);
set.rehash(BucketTraits(&newBuckets[0], newBuckets.size()));
m_buckets.swap(newBuckets);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename SET>
inline bool BucketManager<SET>::CheckRehashOnInsert(SET &set)
{
const size_t setSize = set.size();
if (ACTIV_UNLIKELY(setSize >= m_bucketGrowFillThreshold))
{
size_t newBucketSize = m_buckets.size();
while (setSize >= static_cast<size_t>(newBucketSize * m_bucketGrowFillPercent))
newBucketSize *= 2;
SetBucketCount(set, newBucketSize);
SetBucketFillThresholds();
return true;
}
return false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename SET>
inline void BucketManager<SET>::CheckRehashOnErase(SET &set)
{
const size_t setSize = set.size();
if (ACTIV_UNLIKELY(setSize < m_bucketShrinkFillThreshold) &&
ACTIV_UNLIKELY(m_bucketShrinkFillThreshold > m_initialNumberOfBuckets))
{
size_t newBucketSize = m_buckets.size();
size_t adjustedBucketSize = static_cast<size_t>(newBucketSize * m_bucketShrinkFillPercent);
while ((setSize < adjustedBucketSize) && (adjustedBucketSize > m_initialNumberOfBuckets))
{
newBucketSize /= 2;
adjustedBucketSize = static_cast<size_t>(newBucketSize * m_bucketShrinkFillPercent);
}
set.rehash(BucketTraits(&m_buckets[0], newBucketSize));
m_buckets.resize(newBucketSize);
SetBucketFillThresholds();
}
}
} // namespace Detail
} // namespace IntrusiveSetHelper
} // namespace Activ
#endif // (!defined ACTIV_BASE_INTRUSIVE_SET_HELPER_DETAIL_H)
@@ -1,218 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Detail/ThreadSpecificDataDetail.h
*
* @brief Implementation details thread for specific data storage class.
*/
#if (!defined ACTIV_BASE_DETAIL_THREAD_SPECIFIC_DATA_DETAIL_H)
#define ACTIV_BASE_DETAIL_THREAD_SPECIFIC_DATA_DETAIL_H
#include "ActivMiddleware/ActivBase/OsException.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#if (defined ACTIV_PLATFORM_POSIX)
#include <pthread.h>
#endif
//! Activ namespace.
namespace Activ
{
#if (defined ACTIV_PLATFORM_WINDOWS)
typedef void (*TsdDestructorFn)(void *);
ACTIV_BASE_API void ThreadSpecificDataCleanupAddKey(const DWORD key, TsdDestructorFn pTsdDestructorFn);
ACTIV_BASE_API void ThreadSpecificDataCleanupRemoveKey(const DWORD key);
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename TYPE, typename DERIVED>
inline ThreadSpecificDataBase<TYPE, DERIVED>::ThreadSpecificDataBase() :
m_index(::TlsAlloc()),
m_pSharedInfo(CxxYZ::make_shared<SharedInfo>(CxxYZ::ref(*this)))
{
if (TLS_OUT_OF_INDEXES == m_index)
ACTIV_THROW(OsException, ::GetLastError());
ThreadSpecificDataCleanupAddKey(m_index, &StaticDestructor);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename TYPE, typename DERIVED>
inline ThreadSpecificDataBase<TYPE, DERIVED>::~ThreadSpecificDataBase()
{
void * const pData = ::TlsGetValue(m_index);
if (0 != pData)
StaticDestructor(pData);
{
// Lock the shared portion. We don't want to destroy ourself whilst another thread is cleaning up; if we've gone by the
// time they start to cleanup then they won't be able to do much as we set the shared hook back here to 0.
CxxYZ::lock_guard<CxxYZ::mutex> scopedMutexLocker(m_pSharedInfo->m_mutex);
m_pSharedInfo->m_pThreadSpecificData = 0;
}
ThreadSpecificDataCleanupRemoveKey(m_index);
(void) ::TlsFree(m_index);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename TYPE, typename DERIVED>
inline TYPE *ThreadSpecificDataBase<TYPE, DERIVED>::Get() const
{
PerThreadInfo * const pPerThreadInfo = reinterpret_cast<PerThreadInfo *>(::TlsGetValue(m_index));
if (ACTIV_UNLIKELY(0 == pPerThreadInfo))
return 0;
return pPerThreadInfo->m_pValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename TYPE, typename DERIVED>
inline void ThreadSpecificDataBase<TYPE, DERIVED>::Set(TYPE * const pValue)
{
PerThreadInfo *pPerThreadInfo = reinterpret_cast<PerThreadInfo *>(::TlsGetValue(m_index));
if (0 == pPerThreadInfo)
{
pPerThreadInfo = new PerThreadInfo(m_pSharedInfo);
(void) ::TlsSetValue(m_index, reinterpret_cast<void *>(pPerThreadInfo));
}
pPerThreadInfo->m_pValue = pValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
#elif (defined ACTIV_PLATFORM_POSIX)
template <typename TYPE, typename DERIVED>
inline ThreadSpecificDataBase<TYPE, DERIVED>::ThreadSpecificDataBase() :
m_pSharedInfo(new SharedInfo(*this))
{
int res = ::pthread_key_create(&m_key, &StaticDestructor);
if (0 != res)
ACTIV_THROW(OsException, res);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename TYPE, typename DERIVED>
inline ThreadSpecificDataBase<TYPE, DERIVED>::~ThreadSpecificDataBase()
{
void * const pData = ::pthread_getspecific(m_key);
if (0 != pData)
StaticDestructor(pData);
{
// Lock the shared portion. We don't want to destroy ourself whilst another thread is cleaning up; if we've gone by the
// time they start to cleanup then they won't be able to do much as we set the shared hook back here to 0.
CxxYZ::lock_guard<CxxYZ::mutex> scopedMutexLocker(m_pSharedInfo->m_mutex);
m_pSharedInfo->m_pThreadSpecificData = 0;
}
(void) ::pthread_key_delete(m_key);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename TYPE, typename DERIVED>
inline TYPE *ThreadSpecificDataBase<TYPE, DERIVED>::Get() const
{
PerThreadInfo * const pPerThreadInfo = reinterpret_cast<PerThreadInfo *>(::pthread_getspecific(m_key));
if (ACTIV_UNLIKELY(0 == pPerThreadInfo))
return 0;
return pPerThreadInfo->m_pValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename TYPE, typename DERIVED>
inline void ThreadSpecificDataBase<TYPE, DERIVED>::Set(TYPE * const pValue)
{
PerThreadInfo *pPerThreadInfo = reinterpret_cast<PerThreadInfo *>(::pthread_getspecific(m_key));
if (0 == pPerThreadInfo)
{
pPerThreadInfo = new PerThreadInfo(m_pSharedInfo);
(void) ::pthread_setspecific(m_key, reinterpret_cast<void *>(pPerThreadInfo));
}
pPerThreadInfo->m_pValue = pValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
#else
#error Configure for this platform
#endif
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename TYPE, typename DERIVED>
inline void ThreadSpecificDataBase<TYPE, DERIVED>::InvokeOnThreadExit(TYPE * const pValue)
{
DERIVED &derived = static_cast<DERIVED &>(*this);
derived.OnThreadExit(pValue);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename TYPE, typename DERIVED>
void ThreadSpecificDataBase<TYPE, DERIVED>::StaticDestructor(void *pData)
{
if (0 != pData)
{
PerThreadInfo * const pPerThreadInfo = reinterpret_cast<PerThreadInfo *>(pData);
delete pPerThreadInfo;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename TYPE, typename DERIVED>
ThreadSpecificDataBase<TYPE, DERIVED>::SharedInfo::SharedInfo(ThreadSpecificDataType &threadSpecificData) :
m_pThreadSpecificData(&threadSpecificData)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename TYPE, typename DERIVED>
ThreadSpecificDataBase<TYPE, DERIVED>::PerThreadInfo::PerThreadInfo(SharedInfoPointer &pSharedInfo) :
m_pSharedInfo(pSharedInfo),
m_pValue(0)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename TYPE, typename DERIVED>
ThreadSpecificDataBase<TYPE, DERIVED>::PerThreadInfo::~PerThreadInfo()
{
CxxYZ::lock_guard<CxxYZ::mutex> scopedMutexLocker(m_pSharedInfo->m_mutex);
// If pThreadSpecificData == 0, the ThreadSpecificDataBase object has been destroyed before this thread exited.
// In this case, there is very little we can do; there will probably be a small memory leak.
ThreadSpecificDataType *pThreadSpecificData = m_pSharedInfo->m_pThreadSpecificData;
if ((0 != pThreadSpecificData) && (0 != m_pValue))
pThreadSpecificData->InvokeOnThreadExit(m_pValue);
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_DETAIL_THREAD_SPECIFIC_DATA_DETAIL_H)
@@ -1,54 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/DirectoryRemover.h
*
* @brief Directory remover class.
*/
#if (!defined ACTIV_BASE_DIRECTORY_REMOVER_H)
#define ACTIV_BASE_DIRECTORY_REMOVER_H
#include "ActivMiddleware/ActivBase/DirectoryWalker.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Directory remover class.
*/
class DirectoryRemover : private DirectoryWalker
{
public:
/**
* @brief Default constructor.
*/
ACTIV_BASE_API DirectoryRemover();
/**
* @brief Destructor.
*/
ACTIV_BASE_API virtual ~DirectoryRemover() ACTIV_OVERRIDE;
/**
* @brief Remove files from a directory tree.
*
* @param path the path to the directory to remove.
* @param shouldRecurseDirectory indicates whether the directory should be recursed.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_NOT_FOUND
*/
ACTIV_BASE_API StatusCode Remove(const String &path, const bool shouldRecurseDirectory);
protected:
ACTIV_BASE_API virtual bool OnDirectory(const String &path, const String &name) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual bool OnFile(const String &path, const String &name) ACTIV_OVERRIDE;
private:
bool m_shouldRecurseDirectory; ///< indicates whether the directory should be recursed.
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_DIRECTORY_REMOVER_H)
@@ -1,88 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/DirectoryWalker.h
*
* @brief Directory walker class.
*/
#if (!defined ACTIV_BASE_DIRECTORY_WALKER_H)
#define ACTIV_BASE_DIRECTORY_WALKER_H
#include "ActivMiddleware/ActivBase/External.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Directory walker class.
*
* Do not assume any ordering of OnDirectory() or OnFile() callbacks.
*/
class DirectoryWalker
{
public:
/**
* @brief Constructor.
*/
ACTIV_BASE_API DirectoryWalker();
/**
* @brief Destructor.
*/
ACTIV_BASE_API virtual ~DirectoryWalker();
/**
* @brief Walk a directory.
*
* To recursively walk a directory, override OnDirectory() and call Walk() again, passing
* File::MakePath(path, name) as the path parameter. This is assuming your derived DirectoryWalker class is
* re-entrant in such a manner (the DirectoryWalker class itself is).
*
* @param path the path to the directory to walk.
* @param wildcardPattern only return files/directories matching this wildcard pattern (leave blank to return everything)
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_INTERRUPTED
*/
ACTIV_BASE_API StatusCode Walk(const String &path, const String &wildcardPattern = String());
protected:
/**
* @brief Callback function for when directories are located in the directory walk.
*
* @param path the path to the directory, not including the directory's name. I.e. the value of @a path passed to Walk().
* @param name the name of the directory.
*
* @return true to continue, false to stop (interrupt) the walk.
*/
ACTIV_BASE_API virtual bool OnDirectory(const String &path, const String &name);
/**
* @brief Callback function for when files are located in a directory walk.
*
* @param path the path to the directory, not including the file's name. I.e. the value of @a path passed to Walk().
* @param name the name of the file.
*
* @return true to continue, false to stop (interrupt) the walk.
*/
ACTIV_BASE_API virtual bool OnFile(const String &path, const String &name);
#if (defined ACTIV_PLATFORM_POSIX)
/**
* @brief Callback function for when symlinks are located in a directory walk.
*
* @param path the path to the directory, not including the symlink's name. I.e. the value of @a path passed to Walk().
* @param name the name of the symlink.
* @param linkTarget the target of the link (absolute path).
*
* @return true to continue, false to stop (interrupt) the walk.
*/
ACTIV_BASE_API virtual bool OnLink(const String &path, const String &name, const String &linkTarget);
#endif
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_DIRECTORY_WALKER_H)
@@ -1,158 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Environment.h
*
* @brief Environment variable functions.
*/
#if (!defined ACTIV_BASE_ENVIRONMENT_H)
#define ACTIV_BASE_ENVIRONMENT_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/Misc/Optional.h"
#include "ActivMiddleware/CxxYZ/map.h"
//! Activ namespace.
namespace Activ
{
//! Environment namespace.
namespace Environment
{
typedef CxxYZ::map<String, String> EnvironmentMap;
/**
* @brief Get an environment variable as a string.
*
* @param name the name of the variable.
*
* @return A Boost::optional<String>; Boost::none if the variable is not set, otherwise the contents of the variable.
*/
ACTIV_BASE_API Boost::optional<String> Get(const String &name);
/**
* @brief Get an environment variable as an arbitrary type.
*
* @tparam T the type to convert the variable to.
*
* @param name the name of the variable.
*
* @return A Boost::optional<T>; Boost::none if the variable is not set or cannot be converted,
* otherwise the contents of the variable.
*/
template<typename T>
Boost::optional<T> Get(const String &name);
/**
* @brief Get an environment variable as an arbitrary type.
*
* @tparam T the type to convert the variable to.
*
* @param name the name of the variable.
* @param defaultValue the value to return if the variable is not found or is invalid.
*
* @return The environment value or @a defaultValue if not found or invalid.
*/
template<typename T>
T Get(const String &name, const T &defaultValue);
#if (!defined ACTIV_PLATFORM_WASM)
/**
* @brief Get all environment variables.
*
* @return A map of keys/values for all environment variables.
*/
ACTIV_BASE_API EnvironmentMap GetAll();
#endif
/**
* @brief Set an environment variable from a String.
*
* @param name the name of the variable.
* @param value the value to set.
* @param shouldOverwrite whether to overwrite an existing value.
*
* @return true if variable is set. Note true is returned if !shouldOverwrite and the variable already exists.
*/
ACTIV_BASE_API bool Set(const String &name, const String &value, const bool shouldOverwrite);
/**
* @brief Set an environment variable.
*
* @tparam T type of the value; must be Boost::lexical_cast<>able to String.
*
* @param name the name of the variable.
* @param value the value to set.
* @param shouldOverwrite whether to overwrite an existing value.
*
* @return true if variable is set. Note true is returned if !shouldOverwrite and the variable already exists.
*/
template<typename T>
bool Set(const String &name, const T &value, const bool shouldOverwrite);
//! Remove an environment variable.
ACTIV_BASE_API bool Remove(const String &name);
/**
* @brief Replace any environment variables in a string with the value of the environment variable.
*
* @param source source string.
* @param target reference to a string to receive the expanded string.
*
* @return true if conversion succeeded.
*/
ACTIV_BASE_API bool Expand(const String &source, String &target);
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline Boost::optional<T> Get(const String &name)
{
try
{
Boost::optional<String> value(Get(name));
if (!value)
return Boost::none;
return Boost::lexical_cast<T>(*value);
}
catch (const Boost::bad_lexical_cast &)
{
return Boost::none;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline T Get(const String &name, const T &defaultValue)
{
Boost::optional<T> envVar = Get<T>(name);
if (envVar)
return *envVar;
return defaultValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline bool Set(const String &name, const T &value, const bool shouldOverwrite)
{
try
{
return Set(name, Boost::lexical_cast<String>(value), shouldOverwrite);
}
catch (const Boost::bad_lexical_cast &)
{
return false;
}
}
} // namespace Environment
} // namespace Activ
#endif // (!defined ACTIV_BASE_ENVIRONMENT_H)
@@ -1,124 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/EventManagee.h
*
* @brief Header file for class managed by EventManager.
*/
#if (!defined ACTIV_BASE_EVENT_MANAGEE_H)
#define ACTIV_BASE_EVENT_MANAGEE_H
#include "ActivMiddleware/ActivBase/External.h"
//! Activ namespace.
namespace Activ
{
class EpollManager;
class EventManager;
class IMutex;
class PollManager;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief EventManager managed class.
*/
class EventManagee : private Boost::noncopyable
{
public:
typedef uint32_t Events; ///< Event type.
static const Events EVENT_NONE = 0x00000000;
static const Events EVENT_READ = 0x00000001; ///< Data to read.
static const Events EVENT_WRITE = 0x00000002; ///< OK to write.
static const Events EVENT_CLOSE = 0x00000004; ///< Close has been requested.
/**
* @brief Constructor.
*
* @param eventManager reference to EventManager to attach to.
* @param pMutex (optional) mutex.
*/
ACTIV_BASE_API EventManagee(EventManager &eventManager, IMutex * const pMutex);
//! Destructor.
ACTIV_BASE_API virtual ~EventManagee();
/**
* @brief Add fd to event manager.
*
* NB can be called from any thread, but the mutex *must* already be locked.
*
* @param events set of events to get notification on initially.
* @param socket (Windows only) optional socket associated with m_handle.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_ALREADY_EXISTS AddFd() has already been called; nothing has been done.
* @retval ...
*/
#if (defined ACTIV_PLATFORM_WINDOWS)
ACTIV_BASE_API StatusCode AddFd(const Events events, const SOCKET socket = INVALID_SOCKET);
#else
ACTIV_BASE_API StatusCode AddFd(const Events events);
#endif
/**
* @brief Remove fd from event manager.
*
* NB this *must* be called from the context of the event manager's thread, and the mutex *must*
* already be locked.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_CREATED RemoveFd() has already been called or AddFd() was not called; nothing has been done.
* @retval ...
*/
ACTIV_BASE_API StatusCode RemoveFd();
/**
* @brief Add events to wait for.
*
* NB can be called from any thread, but the mutex *must* already be locked.
*
* @param addEvents events to add to the wait set.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode AddEvents(const Events addEvents);
//! Get the EventManager.
EventManager &GetEventManager();
protected:
/**
* @brief Event processing.
*
* @param events the set of events that have occurred.
*/
virtual void OnEvents(const Events events) = 0;
EventManager & m_eventManager; ///< Hook back to the event manager.
IMutex * const m_pMutex;
HANDLE m_handle; ///< File descriptor to watch.
Events m_events; ///< Current set of events.
bool * m_pIsDeletedFlag;
friend class EventManager;
friend class EpollManager;
friend class PollManager;
private:
bool m_isManaged; ///< Whether the fd has been added to the EventManager.
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline EventManager &EventManagee::GetEventManager()
{
return m_eventManager;
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_EVENT_MANAGEE_H)
@@ -1,20 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/EventManager.h
*
* @brief Header file for event manager.
*/
#if (!defined ACTIV_BASE_EVENT_MANAGER_H)
#define ACTIV_BASE_EVENT_MANAGER_H
#include "ActivMiddleware/ActivBase/External.h"
#if (defined ACTIV_PLATFORM_WINDOWS)
#include "ActivMiddleware/ActivBase/Windows/EventManager.h"
#elif (defined ACTIV_PLATFORM_POSIX)
#include "ActivMiddleware/ActivBase/Posix/EventManager.h"
#else
#error Write me
#endif
#endif // (!defined ACTIV_BASE_EVENT_MANAGER_H)
@@ -1,294 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Exception.h
*
* @brief Header file for the base exception class.
*/
#if (!defined ACTIV_BASE_EXCEPTION_H)
#define ACTIV_BASE_EXCEPTION_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/ActivBase.h"
#include ACTIV_BOOST_INCLUDE(exception/all.hpp)
#include <iostream>
//! Construct an exception.
#define ACTIV_EXCEPTION(t, e) t(__FILE__, __FUNCTION__, __LINE__, e)
/**
* @brief Raise an exception.
*
* Throw an exception of type t with error code e.
* The file, function and line number throwing the exception are automatically generated.
*/
#define ACTIV_THROW(t, e) throw ACTIV_EXCEPTION(t, e)
//! Rethrow an exception.
#define ACTIV_RETHROW(e) \
do \
{ \
e.AddException(new (std::nothrow) ACTIV_EXCEPTION(Exception, 0)); \
throw; \
} \
while (false)
//! Throw exception if result of expression tests true using operator against statusCode
#define ACTIV_THROW_ERROR_IF(statusCode, operator, expression, exception) \
do \
{ \
if (statusCode operator expression) \
throw exception; \
} \
while (false)
//! Construct an exception with a message.
#define ACTIV_EXCEPTION_WITH_MESSAGE(t, e, m) t(__FILE__, __FUNCTION__, __LINE__, e, m)
/**
* @brief Raise an exception with a message.
*
* Throw an exception of type t with error code e and message m.
* The file, function and line number throwing the exception are automatically generated.
*/
#define ACTIV_THROW_WITH_MESSAGE(t, e, m) throw ACTIV_EXCEPTION_WITH_MESSAGE(t, e, m)
// ---------------------------------------------------------------------------------------------------------------------------------
//! Activ namespace.
namespace Activ
{
//! Base Activ exception class.
class Exception
{
public:
/**
* @brief Constructor.
*
* @param file the file which raised the exception.
* @param function the function which raised the exception.
* @param line the line number which raised the exception.
* @param errorCode the exception specific error code.
* @param message the exception message.
*/
ACTIV_BASE_API Exception(const char *file, const char *function, const uint_fast32_t line, const uint_fast32_t errorCode = 0,
const String &message = "");
/**
* @brief Copy constructor.
*
* @param rhs
*/
ACTIV_BASE_API Exception(const Exception &rhs);
//! Destructor.
virtual ~Exception();
/**
* @brief Convert the exception error code to a string.
*
* Classes derived from Exception are required to implement ToString() to convert
* their error codes to a readable string.
*
* @return the error code as a string.
*/
ACTIV_BASE_API virtual String ToString() const;
/**
* @brief Stream output method.
*
* ToStream() allows writing of the exception to an ostream object. The file, function, line,
* error code and error string will be written to the ostream.
*
* @param os the ostream to write the exception to.
*/
ACTIV_BASE_API virtual void ToStream(std::ostream &os) const;
/**
* @brief Attach another exception to the chain.
*
* @param pException the exception to add to the chain.
*/
ACTIV_BASE_API void AddException(Exception *pException) const;
/**
* @brief Set the message.
*
* @param message the new message.
*/
void SetMessage(const String &message);
/**
* @brief Get the message.
*
* @return The message.
*/
const String &GetMessage() const;
const char * const m_file; ///< The file that raised the exception.
const char * const m_function; ///< The function that raised the exception.
const uint_fast32_t m_line; ///< The line number that raised the exception.
const uint_fast32_t m_errorCode; ///< The exception specific error code.
mutable String m_message; ///< The optional message.
private:
mutable const Exception * m_pNextException; ///< Can only be a heap allocated exception.
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline Exception::~Exception()
{
// For some reason, Emscripten refuses to resolve this if in the .cpp at "exe" link time.
delete m_pNextException;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Exception::SetMessage(const String &message)
{
m_message = message;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &Exception::GetMessage() const
{
return m_message;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Helper function to retrieve the file name of @a filePath.
*
* @param filePath
*
* @return An empty string or the file name.
*/
ACTIV_BASE_API String GetExceptionFileInfo(const String &filePath);
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Global operator<< to dump an exception to an ostream.
*
* operator<< allows writing of the exception to an ostream object. The file, function, line,
* error code and error string will be written to the ostream.
*
* @param os the ostream to write the exception to.
* @param e the exception to write.
*
* @return the ostream @a os.
*/
ACTIV_BASE_API std::ostream &operator<<(std::ostream &os, const Activ::Exception &e);
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Helper function to retrieve location of throw from an exception.
*
* @param e an exception.
*
* @return An empty string if the location isn't available, otherwise a string of the form "in <file> at line <line>".
*/
template<typename T>
String GetExceptionThrowLocationInfo(const T &e)
{
const char * const *pFile = Boost::get_error_info<Boost::throw_file>(e);
const int * const pLine = Boost::get_error_info<Boost::throw_line>(e);
if (pFile && pLine)
return "thrown from line " + TypeToString(*pLine) + " of " + GetExceptionFileInfo(*pFile);
else
return "";
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Template function to wrap a function call that can throw in a try-catch; log the exception and return a given value.
*
* @param fn a function object to call (e.g. via CxxYZ::bind).
* @param exceptionReturn value to return if an exception is caught.
* @param pFunctionName name of the function for display purposes if an exception is caught.
*
* @return The result of the wrapped function, or @a exceptionReturn in an exception was caught.
*/
#if (ACTIV_CPLUSPLUS >= ACTIV_CPLUSPLUS_17)
template <typename T> typename std::invoke_result_t<T>
WrapThrowingFunction(const T &fn, const typename std::invoke_result_t<T> exceptionReturn, const char * const pFunctionName)
#else
template <typename T> typename T::result_type
WrapThrowingFunction(const T &fn, const typename T::result_type exceptionReturn, const char * const pFunctionName)
#endif
{
try
{
return fn();
}
catch (const Exception &e)
{
std::ostringstream ss;
ss << pFunctionName << " caught exception " << e;
LogMessage(LOG_TYPE_WARNING, ss.str());
}
catch (const std::exception &e)
{
LogMessage(LOG_TYPE_WARNING, (String(pFunctionName) + " caught exception " + e.what()));
}
ACTIV_CATCH_ALL()
{
LogMessage(LOG_TYPE_WARNING, (String(pFunctionName) + " caught unknown exception"));
}
return exceptionReturn;
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Template function to wrap a void function call that can throw in a try-catch and log the exception.
*
* @param fn a function object to call (e.g. via CxxYZ::bind).
* @param pFunctionName name of the function for display purposes if an exception is caught.
*
* @return true if no exception was thrown, else false.
*/
template<typename T>
bool WrapThrowingFunction(const T &fn, const char * const pFunctionName)
{
try
{
fn();
return true;
}
catch (const Exception &e)
{
std::ostringstream ss;
ss << pFunctionName << " caught exception " << e;
LogMessage(LOG_TYPE_WARNING, ss.str());
}
catch (const std::exception &e)
{
LogMessage(LOG_TYPE_WARNING, (String(pFunctionName) + " caught exception " + e.what()));
}
ACTIV_CATCH_ALL()
{
LogMessage(LOG_TYPE_WARNING, (String(pFunctionName) + " caught unknown exception"));
}
return false;
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_EXCEPTION_H)
@@ -1,20 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/External.h
*
* @brief Import/export rules for ActivBase.
*/
#if (!defined ACTIV_BASE_EXTERNAL_H)
#define ACTIV_BASE_EXTERNAL_H
#if (!defined ACTIV_BASE_API)
# if (!defined ACTIV_STATIC)
# define ACTIV_BASE_API ACTIV_IMPORT_DLL
# else
# define ACTIV_BASE_API ACTIV_IMPORT_LIB
# endif // (!defined ACTIV_STATIC)
#endif // (!defined ACTIV_BASE_API)
#include "ActivMiddleware/ActivMiddleware.h"
#endif // (!defined ACTIV_BASE_EXTERNAL_H)
@@ -1,128 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Fiber.h
*
* @brief Header file for the fiber class.
*/
#if (!defined ACTIV_BASE_FIBER_H)
#define ACTIV_BASE_FIBER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#if (defined ACTIV_FIBER_USE_THREAD)
#include "ActivMiddleware/CxxYZ/condition_variable.h"
#include "ActivMiddleware/CxxYZ/thread.h"
#include "ActivMiddleware/CxxYZ/mutex.h"
#elif (defined ACTIV_PLATFORM_WINDOWS)
#define ACTIV_FIBER_USE_WINDOWS_FIBER
#elif (defined ACTIV_POSIX_HAS_CONTEXT_API)
#define ACTIV_FIBER_USE_UCONTEXT
#include <ucontext.h>
#include ACTIV_BOOST_INCLUDE(scoped_array.hpp)
#else
#error Not supported on this platform
#endif
//! Activ namespace.
namespace Activ
{
/**
* @brief Fiber class.
*/
class Fiber : private Boost::noncopyable
{
public:
typedef CxxYZ::function<void ()> FunctionType;
/**
* @brief Constructor.
*
* @param function function to start on first call to @a Continue(). Copy is taken. If this function exits, the fiber
* implicitly Cede()s back to the calling fiber.
* @param stackSize size of stack to commit. 0 will use the current stack size setting for the process, unless the
* environment variable ACTIV_FIBER_STACK_SIZE is set to a numeric value.
*
* @throw Exception.
*/
ACTIV_BASE_API Fiber(const FunctionType &function, const size_t stackSize = 0);
//! Destructor.
ACTIV_BASE_API ~Fiber();
//! Start or continue to run this fiber.
ACTIV_BASE_API void Continue();
/**
* @brief Yield execution of this fiber and return to the calling fiber.
*
* This call just returns if this object has not been Continue() at all.
* This would be called Yield() except for nonsense in WinBase.h: "#define Yield()". If only inline functions were a thing!
*/
ACTIV_BASE_API void Cede();
//! Is the fiber currently running?
bool IsRunning() const;
private:
enum State
{
STATE_NOT_RUNNING, ///< Fiber isn't running.
STATE_RUNNING, ///< Fiber has been Continue()d.
STATE_EXITED ///< Fiber function has exited.
};
State m_state; ///< Current state of fiber.
const FunctionType m_function;
#if (defined ACTIV_FIBER_USE_WINDOWS_FIBER)
typedef void *FiberId;
static void CALLBACK StaticFiberProc(void *pData);
#elif (defined ACTIV_FIBER_USE_UCONTEXT)
typedef ucontext_t FiberId;
static void StaticFiberProc(const uint32_t highFiberAddress, const uint32_t lowFiberAddress);
const size_t m_stackSize;
char * const m_pStack; ///< Stack for fiber.
#elif (defined ACTIV_FIBER_USE_THREAD)
void ThreadFunction();
void WaitForState(const State state, CxxYZ::unique_lock<CxxYZ::mutex> &uniqueLock);
CxxYZ::thread m_thread;
CxxYZ::mutex m_mutex;
CxxYZ::condition_variable m_conditionVariable;
#else
#error Write me
#endif
#if (!defined ACTIV_FIBER_USE_THREAD)
FiberId m_id; ///< This fiber id.
FiberId m_returnId; ///< Fiber to return to.
#endif
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Fiber::IsRunning() const
{
return (STATE_RUNNING == m_state);
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIBER_H)
@@ -1,227 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/ActivFieldTypes.h
*
* @brief Global functions from ActivFieldTypes.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_ACTIV_FIELD_TYPES_H)
#define ACTIV_BASE_FIELD_TYPES_ACTIV_FIELD_TYPES_H
#include "ActivMiddleware/ActivBase/External.h"
#include ACTIV_BOOST_INCLUDE(mpl/contains.hpp)
#include ACTIV_BOOST_INCLUDE(mpl/list.hpp)
#include ACTIV_BOOST_INCLUDE(preprocessor/punctuation/comma_if.hpp)
#include ACTIV_BOOST_INCLUDE(preprocessor/seq/for_each.hpp)
#include ACTIV_BOOST_INCLUDE(preprocessor/seq/for_each_i.hpp)
#include ACTIV_BOOST_INCLUDE(preprocessor/tuple/elem.hpp)
/**
* @brief The list of field types and their string representation.
*
* TYPE enumeration value of the field type.
* NAME The concrete class name of the field type.
* SIZE1 size of inlined field length in a record message.
* SIZE2 size of inlined field length in an update message.
*
* TYPE NAME SIZE1 SIZE2
*/
#define ACTIV_FIELD_TYPE_TUPLE_LIST \
((DATE, Date, 0, 0)) \
((TIME, Time, 0, 0)) \
((DATE_TIME, DateTime, 0, 0)) \
((SINT, SInt, 0, 1)) \
((UINT, UInt, 0, 1)) \
((RATIONAL, Rational, 0, 0)) \
((TRATIONAL, TRational, 0, 0)) \
((TEXT_STRING, TextString, 1, 1)) \
((TEXT_ARRAY, TextArray, 0, 1)) \
((BINARY_STRING, BinaryString, 1, 1)) \
((BINARY_ARRAY, BinaryArray, 0, 1)) \
((BLOB, Blob, 4, 4)) \
((CRC_BLOB, CrcBlob, 4, 4)) \
((BOOLEAN, Boolean, 0, 0)) \
((FIELD_MAP, FieldMap, 4, 4)) \
((FIELD_TYPE_LIST, FieldTypeList, 4, 4)) \
((DOUBLE, Double, 0, 0))
// Element accessors.
#define ACTIV_FIELD_TYPE_TUPLE_GET_TYPE(tuple) ACTIV_JOIN(FIELD_TYPE_, ACTIV_BOOST_PP_TUPLE_ELEM(4, 0, tuple))
#define ACTIV_FIELD_TYPE_TUPLE_GET_NAME(tuple) ACTIV_BOOST_PP_TUPLE_ELEM(4, 1, tuple)
#define ACTIV_FIELD_TYPE_TUPLE_GET_RECORD_SIZE(tuple) ACTIV_BOOST_PP_TUPLE_ELEM(4, 2, tuple)
#define ACTIV_FIELD_TYPE_TUPLE_GET_UPDATE_SIZE(tuple) ACTIV_BOOST_PP_TUPLE_ELEM(4, 3, tuple)
//! Activ namespace.
namespace Activ
{
typedef uint8_t FieldType; ///< The field type type definition.
const FieldType FIELD_TYPE_UNKNOWN = ~0;
// ---------------------------------------------------------------------------------------------------------------------------------
#define ACTIV_DECLARE_FIELD_TYPE_ENUMERATION(r, data, tuple) ACTIV_FIELD_TYPE_TUPLE_GET_TYPE(tuple),
//! Enumeration of all field types.
enum FieldTypeEnum
{
ACTIV_BOOST_PP_SEQ_FOR_EACH(ACTIV_DECLARE_FIELD_TYPE_ENUMERATION, , ACTIV_FIELD_TYPE_TUPLE_LIST)
NUMBER_OF_FIELD_TYPES
};
#undef ACTIV_DECLARE_FIELD_TYPE_ENUMERATION
// ---------------------------------------------------------------------------------------------------------------------------------
#define ACTIV_DECLARE_FIELD_TYPE_FORWARD_REFERENCE(r, data, tuple) class ACTIV_FIELD_TYPE_TUPLE_GET_NAME(tuple);
// Forward reference all ACTIV field type types.
class IFieldType;
ACTIV_BOOST_PP_SEQ_FOR_EACH(ACTIV_DECLARE_FIELD_TYPE_FORWARD_REFERENCE, , ACTIV_FIELD_TYPE_TUPLE_LIST)
#undef ACTIV_DECLARE_FIELD_TYPE_FORWARD_REFERENCE
// ---------------------------------------------------------------------------------------------------------------------------------
#define ACTIV_DECLARE_FIELD_TYPE_TYPE_LIST(r, data, i, tuple) ACTIV_BOOST_PP_COMMA_IF(i) ACTIV_FIELD_TYPE_TUPLE_GET_NAME(tuple)
//! An MPL sequence of all ACTIV field types.
typedef Boost::mpl::list<ACTIV_BOOST_PP_SEQ_FOR_EACH_I(ACTIV_DECLARE_FIELD_TYPE_TYPE_LIST, , ACTIV_FIELD_TYPE_TUPLE_LIST)>
FieldTypeTypeList;
#undef ACTIV_DECLARE_FIELD_TYPE_TYPE_LIST
// ---------------------------------------------------------------------------------------------------------------------------------
//! Is a type an ACTIV FieldType?
template<typename T>
class IsFieldType : public Boost::mpl::contains<FieldTypeTypeList, T>
{
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private Template to map from FIELD_TYPE_* values to concrete IFieldType class.
template<FieldType>
class FieldTypeToClass
{
// Nothing defined for unknown field type. Specializations are provided for each concrete IFieldType class.
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<IsFieldType<T>, std::ostream &>::type operator<<(std::ostream &os, const T &value)
{
os << value.ToString();
return os;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<IsFieldType<T>, std::istream &>::type operator>>(std::istream &is, T &value)
{
String str;
is >> str;
value.FromString(str);
return is;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Convert compile-time field type to update length size.
*
* @tparam FIELD_TYPE the field type.
*
* @return the length corresponding to the field type.
*/
template <FieldType FIELD_TYPE>
size_t FieldTypeToUpdateLengthSize();
// ---------------------------------------------------------------------------------------------------------------------------------
#define ACTIV_DECLARE_FIELD_TYPE_UPDATE_LENGTH_SIZE_TEMPLATE(r, data, tuple) \
template<> \
inline size_t FieldTypeToUpdateLengthSize<ACTIV_FIELD_TYPE_TUPLE_GET_TYPE(tuple)>() \
{ \
return ACTIV_FIELD_TYPE_TUPLE_GET_UPDATE_SIZE(tuple); \
}
ACTIV_BOOST_PP_SEQ_FOR_EACH(ACTIV_DECLARE_FIELD_TYPE_UPDATE_LENGTH_SIZE_TEMPLATE, , ACTIV_FIELD_TYPE_TUPLE_LIST)
#undef ACTIV_DECLARE_FIELD_TYPE_UPDATE_LENGTH_SIZE_TEMPLATE
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Convert a field type to a string.
*
* @param fieldType the field type.
*
* @return the string corresponding to the field type.
*/
ACTIV_BASE_API String FieldTypeToString(const FieldType fieldType);
/**
* @brief Convert a string to a field type.
*
* @param name the name of the field type
*
* @return the field type the corresponds to the name (or FIELD_TYPE_UNKNOWN).
*/
ACTIV_BASE_API FieldType StringToFieldType(const String &name);
/**
* @brief Convert a field type to the field length size for a record message.
*
* @param fieldType the field type.
*
* @return the length corresponding to the field type.
*/
ACTIV_BASE_API size_t FieldTypeToRecordLengthSize(const FieldType fieldType);
/**
* @brief Convert a field type to the field length size for an update message.
*
* @param fieldType the field type.
*
* @return the length corresponding to the field type.
*/
ACTIV_BASE_API size_t FieldTypeToUpdateLengthSize(const FieldType fieldType);
/**
* @brief Get a usage string for the format supported by IFieldType::FromString().
*
* @param fieldType the field type.
*
* @return String, may be empty.
*/
ACTIV_BASE_API String FieldTypeFromStringFormat(const FieldType fieldType);
// ---------------------------------------------------------------------------------------------------------------------------------
#if (defined ACTIV_PLATFORM_WASM)
// Wasm namespace.
namespace Wasm
{
class FieldTypeAccessor;
} // namespace Wasm;
#endif // (defined ACTIV_PLATFORM_WASM)
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_ACTIV_FIELD_TYPES_H)
@@ -1,28 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/All.h
*
* @brief Helper include to include all FieldType headers.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_ALL_H)
#define ACTIV_BASE_FIELD_TYPES_ALL_H
#include "ActivMiddleware/ActivBase/FieldTypes/BinaryArray.h"
#include "ActivMiddleware/ActivBase/FieldTypes/BinaryString.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Blob.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Boolean.h"
#include "ActivMiddleware/ActivBase/FieldTypes/CrcBlob.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Date.h"
#include "ActivMiddleware/ActivBase/FieldTypes/DateTime.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Double.h"
#include "ActivMiddleware/ActivBase/FieldTypes/FieldTypeList.h"
#include "ActivMiddleware/ActivBase/FieldTypes/FieldMap.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Rational.h"
#include "ActivMiddleware/ActivBase/FieldTypes/SInt.h"
#include "ActivMiddleware/ActivBase/FieldTypes/TextArray.h"
#include "ActivMiddleware/ActivBase/FieldTypes/TextString.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Time.h"
#include "ActivMiddleware/ActivBase/FieldTypes/TRational.h"
#include "ActivMiddleware/ActivBase/FieldTypes/UInt.h"
#endif // (!defined ACTIV_BASE_FIELD_TYPES_ALL_H)
@@ -1,609 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/BinaryArray.h
*
* @brief Header file for the binary array class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_BINARY_ARRAY_H)
#define ACTIV_BASE_FIELD_TYPES_BINARY_ARRAY_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/IFieldType.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/Misc/MemoryHelper.h"
#include "ActivMiddleware/Misc/BitFields.h"
//! Activ namespace.
namespace Activ
{
//! Binary array class.
class BinaryArray ACTIV_FINAL : public IFieldType
{
public:
static const FieldType FIELD_TYPE = FIELD_TYPE_BINARY_ARRAY; ///< The field type.
using IFieldType::FromString;
using IFieldType::Serialize;
using IFieldType::SerializeBody;
using IFieldType::SerializeLengthAndBody;
using IFieldType::Deserialize;
using IFieldType::DeserializeBody;
using IFieldType::DeserializeLengthAndBody;
//! Default constructor.
BinaryArray();
/**
* @brief Constructor.
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @throw StatusCodeException
*/
BinaryArray(const uint8_t * const pData, const size_t size);
/**
* @brief Copy constructor.
*
* @param rhs the value to assign to this object.
*/
BinaryArray(const BinaryArray &rhs);
//! Destructor.
virtual ~BinaryArray() ACTIV_OVERRIDE;
/**
* @brief Equality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*/
bool operator==(const BinaryArray &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*/
bool operator!=(const BinaryArray &rhs) const;
/**
* @brief Assignment operator.
*
* @param rhs the value to assign to this object.
*
* @return a reference to this object.
*/
BinaryArray &operator=(const BinaryArray &rhs);
/**
* @brief Set the data and size.
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_PARAMETER
*/
StatusCode Set(const uint8_t * const pData, const size_t size);
/**
* @brief Get the data and size.
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
*/
StatusCode Get(const uint8_t *&pData, size_t &size) const;
/**
* @brief Get the data.
*
* @return the pointer to the data.
*
* @throw StatusCodeException
*/
const uint8_t *GetData() const;
/**
* @brief Get the size.
*
* @return the size of the data.
*
* @throw StatusCodeException
*/
size_t GetSize() const;
virtual void Reset() ACTIV_OVERRIDE;
virtual void Clear() ACTIV_OVERRIDE;
/**
* @brief Compare.
*
* @param rhs the object to compare with.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API StatusCode Compare(const BinaryArray &rhs, int &result) const;
ACTIV_BASE_API virtual StatusCode Compare(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Convert(const IFieldType * const pIFieldType) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode AppendAsString(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
/**
* @brief Convert the object to a string.
*
* @param isHexFormat indicates whether the data is copied in hex format.
*
* @return the object as a string.
*/
ACTIV_BASE_API virtual String ToString(const bool isHexFormat) const;
/**
* @brief Append the object to a message builder as a string.
*
* @param messageBuilder the message builder.
* @param isHexFormat indicates whether the data is copied in hex format.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API virtual StatusCode AppendAsString(MessageBuilder &messageBuilder, const bool isHexFormat) const;
ACTIV_BASE_API virtual StatusCode FromString(MessageValidator &messageValidator) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String GetFromStringFormat() const ACTIV_OVERRIDE;
/**
* @brief Convert the object to a base64 string.
*
* UTF7 indicates whether the data is copied in UTF7 format.
*
* @return the object as a string.
*/
template<bool UTF7>
ACTIV_BASE_API String ToBase64String() const;
/**
* @brief Convert the object from a base64 string.
*
* UTF7 indicates whether the data is copied in UTF7 format.
*
* @param field the field as a base64 string.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
template<bool UTF7>
ACTIV_BASE_API StatusCode FromBase64String(const String &field);
ACTIV_BASE_API virtual StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) ACTIV_OVERRIDE;
virtual size_t GetSerializedLength() const ACTIV_OVERRIDE;
virtual size_t GetSerializedBodyLength() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode IsDifferent(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, bool &isDifferent) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetMemoryUsage() const ACTIV_OVERRIDE;
/**
* @brief Get the maximum serialized length of the object.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object.
*/
static size_t GetMaxSerializedLength(const size_t size);
/**
* @brief Get the maximum serialized length of the object's body.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object's body.
*/
static size_t GetMaxSerializedBodyLength(const size_t size);
/**
* @brief Compare two objects serialized bodies.
*
* @param pLhsSerializedBody the buffer containing the lhs serialized version of the object's body in.
* @param lhsSerializedBodyLength the lhs serialized body length.
* @param pRhsSerializedBody the buffer containing the rhs serialized version of the object's body in.
* @param rhsSerializedBodyLength the rhs serialized body length.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API static StatusCode Compare(const void * const pLhsSerializedBody, const size_t lhsSerializedBodyLength, const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result);
/**
* @brief Serialize the object into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Serialize the object's body into the supplied data buffer.
*
* @param pSerializedBody the buffer to store a serialized version of the object's body in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param serializedBodyLength the serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Serialize the object's length and body into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Deserialize the object from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength, const uint8_t *&pData, size_t &size);
/**
* @brief Deserialize the object's body from the supplied data buffer.
*
* @param pSerializedBody the buffer from which the object's body will be extracted.
* @param serializedBodyLength the serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API static StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength, const uint8_t *&pData, size_t &size);
/**
* @brief Deserialize the object's length and body from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength, const uint8_t *&pData, size_t &size);
/**
* @brief Validate the serialized length and body.
*
* @param messageValidator the message validator.
* @param serializedBodyOffset the serialized body offset.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode ValidateSerializedLengthAndBody(MessageValidator &messageValidator, size_t &serializedBodyOffset, size_t &serializedBodyLength);
/**
* @brief Is valid serialized body length.
*
* @param serializedBodyLength the serialized body length.
*
* @return whether the serialized body length is valid.
*/
static bool IsValidSerializedBodyLength(const size_t serializedBodyLength);
/**
* @brief Get a usage string for the format supported by FromString().
*
* @return String, may be empty.
*/
ACTIV_BASE_API static String FromStringFormat();
private:
struct UnknownLengthBitmap : public Bitmap<8, MsbOrigin>
{
typedef BitField<UnknownLengthBitmap, 1> IsMultiByteLength;
typedef BitField<IsMultiByteLength, 1> IsFourByteLength;
};
struct OneByteLengthBitmap : public Bitmap<8, MsbOrigin>
{
typedef BitField<OneByteLengthBitmap, 1> IsMultiByteLength;
typedef BitField<IsMultiByteLength, 7> Length;
};
struct TwoByteLengthBitmap : public Bitmap<16, MsbOrigin>
{
typedef BitField<TwoByteLengthBitmap, 1> IsMultiByteLength;
typedef BitField<IsMultiByteLength, 1> IsFourByteLength;
typedef BitField<IsFourByteLength, 14> Length;
};
struct FourByteLengthBitmap : public Bitmap<32, MsbOrigin>
{
typedef BitField<FourByteLengthBitmap, 1> IsMultiByteLength;
typedef BitField<IsMultiByteLength, 1> IsFourByteLength;
typedef BitField<IsFourByteLength, 30> Length;
};
static const size_t RESERVED_BUFFER_SIZE = 32; ///< The reserved buffer size.
/**
* @brief Compare two buffers.
*
* @param pLhsBuffer the lhs buffer.
* @param lhsBufferLength the lhs buffer length.
* @param pRhsBuffer the rhs buffer.
* @param rhsBufferLength the rhs buffer length.
*
* @return result the result of the comparison.
*/
static int Compare(const void * const pLhsBuffer, const size_t lhsBufferLength, const void * const pRhsBuffer, const size_t rhsBufferLength);
uint8_t m_reservedBuffer[RESERVED_BUFFER_SIZE]; ///< The reserved buffer.
size_t m_allocatedSize; ///< The allocated size of the data.
uint8_t * m_pData; ///< Pointer to the data.
size_t m_size; ///< The size of the data.
#if (defined ACTIV_PLATFORM_WASM)
friend class Wasm::FieldTypeAccessor;
#endif
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline BinaryArray::BinaryArray() :
IFieldType(FIELD_TYPE),
m_allocatedSize(0),
m_pData(m_reservedBuffer)
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline BinaryArray::BinaryArray(const uint8_t * const pData, const size_t size) :
IFieldType(FIELD_TYPE),
m_allocatedSize(0),
m_pData(m_reservedBuffer)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(pData, size));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline BinaryArray::BinaryArray(const BinaryArray &rhs) :
IFieldType(FIELD_TYPE),
m_allocatedSize(0),
m_pData(m_reservedBuffer)
{
if (rhs.IsInitialized())
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(rhs.m_pData, rhs.m_size));
else
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline BinaryArray::~BinaryArray()
{
if (0 != m_allocatedSize)
std::free(m_pData);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool BinaryArray::operator==(const BinaryArray &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (0 == result);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool BinaryArray::operator!=(const BinaryArray &rhs) const
{
return !(*this == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline BinaryArray &BinaryArray::operator=(const BinaryArray &rhs)
{
if (this != &rhs)
{
if (rhs.IsInitialized())
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(rhs.m_pData, rhs.m_size));
}
else
{
Reset();
}
}
return *this;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode BinaryArray::Set(const uint8_t * const pData, const size_t size)
{
if (ACTIV_UNLIKELY(0 == size))
return STATUS_CODE_INVALID_PARAMETER;
if (ACTIV_UNLIKELY(size > GetMaximum<size_t>(m_allocatedSize, size_t(RESERVED_BUFFER_SIZE))))
{
const size_t allocatedSize = (4 * (((std::max<size_t>(m_allocatedSize + (m_allocatedSize / 2), size) - 1) / 4) + 1));
uint8_t * const pAllocated = static_cast<uint8_t *>(((0 != m_allocatedSize) ?
std::realloc(m_pData, allocatedSize) : std::malloc(allocatedSize)));
if (0 == pAllocated)
return STATUS_CODE_HEAP_EMPTY;
m_allocatedSize = allocatedSize;
m_pData = pAllocated;
}
MemoryCopy(m_pData, pData, size);
m_size = size;
m_isInitialized = true;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode BinaryArray::Get(const uint8_t *&pData, size_t &size) const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
return STATUS_CODE_NOT_INITIALIZED;
pData = m_pData;
size = m_size;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const uint8_t *BinaryArray::GetData() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_pData;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t BinaryArray::GetSize() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_size;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void BinaryArray::Reset()
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void BinaryArray::Clear()
{
if (0 != m_allocatedSize)
{
std::free(m_pData);
m_allocatedSize = 0;
}
m_pData = m_reservedBuffer;
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t BinaryArray::GetSerializedLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedLength(m_size);
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t BinaryArray::GetSerializedBodyLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedBodyLength(m_size);
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t BinaryArray::GetMaxSerializedLength(const size_t size)
{
return GetMaxSerializedBodyLength(size);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t BinaryArray::GetMaxSerializedBodyLength(const size_t size)
{
return size;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool BinaryArray::IsValidSerializedBodyLength(const size_t serializedBodyLength)
{
return (0 != serializedBodyLength);
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private Template specialization to map from FIELD_TYPE_BINARY_ARRAY to BinaryArray class.
template<>
class FieldTypeToClass<FIELD_TYPE_BINARY_ARRAY>
{
public:
typedef BinaryArray Type;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_BINARY_ARRAY_H)
@@ -1,580 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/BinaryString.h
*
* @brief Header file for the binary string class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_BINARY_STRING_H)
#define ACTIV_BASE_FIELD_TYPES_BINARY_STRING_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/IFieldType.h"
#include "ActivMiddleware/Misc/MemoryHelper.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
//! Activ namespace.
namespace Activ
{
//! Binary string class.
class BinaryString ACTIV_FINAL : public IFieldType
{
public:
static const FieldType FIELD_TYPE = FIELD_TYPE_BINARY_STRING; ///< The field type.
using IFieldType::FromString;
using IFieldType::Serialize;
using IFieldType::SerializeBody;
using IFieldType::SerializeLengthAndBody;
using IFieldType::Deserialize;
using IFieldType::DeserializeBody;
using IFieldType::DeserializeLengthAndBody;
//! Default constructor.
BinaryString();
/**
* @brief Constructor.
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @throw StatusCodeException
*/
BinaryString(const uint8_t * const pData, const size_t size);
/**
* @brief Copy constructor.
*
* @param rhs the value to assign to this object.
*/
BinaryString(const BinaryString &rhs);
//! Destructor.
virtual ~BinaryString() ACTIV_OVERRIDE;
/**
* @brief Equality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*/
bool operator==(const BinaryString &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*/
bool operator!=(const BinaryString &rhs) const;
/**
* @brief Assignment operator.
*
* @param rhs the value to assign to this object.
*
* @return a reference to this object.
*/
BinaryString& operator=(const BinaryString &rhs);
/**
* @brief Set the data and size.
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_PARAMETER
*/
StatusCode Set(const uint8_t * const pData, const size_t size);
/**
* @brief Get the data and size.
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
*/
StatusCode Get(const uint8_t *&pData, size_t &size) const;
/**
* @brief Get the data.
*
* @return the pointer to the data.
*
* @throw StatusCodeException
*/
const uint8_t *GetData() const;
/**
* @brief Get the size.
*
* @return the size of the data.
*
* @throw StatusCodeException
*/
size_t GetSize() const;
virtual void Reset() ACTIV_OVERRIDE;
virtual void Clear() ACTIV_OVERRIDE;
/**
* @brief Compare.
*
* @param rhs the object to compare with.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API StatusCode Compare(const BinaryString &rhs, int &result) const;
ACTIV_BASE_API virtual StatusCode Compare(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Convert(const IFieldType * const pIFieldType) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode AppendAsString(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
/**
* @brief Convert the object to a string.
*
* @param isHexFormat indicates whether the data is copied in hex format.
*
* @return the object as a string.
*/
ACTIV_BASE_API virtual String ToString(const bool isHexFormat) const;
/**
* @brief Append the object to a message builder as a string.
*
* @param messageBuilder the message builder.
* @param isHexFormat indicates whether the data is copied in hex format.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API virtual StatusCode AppendAsString(MessageBuilder &messageBuilder, const bool isHexFormat) const;
ACTIV_BASE_API virtual StatusCode FromString(MessageValidator &messageValidator) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String GetFromStringFormat() const ACTIV_OVERRIDE;
/**
* @brief Convert the object to a base64 string.
*
* UTF7 indicates whether the data is copied in UTF7 format.
*
* @return the object as a string.
*/
template<bool UTF7>
ACTIV_BASE_API String ToBase64String() const;
/**
* @brief Convert the object from a base64 string.
*
* UTF7 indicates whether the data is copied in UTF7 format.
*
* @param field the field as a base64 string.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
template<bool UTF7>
ACTIV_BASE_API StatusCode FromBase64String(const String &field);
ACTIV_BASE_API virtual StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) ACTIV_OVERRIDE;
virtual size_t GetSerializedLength() const ACTIV_OVERRIDE;
virtual size_t GetSerializedBodyLength() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode IsDifferent(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, bool &isDifferent) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetMemoryUsage() const ACTIV_OVERRIDE;
/**
* @brief Get the maximum serialized length of the object.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object.
*/
static size_t GetMaxSerializedLength(const size_t size);
/**
* @brief Get the maximum serialized length of the object's body.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object's body.
*/
static size_t GetMaxSerializedBodyLength(const size_t size);
/**
* @brief Compare two objects serialized bodies.
*
* @param pLhsSerializedBody the buffer containing the lhs serialized version of the object's body in.
* @param lhsSerializedBodyLength the lhs serialized body length.
* @param pRhsSerializedBody the buffer containing the rhs serialized version of the object's body in.
* @param rhsSerializedBodyLength the rhs serialized body length.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API static StatusCode Compare(const void * const pLhsSerializedBody, const size_t lhsSerializedBodyLength, const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result);
/**
* @brief Serialize the object into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Serialize the object's body into the supplied data buffer.
*
* @param pSerializedBody the buffer to store a serialized version of the object's body in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param serializedBodyLength the serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Serialize the object's length and body into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Deserialize the object from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength, const uint8_t *&pData, size_t &size);
/**
* @brief Deserialize the object's body from the supplied data buffer.
*
* @param pSerializedBody the buffer from which the object's body will be extracted.
* @param serializedBodyLength the serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API static StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength, const uint8_t *&pData, size_t &size);
/**
* @brief Deserialize the object's length and body from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength, const uint8_t *&pData, size_t &size);
/**
* @brief Validate the serialized length and body.
*
* @param messageValidator the message validator.
* @param serializedBodyOffset the serialized body offset.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode ValidateSerializedLengthAndBody(MessageValidator &messageValidator, size_t &serializedBodyOffset, size_t &serializedBodyLength);
/**
* @brief Is valid serialized body length.
*
* @param serializedBodyLength the serialized body length.
*
* @return whether the serialized body length is valid.
*/
static bool IsValidSerializedBodyLength(const size_t serializedBodyLength);
/**
* @brief Get a usage string for the format supported by FromString().
*
* @return String, may be empty.
*/
ACTIV_BASE_API static String FromStringFormat();
private:
static const size_t RESERVED_BUFFER_SIZE = 32; ///< The reserved buffer size.
/**
* @brief Compare two buffers.
*
* @param pLhsBuffer the lhs buffer.
* @param lhsBufferLength the lhs buffer length.
* @param pRhsBuffer the rhs buffer.
* @param rhsBufferLength the rhs buffer length.
*
* @return result the result of the comparison.
*/
static int Compare(const void * const pLhsBuffer, const size_t lhsBufferLength, const void * const pRhsBuffer, const size_t rhsBufferLength);
uint8_t m_reservedBuffer[RESERVED_BUFFER_SIZE]; ///< The reserved buffer.
size_t m_allocatedSize; ///< The allocated size of the data.
uint8_t * m_pData; ///< Pointer to the data.
size_t m_size; ///< The size of the data.
#if (defined ACTIV_PLATFORM_WASM)
friend class Wasm::FieldTypeAccessor;
#endif
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline BinaryString::BinaryString() :
IFieldType(FIELD_TYPE),
m_allocatedSize(0),
m_pData(m_reservedBuffer)
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline BinaryString::BinaryString(const uint8_t * const pData, const size_t size) :
IFieldType(FIELD_TYPE),
m_allocatedSize(0),
m_pData(m_reservedBuffer)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(pData, size));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline BinaryString::BinaryString(const BinaryString &rhs) :
IFieldType(FIELD_TYPE),
m_allocatedSize(0),
m_pData(m_reservedBuffer)
{
if (rhs.IsInitialized())
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(rhs.m_pData, rhs.m_size));
else
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline BinaryString::~BinaryString()
{
if (0 != m_allocatedSize)
std::free(m_pData);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool BinaryString::operator==(const BinaryString &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (0 == result);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool BinaryString::operator!=(const BinaryString &rhs) const
{
return !(*this == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline BinaryString& BinaryString::operator=(const BinaryString &rhs)
{
if (this != &rhs)
{
if (rhs.IsInitialized())
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(rhs.m_pData, rhs.m_size));
}
else
{
Reset();
}
}
return *this;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode BinaryString::Set(const uint8_t * const pData, const size_t size)
{
if (ACTIV_UNLIKELY(0 == size))
return STATUS_CODE_INVALID_PARAMETER;
if (ACTIV_UNLIKELY(size > GetMaximum<size_t>(m_allocatedSize, size_t(RESERVED_BUFFER_SIZE))))
{
const size_t allocatedSize = (4 * (((std::max<size_t>(m_allocatedSize + (m_allocatedSize / 2), size) - 1) / 4) + 1));
uint8_t * const pAllocated = static_cast<uint8_t *>(((0 != m_allocatedSize) ? std::realloc(m_pData, allocatedSize) : std::malloc(allocatedSize)));
if (0 == pAllocated)
return STATUS_CODE_HEAP_EMPTY;
m_allocatedSize = allocatedSize;
m_pData = pAllocated;
}
MemoryCopy(m_pData, pData, size);
m_size = size;
m_isInitialized = true;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode BinaryString::Get(const uint8_t *&pData, size_t &size) const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
return STATUS_CODE_NOT_INITIALIZED;
pData = m_pData;
size = m_size;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const uint8_t *BinaryString::GetData() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_pData;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t BinaryString::GetSize() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_size;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void BinaryString::Reset()
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void BinaryString::Clear()
{
if (0 != m_allocatedSize)
{
std::free(m_pData);
m_allocatedSize = 0;
}
m_pData = m_reservedBuffer;
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t BinaryString::GetSerializedLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedLength(m_size);
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t BinaryString::GetSerializedBodyLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedBodyLength(m_size);
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t BinaryString::GetMaxSerializedLength(const size_t size)
{
return (sizeof(uint8_t) + GetMaxSerializedBodyLength(size));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t BinaryString::GetMaxSerializedBodyLength(const size_t size)
{
return size;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool BinaryString::IsValidSerializedBodyLength(const size_t serializedBodyLength)
{
return ((serializedBodyLength > 0) && (serializedBodyLength <= UINT8_MAX));
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private Template specialization to map from FIELD_TYPE_BINARY_STRING to BinaryString class.
template<>
class FieldTypeToClass<FIELD_TYPE_BINARY_STRING>
{
public:
typedef BinaryString Type;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_BINARY_STRING_H)
@@ -1,971 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/Blob.h
*
* @brief Header file for the blob class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_BLOB_H)
#define ACTIV_BASE_FIELD_TYPES_BLOB_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/IFieldType.h"
#include "ActivMiddleware/Misc/MemoryHelper.h"
#include "ActivMiddleware/ActivBase/ActivBase.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/ActivBase/Compress/ZlibCompressor.h"
//! Activ namespace.
namespace Activ
{
//! Blob class.
class Blob ACTIV_FINAL : public IFieldType
{
public:
static const FieldType FIELD_TYPE = FIELD_TYPE_BLOB; ///< The field type.
using IFieldType::FromString;
using IFieldType::Serialize;
using IFieldType::SerializeBody;
using IFieldType::SerializeLengthAndBody;
using IFieldType::Deserialize;
using IFieldType::DeserializeBody;
using IFieldType::DeserializeLengthAndBody;
//! Default constructor.
Blob();
/**
* @brief Constructor.
*
* @param pData pointer to the data.
* @param size the size of the data.
* @param sizeWhenDecompressed indicates the size of the data when decompressed (zero indicates uncompressed).
*
* @throw StatusCodeException
*/
Blob(const uint8_t * const pData, const size_t size, const size_t sizeWhenDecompressed);
/**
* @brief Constructor.
*
* The data will be stored compressed (if size >= compressed size).
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @throw StatusCodeException
*/
Blob(const uint8_t * const pData, const size_t size);
/**
* @brief Copy constructor.
*
* @param rhs the value to assign to this object.
*/
Blob(const Blob &rhs);
//! Destructor.
virtual ~Blob() ACTIV_OVERRIDE;
/**
* @brief Equality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator==(const Blob &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator!=(const Blob &rhs) const;
/**
* @brief Assignment operator.
*
* @param rhs the value to assign to this object.
*
* @return a reference to this object.
*/
Blob& operator=(const Blob &rhs);
/**
* @brief Set the data, size and decompressed size.
*
* @param pData pointer to the data.
* @param size the size of the data.
* @param sizeWhenDecompressed indicates the size of the data when decompressed (zero indicates uncompressed).
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_PARAMETER
*/
StatusCode Set(const uint8_t * const pData, const size_t size, const size_t sizeWhenDecompressed);
/**
* @brief Set the data and size.
*
* The data will be stored compressed (only if compressed size < decompressed size).
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
StatusCode Set(const uint8_t * const pData, const size_t size);
/**
* @brief Get the data, size and decompressed size.
*
* @param pData pointer to the data.
* @param size the size of the data.
* @param sizeWhenDecompressed indicates the size of the data when decompressed (zero indicates uncompressed).
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
*/
StatusCode Get(const uint8_t *&pData, size_t &size, size_t &sizeWhenDecompressed) const;
/**
* @brief Get the data and size.
*
* The data will be returned uncompressed.
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval ...
*/
StatusCode Get(const uint8_t *&pData, size_t &size) const;
/**
* @brief Get the data.
*
* @return the pointer to the data.
*
* @throw StatusCodeException
*/
const uint8_t *GetData() const;
/**
* @brief Get the size of the data.
*
* @return the size of the data.
*
* @throw StatusCodeException
*/
size_t GetSize() const;
/**
* @brief Get the size when decompressed.
*
* @return the size of the data when decompressed.
*
* @throw StatusCodeException
*/
size_t GetSizeWhenDecompressed() const;
/**
* @brief Get the data compressed.
*
* @return the pointer to the data compressed.
*
* @throw StatusCodeException
*/
const uint8_t *GetDataCompressed() const;
/**
* @brief Get the size of the data compressed.
*
* @return the size of the data compressed.
*
* @throw StatusCodeException
*/
size_t GetSizeCompressed() const;
/**
* @brief Get the data decompressed.
*
* @return the pointer to the data decompressed.
*
* @throw StatusCodeException
*/
const uint8_t *GetDataDecompressed() const;
/**
* @brief Get the size of the data decompressed.
*
* @return the size of the data decompressed.
*
* @throw StatusCodeException
*/
size_t GetSizeDecompressed() const;
virtual void Reset() ACTIV_OVERRIDE;
virtual void Clear() ACTIV_OVERRIDE;
/**
* @brief Compare.
*
* @param rhs the object to compare with.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API StatusCode Compare(const Blob &rhs, int &result) const;
ACTIV_BASE_API virtual StatusCode Compare(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Convert(const IFieldType * const pIFieldType) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode AppendAsString(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
/**
* @brief Convert the object to a string.
*
* @param isHexFormat indicates whether the data is copied in hex format.
*
* @return the object as a string.
*
* @throw StatusCodeException
*/
ACTIV_BASE_API virtual String ToString(const bool isHexFormat) const;
/**
* @brief Append the object to a message builder as a string.
*
* @param messageBuilder the message builder.
* @param isHexFormat indicates whether the data is copied in hex format.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API virtual StatusCode AppendAsString(MessageBuilder &messageBuilder, const bool isHexFormat) const;
ACTIV_BASE_API virtual StatusCode FromString(MessageValidator &messageValidator) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String GetFromStringFormat() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) ACTIV_OVERRIDE;
virtual size_t GetSerializedLength() const ACTIV_OVERRIDE;
virtual size_t GetSerializedBodyLength() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode IsDifferent(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, bool &isDifferent) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetMemoryUsage() const ACTIV_OVERRIDE;
/**
* @brief Compress.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval ...
*/
StatusCode Compress() const;
/**
* @brief Compress.
*
* @param shouldSerializeCompressed indicates whether the object should be serialized compressed (only if compressed size < decompressed size).
* @param shouldForceSerializeCompressed indicates whether should force the object should be serialized compressed.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval ...
*/
StatusCode Compress(bool shouldSerializeCompressed, bool shouldForceSerializeCompressed = false);
/**
* @brief Decompress.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval ...
*/
StatusCode Decompress() const;
/**
* @brief Decompress.
*
* @param shouldSerializeDecompressed indicates whether the object should be serialized decompressed.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval ...
*/
StatusCode Decompress(bool shouldSerializeDecompressed);
//! Is the data compressed.
bool IsCompressed() const;
/**
* @brief Get the maximum serialized length of the object.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object.
*/
static size_t GetMaxSerializedLength(const size_t size);
/**
* @brief Get the maximum serialized length of the object's body.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object's body.
*/
static size_t GetMaxSerializedBodyLength(const size_t size);
/**
* @brief Compare two objects serialized bodies.
*
* @param pLhsSerializedBody the buffer containing the lhs serialized version of the object's body in.
* @param lhsSerializedBodyLength the lhs serialized body length.
* @param pRhsSerializedBody the buffer containing the rhs serialized version of the object's body in.
* @param rhsSerializedBodyLength the rhs serialized body length.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API static StatusCode Compare(const void * const pLhsSerializedBody, const size_t lhsSerializedBodyLength, const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result);
/**
* @brief Serialize the object into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
* @param sizeWhenDecompressed indicates the size of the data when decompressed (zero indicates uncompressed).
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength, const uint8_t * const pData, const size_t size, const size_t sizeWhenDecompressed = 0);
/**
* @brief Serialize the object's body into the supplied data buffer.
*
* @param pSerializedBody the buffer to store a serialized version of the object's body in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param serializedBodyLength the serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
* @param sizeWhenDecompressed indicates the size of the data when decompressed (zero indicates uncompressed).
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength, const uint8_t * const pData, const size_t size, const size_t sizeWhenDecompressed = 0);
/**
* @brief Serialize the object's length and body into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
* @param sizeWhenDecompressed indicates the size of the data when decompressed (zero indicates uncompressed).
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength, const uint8_t * const pData, const size_t size, const size_t sizeWhenDecompressed = 0);
/**
* @brief Deserialize the object from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
* @param sizeWhenDecompressed indicates the size of the data when decompressed (zero indicates uncompressed).
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength, const uint8_t *&pData, size_t &size, size_t &sizeWhenDecompressed);
/**
* @brief Deserialize the object's body from the supplied data buffer.
*
* @param pSerializedBody the buffer from which the object's body will be extracted.
* @param serializedBodyLength the serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
* @param sizeWhenDecompressed indicates the size of the data when decompressed (zero indicates uncompressed).
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength, const uint8_t *&pData, size_t &size, size_t &sizeWhenDecompressed);
/**
* @brief Deserialize the object's length and body from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
* @param sizeWhenDecompressed indicates the size of the data when decompressed (zero indicates uncompressed).
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength, const uint8_t *&pData, size_t &size, size_t &sizeWhenDecompressed);
/**
* @brief Validate the serialized length and body.
*
* @param messageValidator the message validator.
* @param serializedBodyOffset the serialized body offset.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode ValidateSerializedLengthAndBody(MessageValidator &messageValidator, size_t &serializedBodyOffset, size_t &serializedBodyLength);
/**
* @brief Is valid serialized body length.
*
* @param serializedBodyLength the serialized body length.
*
* @return whether the serialized body length is valid.
*/
static bool IsValidSerializedBodyLength(const size_t serializedBodyLength);
/**
* @brief Compress a buffer.
*
* @param pSource the source buffer.
* @param sourceLength the source buffer length.
* @param pTarget the target buffer.
* @param targetSize the size of the target buffer.
* @param targetLength the target buffer length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
static StatusCode Compress(const uint8_t * const pSource, const size_t sourceLength, uint8_t * const pTarget, const size_t targetSize, size_t &targetLength);
/**
* @brief Decompress a buffer.
*
* @param pSource the source buffer.
* @param sourceLength the source buffer length.
* @param pTarget the target buffer.
* @param targetSize the size of the target buffer.
* @param targetLength the target buffer length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
static StatusCode Decompress(const uint8_t * const pSource, const size_t sourceLength, uint8_t * const pTarget, const size_t targetSize, size_t &targetLength);
/**
* @brief Get a usage string for the format supported by FromString().
*
* @return String, may be empty.
*/
ACTIV_BASE_API static String FromStringFormat();
private:
/**
* @brief Compare two buffers.
*
* @param pLhsBuffer the lhs buffer.
* @param lhsBufferLength the lhs buffer length.
* @param pRhsBuffer the rhs buffer.
* @param rhsBufferLength the rhs buffer length.
*
* @return result the result of the comparison.
*/
static int Compare(const void * const pLhsBuffer, const size_t lhsBufferLength, const void * const pRhsBuffer, const size_t rhsBufferLength);
mutable uint8_t * m_pDataCompressed; ///< Pointer to the data compressed.
mutable size_t m_allocatedSizeCompressed; ///< The allocated size of the data compressed.
mutable size_t m_sizeCompressed; ///< The size of the data compressed.
mutable uint8_t * m_pDataDecompressed; ///< Pointer to the data decompressed.
mutable size_t m_allocatedSizeDecompressed; ///< The allocated size of the data decompressed.
mutable size_t m_sizeDecompressed; ///< The size of the data decompressed.
uint8_t * m_pData; ///< Pointer to the data.
size_t m_size; ///< The size of the data.
size_t m_sizeWhenDecompressed; ///< The size of the data when decompressed.
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline Blob::Blob() :
IFieldType(FIELD_TYPE),
m_allocatedSizeCompressed(0),
m_allocatedSizeDecompressed(0)
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Blob::Blob(const uint8_t * const pData, const size_t size, const size_t sizeWhenDecompressed) :
IFieldType(FIELD_TYPE),
m_allocatedSizeCompressed(0),
m_allocatedSizeDecompressed(0)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(pData, size, sizeWhenDecompressed));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Blob::Blob(const uint8_t * const pData, const size_t size) :
IFieldType(FIELD_TYPE),
m_allocatedSizeCompressed(0),
m_allocatedSizeDecompressed(0)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(pData, size));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Blob::Blob(const Blob &rhs) :
IFieldType(FIELD_TYPE),
m_allocatedSizeCompressed(0),
m_allocatedSizeDecompressed(0)
{
if (rhs.IsInitialized())
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(rhs.m_pData, rhs.m_size, rhs.m_sizeWhenDecompressed));
else
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Blob::~Blob()
{
if (0 != m_allocatedSizeCompressed)
std::free(m_pDataCompressed);
if (0 != m_allocatedSizeDecompressed)
std::free(m_pDataDecompressed);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Blob::operator==(const Blob &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (0 == result);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Blob::operator!=(const Blob &rhs) const
{
return !((*this) == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Blob& Blob::operator=(const Blob &rhs)
{
if (this != &rhs)
{
if (rhs.IsInitialized())
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(rhs.m_pData, rhs.m_size, rhs.m_sizeWhenDecompressed));
}
else
{
Reset();
}
}
return *this;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Blob::Set(const uint8_t * const pData, const size_t size, const size_t sizeWhenDecompressed)
{
if (ACTIV_UNLIKELY(0 == size))
return STATUS_CODE_INVALID_PARAMETER;
if (0 == sizeWhenDecompressed)
{
if (ACTIV_UNLIKELY(size > m_allocatedSizeDecompressed))
{
const size_t allocatedSize = (4 * (((std::max<size_t>(m_allocatedSizeDecompressed + (m_allocatedSizeDecompressed / 2), size) - 1) / 4) + 1));
uint8_t * const pAllocated = static_cast<uint8_t *>(((0 != m_allocatedSizeDecompressed) ? std::realloc(m_pDataDecompressed, allocatedSize) : std::malloc(allocatedSize)));
if (0 == pAllocated)
return STATUS_CODE_HEAP_EMPTY;
m_allocatedSizeDecompressed = allocatedSize;
m_pDataDecompressed = pAllocated;
}
MemoryCopy(m_pDataDecompressed, pData, size);
m_sizeDecompressed = size;
m_sizeCompressed = 0;
m_pData = m_pDataDecompressed;
m_size = size;
m_sizeWhenDecompressed = sizeWhenDecompressed;
m_isInitialized = true;
}
else
{
if (ACTIV_UNLIKELY(size > m_allocatedSizeCompressed))
{
const size_t allocatedSize = (4 * (((std::max<size_t>(m_allocatedSizeCompressed + (m_allocatedSizeCompressed / 2), size) - 1) / 4) + 1));
uint8_t * const pAllocated = static_cast<uint8_t *>(((0 != m_allocatedSizeCompressed) ? std::realloc(m_pDataCompressed, allocatedSize) : std::malloc(allocatedSize)));
if (0 == pAllocated)
return STATUS_CODE_HEAP_EMPTY;
m_allocatedSizeCompressed = allocatedSize;
m_pDataCompressed = pAllocated;
}
MemoryCopy(m_pDataCompressed, pData, size);
m_sizeCompressed = size;
m_sizeDecompressed = 0;
m_pData = m_pDataCompressed;
m_size = size;
m_sizeWhenDecompressed = sizeWhenDecompressed;
m_isInitialized = true;
}
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Blob::Set(const uint8_t * const pData, const size_t size)
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, Set(pData, size, 0));
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, Compress(true));
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Blob::Get(const uint8_t *&pData, size_t &size, size_t &sizeWhenDecompressed) const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
return STATUS_CODE_NOT_INITIALIZED;
pData = m_pData;
size = m_size;
sizeWhenDecompressed = m_sizeWhenDecompressed;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Blob::Get(const uint8_t *&pData, size_t &size) const
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, Decompress());
pData = m_pDataDecompressed;
size = m_sizeDecompressed;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const uint8_t *Blob::GetData() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_pData;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Blob::GetSize() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_size;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Blob::GetSizeWhenDecompressed() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_sizeWhenDecompressed;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const uint8_t *Blob::GetDataCompressed() const
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compress());
return m_pDataCompressed;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Blob::GetSizeCompressed() const
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compress());
return m_sizeCompressed;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const uint8_t *Blob::GetDataDecompressed() const
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Decompress());
return m_pDataDecompressed;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Blob::GetSizeDecompressed() const
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Decompress());
return m_sizeDecompressed;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Blob::Reset()
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Blob::Clear()
{
if (0 != m_allocatedSizeCompressed)
{
std::free(m_pDataCompressed);
m_allocatedSizeCompressed = 0;
}
if (0 != m_allocatedSizeDecompressed)
{
std::free(m_pDataDecompressed);
m_allocatedSizeDecompressed = 0;
}
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Blob::GetSerializedLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedLength(m_size);
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Blob::GetSerializedBodyLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedBodyLength(m_size);
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Blob::Compress() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
return STATUS_CODE_NOT_INITIALIZED;
if (0 == m_sizeCompressed)
{
const size_t sizeCompressed = ACTIV_COMPRESS_GET_DESTINATION_BUFFER_LENGTH(m_sizeDecompressed);
if (sizeCompressed > m_allocatedSizeCompressed)
{
const size_t allocatedSize = (4 * (((std::max<size_t>(m_allocatedSizeCompressed + (m_allocatedSizeCompressed / 2), sizeCompressed) - 1) / 4) + 1));
uint8_t * const pAllocated = static_cast<uint8_t *>(((0 != m_allocatedSizeCompressed) ? std::realloc(m_pDataCompressed, allocatedSize) : std::malloc(allocatedSize)));
if (0 == pAllocated)
return STATUS_CODE_HEAP_EMPTY;
m_allocatedSizeCompressed = allocatedSize;
m_pDataCompressed = pAllocated;
}
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, Compress(m_pDataDecompressed, m_sizeDecompressed, m_pDataCompressed, m_allocatedSizeCompressed, m_sizeCompressed));
}
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Blob::Compress(bool shouldSerializeCompressed, bool shouldForceSerializeCompressed)
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, Compress());
if ((0 == m_sizeWhenDecompressed) && (((shouldSerializeCompressed) && (m_sizeCompressed < m_sizeDecompressed)) || (shouldForceSerializeCompressed)))
{
m_pData = m_pDataCompressed;
m_size = m_sizeCompressed;
m_sizeWhenDecompressed = m_sizeDecompressed;
}
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Blob::Decompress() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
return STATUS_CODE_NOT_INITIALIZED;
if (0 == m_sizeDecompressed)
{
if (m_sizeWhenDecompressed > m_allocatedSizeDecompressed)
{
const size_t allocatedSize = (4 * (((std::max<size_t>(m_allocatedSizeDecompressed + (m_allocatedSizeDecompressed / 2), m_sizeWhenDecompressed) - 1) / 4) + 1));
uint8_t * const pAllocated = static_cast<uint8_t *>(((0 != m_allocatedSizeDecompressed) ? std::realloc(m_pDataDecompressed, allocatedSize) : std::malloc(allocatedSize)));
if (0 == pAllocated)
return STATUS_CODE_HEAP_EMPTY;
m_allocatedSizeDecompressed = allocatedSize;
m_pDataDecompressed = pAllocated;
}
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, Decompress(m_pDataCompressed, m_sizeCompressed, m_pDataDecompressed, m_allocatedSizeDecompressed, m_sizeDecompressed));
}
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Blob::Decompress(bool shouldSerializeDecompressed)
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, Decompress());
if ((shouldSerializeDecompressed) && (0 != m_sizeWhenDecompressed))
{
m_pData = m_pDataDecompressed;
m_size = m_sizeDecompressed;
m_sizeWhenDecompressed = 0;
}
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Blob::IsCompressed() const
{
if (ACTIV_LIKELY(IsInitialized()))
return (0 != m_sizeWhenDecompressed);
else
return false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Blob::GetMaxSerializedLength(const size_t size)
{
return (sizeof(uint32_t) + GetMaxSerializedBodyLength(size));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Blob::GetMaxSerializedBodyLength(const size_t size)
{
return (sizeof(uint32_t) + size);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Blob::IsValidSerializedBodyLength(const size_t serializedBodyLength)
{
return ((serializedBodyLength > GetMaxSerializedBodyLength(0)) && (serializedBodyLength <= UINT32_MAX));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Blob::Compress(const uint8_t * const pSource, const size_t sourceLength, uint8_t * const pTarget, const size_t targetSize, size_t &targetLength)
{
return ZlibCompressor().Compress(pTarget, targetSize, pSource, sourceLength, targetLength);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Blob::Decompress(const uint8_t * const pSource, const size_t sourceLength, uint8_t * const pTarget, const size_t targetSize, size_t &targetLength)
{
return ZlibCompressor().Decompress(pTarget, targetSize, pSource, sourceLength, targetLength);
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private Template specialization to map from FIELD_TYPE_BLOB to Blob class.
template<>
class FieldTypeToClass<FIELD_TYPE_BLOB>
{
public:
typedef Blob Type;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_BLOB_H)
@@ -1,384 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/Boolean.h
*
* @brief Header file for the boolean class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_BOOLEAN_H)
#define ACTIV_BASE_FIELD_TYPES_BOOLEAN_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/IFieldType.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/Misc/MemoryHelper.h"
//! Activ namespace.
namespace Activ
{
//! Boolean class.
class Boolean ACTIV_FINAL : public IFieldType
{
public:
static const FieldType FIELD_TYPE = FIELD_TYPE_BOOLEAN; ///< The field type.
using IFieldType::FromString;
using IFieldType::Serialize;
using IFieldType::SerializeBody;
using IFieldType::SerializeLengthAndBody;
using IFieldType::Deserialize;
using IFieldType::DeserializeBody;
using IFieldType::DeserializeLengthAndBody;
//! Default constructor.
Boolean();
/**
* @brief Constructor.
*
* @param value the value.
*/
Boolean(const bool value);
//! Destructor.
virtual ~Boolean() ACTIV_OVERRIDE;
/**
* @brief Equality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator==(const Boolean &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator!=(const Boolean &rhs) const;
/**
* @brief Set a new value.
*
* @param value the value.
*
* @retval STATUS_CODE_SUCCESS
*/
StatusCode Set(const bool value);
/**
* @brief Get the value.
*
* @param value the value.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
*/
StatusCode Get(bool &value) const;
/**
* @brief Get the value.
*
* @return the value.
*
* @throw StatusCodeException
*/
bool Get() const;
virtual void Reset() ACTIV_OVERRIDE;
virtual void Clear() ACTIV_OVERRIDE;
/**
* @brief Compare.
*
* @param rhs the object to compare with.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API StatusCode Compare(const Boolean &rhs, int &result) const;
ACTIV_BASE_API virtual StatusCode Compare(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength,
int &result) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Convert(const IFieldType * const pIFieldType) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode AppendAsString(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode FromString(MessageValidator &messageValidator) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String GetFromStringFormat() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength,
size_t &serializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder,
const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator,
const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) ACTIV_OVERRIDE;
virtual size_t GetSerializedLength() const ACTIV_OVERRIDE;
virtual size_t GetSerializedBodyLength() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode IsDifferent(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength,
bool &isDifferent) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetMemoryUsage() const ACTIV_OVERRIDE;
/**
* @brief Get the maximum serialized length of the object.
*
* @return the maximum serialized length of the object.
*/
static size_t GetMaxSerializedLength();
/**
* @brief Get the maximum serialized length of the object's body.
*
* @return the maximum serialized length of the object's body.
*/
static size_t GetMaxSerializedBodyLength();
/**
* @brief Compare two objects serialized bodies.
*
* @param pLhsSerializedBody the buffer containing the lhs serialized version of the object's body in.
* @param lhsSerializedBodyLength the lhs serialized body length.
* @param pRhsSerializedBody the buffer containing the rhs serialized version of the object's body in.
* @param rhsSerializedBodyLength the rhs serialized body length.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API static StatusCode Compare(const void * const pLhsSerializedBody, const size_t lhsSerializedBodyLength,
const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result);
/**
* @brief Validate the serialized length and body.
*
* @param messageValidator the message validator.
* @param serializedBodyOffset the serialized body offset.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode ValidateSerializedLengthAndBody(MessageValidator &messageValidator,
size_t &serializedBodyOffset, size_t &serializedBodyLength);
/**
* @brief Serialize a value's length and body into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param value the value to serialize.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
static StatusCode SerializeValueLengthAndBody(MessageBuilder &messageBuilder, const bool value);
/**
* @brief Is valid serialized body length.
*
* @param serializedBodyLength the serialized body length.
*
* @return whether the serialized body length is valid.
*/
static bool IsValidSerializedBodyLength(const size_t serializedBodyLength);
/**
* @brief Get a usage string for the format supported by FromString().
*
* @return String, may be empty.
*/
ACTIV_BASE_API static String FromStringFormat();
private:
/**
* @brief Serialize the object's body into the supplied data buffer.
*
* This will serialize to a fixed size buffer (GetMaxSerializedLength<T>()).
*
* @param pSerializedBody the buffer to store a serialized version of the object in.
*
* @retval STATUS_CODE_SUCCESS
*/
template <typename T>
StatusCode SerializeBody(void * const pSerializedBody) const;
/**
* @brief Deserialize the object's body from the supplied data buffer.
*
* This will deserialize from a fixed size buffer (GetMaxSerializedLength<T>()).
*
* @param pSerializedBody the buffer from which the object will be extracted.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_FORMAT
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval STATUS_CODE_OUT_OF_RANGE
*/
template <typename T> StatusCode DeserializeBody(const void * const pSerializedBody);
static const size_t MAX_SERIALIZED_BODY_LENGTH = 1; ///< The max serialized body length.
bool m_value; ///< The value.
#if (defined ACTIV_PLATFORM_WASM)
friend class Wasm::FieldTypeAccessor;
#endif
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline Boolean::Boolean() :
IFieldType(FIELD_TYPE)
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Boolean::Boolean(const bool value) :
IFieldType(FIELD_TYPE)
{
(void) Set(value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Boolean::~Boolean()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Boolean::operator==(const Boolean &rhs) const
{
if (m_isInitialized)
return (rhs.m_isInitialized && (m_value == rhs.m_value));
else
return !rhs.m_isInitialized;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Boolean::operator!=(const Boolean &rhs) const
{
return !((*this) == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Boolean::Set(const bool value)
{
m_value = value;
m_isInitialized = true;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Boolean::Get(bool &value) const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
return STATUS_CODE_NOT_INITIALIZED;
value = m_value;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Boolean::Get() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_value;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Boolean::Reset()
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Boolean::Clear()
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Boolean::GetSerializedLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedLength();
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Boolean::GetSerializedBodyLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedLength();
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Boolean::GetMaxSerializedLength()
{
return GetMaxSerializedBodyLength();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Boolean::GetMaxSerializedBodyLength()
{
return MAX_SERIALIZED_BODY_LENGTH;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Boolean::SerializeValueLengthAndBody(MessageBuilder &messageBuilder, const bool value)
{
return messageBuilder.Append(static_cast<uint8_t>(value ? 1 : 0));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Boolean::IsValidSerializedBodyLength(const size_t serializedBodyLength)
{
return (GetMaxSerializedBodyLength() == serializedBodyLength);
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private Template specialization to map from FIELD_TYPE_BOOLEAN to Boolean class.
template<>
class FieldTypeToClass<FIELD_TYPE_BOOLEAN>
{
public:
typedef Boolean Type;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_BOOLEAN_H)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,765 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/FieldMap.h
*
* @brief Header file for the FieldMap class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_FIELD_MAP_H)
#define ACTIV_BASE_FIELD_TYPES_FIELD_MAP_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/IFieldType.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Boolean.h"
#include "ActivMiddleware/ActivBase/FieldTypes/TextString.h"
#include "ActivMiddleware/ActivBase/FieldTypes/UInt.h"
#include "ActivMiddleware/ActivBase/FieldTypes/FieldTypeList.h"
#include "ActivMiddleware/CxxYZ/map.h"
#include "ActivMiddleware/CxxYZ/memory.h"
#include ACTIV_BOOST_INCLUDE(range/const_iterator.hpp)
#include ACTIV_BOOST_INCLUDE(range/iterator.hpp)
//! Activ namespace.
namespace Activ
{
//! Field map class.
class FieldMap ACTIV_FINAL : public IFieldType
{
public:
static const FieldType FIELD_TYPE = FIELD_TYPE_FIELD_MAP; ///< The field type.
//! Field identifier type.
typedef uint16_t FieldId;
//! The underlying map type.
typedef CxxYZ::map<FieldId, CxxYZ::unique_ptr<IFieldType> > Map;
//! The const iterator type.
typedef Map::const_iterator ConstIterator;
//! The value type type.
typedef Map::value_type ValueType;
using IFieldType::FromString;
using IFieldType::Serialize;
using IFieldType::SerializeBody;
using IFieldType::SerializeLengthAndBody;
using IFieldType::Deserialize;
using IFieldType::DeserializeBody;
using IFieldType::DeserializeLengthAndBody;
//! Default constructor.
FieldMap();
/**
* @brief Copy constructor.
*
* @param rhs the value to assign to this object.
*/
ACTIV_BASE_API FieldMap(const FieldMap &rhs);
//! Is present.
ACTIV_BASE_API bool IsPresent(const FieldId fieldId) const;
//! Is defined.
ACTIV_BASE_API bool IsDefined(const FieldId fieldId) const;
/**
* @brief Set a field to an initialized value.
*
* If @a value is not initialized an exception is thrown.
*
* If the field already exists, it's value will be overwritten.
*
* @param fieldId id of the field to set.
* @param value the new value to set.
*
* @throw Exception
* @throw std::exception
*/
ACTIV_BASE_API void Set(const FieldId fieldId, const IFieldType &value);
/**
* @brief Set a field to an initialized value.
*
* If @a value is not initialized an exception is thrown.
*
* If the field already exists, it's value will be overwritten.
*
* @param fieldId id of the field to set.
* @param fieldValue the new value to set.
*
* @throw Exception
* @throw std::exception
*/
template<typename T>
typename Boost::enable_if_c<Boost::is_integral<T>::value && !Boost::is_same<bool, T>::value, void>::type
Set(const FieldId fieldId, const T fieldValue);
/**
* @brief Set a field to an initialized value.
*
* If @a value is not initialized an exception is thrown.
*
* If the field already exists, it's value will be overwritten.
*
* @param fieldId id of the field to set.
* @param fieldValue the new value to set.
*
* @throw Exception
* @throw std::exception
*/
template<typename T>
typename Boost::enable_if<Boost::is_floating_point<T>, void>::type Set(const FieldId fieldId, const T fieldValue);
/**
* @brief Set a field to an initialized value.
*
* If @a value is not initialized an exception is thrown.
*
* If the field already exists, it's value will be overwritten.
*
* @param fieldId id of the field to set.
* @param fieldValue the new value to set.
*
* @throw Exception
* @throw std::exception
*/
template<typename T>
typename Boost::enable_if<Boost::is_same<bool, T>, void>::type Set(const FieldId fieldId, const T fieldValue);
/**
* @brief Set a field to an initialized value.
*
* If @a value is not initialized an exception is thrown.
*
* If the field already exists, it's value will be overwritten.
*
* @param fieldId id of the field to set.
* @param fieldValue the new value to set.
*
* @throw Exception
* @throw std::exception
*/
template<typename T>
typename Boost::enable_if<Boost::is_same<String, T>, void>::type Set(const FieldId fieldId, const T &fieldValue);
#if (!defined ACTIV_BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
/**
* @brief Set a field to an initialized list value.
*
* If the field already exists, it's value will be overwritten.
*
* @param fieldId id of the field to set.
* @param fieldValue the new value to set.
*
* @throw Exception
* @throw std::exception
*/
template<typename T>
void Set(const FieldId fieldId, std::initializer_list<T> fieldValue);
#endif
/**
* @brief Set a field to an initialized value.
*
* If @a value is empty string, an exception is thrown.
*
* If the field already exists, it's value will be overwritten.
*
* @param fieldId id of the field to set.
* @param fieldValue the new value to set.
*
* @throw Exception
* @throw std::exception
*/
void Set(const FieldId fieldId, const char *fieldValue);
/**
* @brief Set a field to be undefined.
*
* If the field already exists, it's value will be cleared.
*
* Undefining a field will create or update an entry in the map, with a null pointer to represent that the field is undefined.
*
* @param fieldId id of the field to undefine.
*
* @throw std::exception
*/
ACTIV_BASE_API void SetUndefined(const FieldId fieldId);
/**
* @brief Remove a field from the map.
*
* @param fieldId if of the field to remove.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
*/
ACTIV_BASE_API StatusCode Remove(const FieldId fieldId);
/**
* @brief Get a field from the map.
*
* A pointer is passed back to the field value in the map. Uninitialized field values should not be present in the map.
* The field value must not be cleared and assigned to an uninitialized value.
*
* @param fieldId id of the field to get.
* @param pFieldType reference to IFieldType pointer to receive the field value.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
*/
ACTIV_BASE_API StatusCode Get(const FieldId fieldId, IFieldType *&pFieldType);
/**
* @brief Get a const field from the map.
*
* @param fieldId id of the field to get.
* @param pFieldType reference to IFieldType pointer to receive the field value.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
*/
ACTIV_BASE_API StatusCode Get(const FieldId fieldId, const IFieldType *&pFieldType) const;
/**
* @brief Get a field from the map.
*
* @param fieldId id of the field to get.
* @param pFieldType reference to IFieldType pointer to receive the field value.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
*/
template <typename T>
typename Boost::enable_if<IsFieldType<T>, StatusCode>::type Get(const FieldId fieldId, T *&pFieldType);
/**
* @brief Get a const field from the map.
*
* @param fieldId id of the field to get.
* @param pFieldType reference to IFieldType pointer to receive the field value.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
*/
template <typename T>
typename Boost::enable_if<IsFieldType<T>, StatusCode>::type Get(const FieldId fieldId, const T *&pFieldType) const;
/**
* @brief Get field value base on field from the map.
*
* @param fieldId id of the field to get.
* @param fieldValue reference where the field value will be returned.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
* @retval STATUS_CODE_OUT_OF_RANGE
*/
template<typename T>
ACTIV_BASE_API typename Boost::enable_if<Boost::is_signed<T>, StatusCode>::type Get(const FieldId fieldId, T &fieldValue) const;
/**
* @brief Get field value base on field from the map.
*
* @param fieldId id of the field to get.
* @param fieldValue reference where the field value will be returned.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
* @retval STATUS_CODE_OUT_OF_RANGE
*/
template<typename T>
ACTIV_BASE_API typename Boost::enable_if_c<Boost::is_unsigned<T>::value && !Boost::is_same<bool, T>::value, StatusCode>::type
Get(const FieldId fieldId, T &fieldValue) const;
/**
* @brief Get field value base on field from the map.
*
* @param fieldId id of the field to get.
* @param fieldValue reference where the field value will be returned.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
* @retval STATUS_CODE_OUT_OF_RANGE
*/
template<typename T>
ACTIV_BASE_API typename Boost::enable_if<Boost::is_floating_point<T>, StatusCode>::type Get(const FieldId fieldId, T &fieldValue) const;
/**
* @brief Get field value base on field from the map.
*
* @param fieldId id of the field to get.
* @param fieldValue reference where the field value will be returned.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
* @retval STATUS_CODE_OUT_OF_RANGE
*/
template<typename T>
ACTIV_BASE_API typename Boost::enable_if<Boost::is_same<bool, T>, StatusCode>::type Get(const FieldId fieldId, bool &fieldValue) const;
/**
* @brief Get field value base on field from the map.
*
* @param fieldId id of the field to get.
* @param fieldValue reference where the field value will be returned.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
* @retval STATUS_CODE_OUT_OF_RANGE
*/
template<typename T>
ACTIV_BASE_API typename Boost::enable_if<Boost::is_same<String, T>, StatusCode>::type Get(const FieldId fieldId, String &fieldValue) const;
/**
* @brief Get a non-const defined field from the map.
*
* @param fieldId id of the field to get.
*
* @return non-const reference to the defined field.
*
* @throw Exception
*/
template <typename T>
typename Boost::enable_if<IsFieldType<T>, T>::type &Get(const FieldId fieldId);
/**
* @brief Get a const defined field from the map.
*
* @param fieldId id of the field to get.
*
* @return const reference to the defined field.
*
* @throw Exception
*/
template <typename T>
const typename Boost::enable_if<IsFieldType<T>, T>::type &Get(const FieldId fieldId) const;
/**
* @brief Get a field value from the map.
*
* @param fieldId id of the field to copy.
*
* @return field value of the defined field.
*
* @throw Exception
*/
template<typename T>
typename Boost::enable_if<Boost::is_integral<T>, T>::type Get(const FieldId fieldId) const;
/**
* @brief Get a field value from the map.
*
* @param fieldId id of the field to copy.
*
* @return field value of the defined field.
*
* @throw Exception
*/
template<typename T>
typename Boost::enable_if<Boost::is_floating_point<T>, T>::type Get(const FieldId fieldId) const;
/**
* @brief Get a field value from the map.
*
* @param fieldId id of the field to copy.
*
* @return field value of the defined field.
*
* @throw Exception
*/
template<typename T>
typename Boost::enable_if<Boost::is_same<String, T>, String>::type Get(const FieldId fieldId) const;
/**
* @brief Copy field defined by @a fieldId from @a fieldMap.
*
* @param fieldId id of the field to copy.
* @param fieldMap fieldMap to copy field from.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval ...
*/
ACTIV_BASE_API StatusCode CopyFrom(const FieldId fieldId, const FieldMap &fieldMap);
/**
* @brief Copy field defined by @a fromFieldId from @a fieldMap to @a toFieldId.
*
* @param fromFieldId id of the field to copy from.
* @param fieldMap fieldMap to copy field from.
* @param toFieldId id of the field to copy to.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval ...
*/
ACTIV_BASE_API StatusCode CopyFrom(const FieldId fromFieldId, const FieldMap &fieldMap, const FieldId toFieldId);
/**
* @brief Equality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*/
ACTIV_BASE_API bool operator==(const FieldMap &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*/
bool operator!=(const FieldMap &rhs) const;
/**
* @brief Assignment operator.
*
* @param rhs the value to assign to this object.
*
* @return a reference to this object.
*
* @throw Exception
* @throw std::exception
*/
ACTIV_BASE_API FieldMap &operator=(const FieldMap &rhs);
//! Get an iterator to the first field in the map.
ConstIterator begin() const;
//! Get an iterator that points to beyond the last field in the map.
ConstIterator end() const;
/**
* @brief Compare.
*
* @param rhs the object to compare with.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API StatusCode Compare(const FieldMap &rhs, int &result) const;
// IFieldType interface
virtual void Reset() ACTIV_OVERRIDE;
virtual void Clear() ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Compare(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Convert(const IFieldType * const pIFieldType) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode AppendAsString(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode FromString(MessageValidator &messageValidator) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String GetFromStringFormat() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetSerializedLength() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetSerializedBodyLength() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode IsDifferent(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, bool &isDifferent) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetMemoryUsage() const ACTIV_OVERRIDE;
/**
* @brief Validate the serialized length and body.
*
* @param messageValidator the message validator.
* @param serializedBodyOffset the serialized body offset.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode ValidateSerializedLengthAndBody(MessageValidator &messageValidator, size_t &serializedBodyOffset, size_t &serializedBodyLength);
/**
* @brief Is valid serialized body length.
*
* @param serializedBodyLength the serialized body length.
*
* @return whether the serialized body length is valid.
*/
static bool IsValidSerializedBodyLength(const size_t serializedBodyLength);
/**
* @brief Get a usage string for the format supported by FromString().
*
* @return String, may be empty.
*/
ACTIV_BASE_API static String FromStringFormat();
/**
* @brief Serialize the object's body into the supplied @a MessageBuilder.
*
* @param messageBuilder
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode SerializeBody(MessageBuilder &messageBuilder) const;
//! Maximum field id.
static const FieldId MAX_FIELD_ID = 0x3fff;
private:
/**
* @brief Internal deserialize body.
*
* @param messageValidator
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
StatusCode DeserializeBody(MessageValidator &messageValidator);
//! Mask defining the id bits of the FieldId type.
static const FieldId FIELD_ID_MASK = 0x3fff;
//! The undefined bit mask.
static const FieldId UNDEFINED_MASK = 0x8000;
Map m_map; ///< The underlying map.
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline FieldMap::FieldMap() :
IFieldType(FIELD_TYPE_FIELD_MAP)
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if_c<Boost::is_integral<T>::value && !Boost::is_same<bool, T>::value, void>::type
FieldMap::Set(const FieldId fieldId, const T fieldValue)
{
if (ACTIV_UNLIKELY(fieldValue < 0))
ACTIV_THROW(StatusCodeException, STATUS_CODE_OUT_OF_RANGE);
Set(fieldId, UInt(static_cast<uint64_t>(fieldValue)));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_floating_point<T>, void>::type
FieldMap::Set(const FieldId fieldId, const T fieldValue)
{
Set(fieldId, Double(fieldValue));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_same<bool, T>, void>::type
FieldMap::Set(const FieldId fieldId, const T fieldValue)
{
Set(fieldId, Boolean(fieldValue));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_same<String, T>, void>::type
FieldMap::Set(const FieldId fieldId, const T &fieldValue)
{
Set(fieldId, TextString(fieldValue));
}
// ---------------------------------------------------------------------------------------------------------------------------------
#if (!defined ACTIV_BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
template<typename T>
inline void FieldMap::Set(const FieldId fieldId, std::initializer_list<T> fieldValue)
{
Set(fieldId, FieldTypeList(fieldValue));
}
#endif
// ---------------------------------------------------------------------------------------------------------------------------------
inline void FieldMap::Set(const FieldId fieldId, const char *fieldValue)
{
Set(fieldId, TextString(fieldValue));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T>
inline typename Boost::enable_if<IsFieldType<T>, StatusCode>::type FieldMap::Get(const FieldId fieldId, T *&pFieldType)
{
IFieldType *pIFieldType;
ACTIV_RETURN_RESULT_IF(STATUS_CODE_SUCCESS, !=, Get(fieldId, pIFieldType));
if (ACTIV_UNLIKELY(T::FIELD_TYPE != pIFieldType->GetType()))
return STATUS_CODE_INVALID_FIELD_TYPE;
pFieldType = static_cast<T *>(pIFieldType);
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T>
inline typename Boost::enable_if<IsFieldType<T>, StatusCode>::type FieldMap::Get(const FieldId fieldId, const T *&pFieldType) const
{
const IFieldType *pIFieldType;
ACTIV_RETURN_RESULT_IF(STATUS_CODE_SUCCESS, !=, Get(fieldId, pIFieldType));
if (ACTIV_UNLIKELY(T::FIELD_TYPE != pIFieldType->GetType()))
return STATUS_CODE_INVALID_FIELD_TYPE;
pFieldType = static_cast<const T *>(pIFieldType);
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T>
inline typename Boost::enable_if<IsFieldType<T>, T>::type &FieldMap::Get(const FieldId fieldId)
{
T *pFieldValue;
ACTIV_THROW_RESULT_WITH_MESSAGE_IF(STATUS_CODE_SUCCESS, !=, Get<T>(fieldId, pFieldValue), ("field " + TypeToString(fieldId)));
return *pFieldValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T>
inline const typename Boost::enable_if<IsFieldType<T>, T>::type &FieldMap::Get(const FieldId fieldId) const
{
const T *pFieldValue;
ACTIV_THROW_RESULT_WITH_MESSAGE_IF(STATUS_CODE_SUCCESS, !=, Get(fieldId, pFieldValue), ("field " + TypeToString(fieldId)));
return *pFieldValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_integral<T>, T>::type FieldMap::Get(const FieldId fieldId) const
{
T fieldValue;
ACTIV_THROW_RESULT_WITH_MESSAGE_IF(STATUS_CODE_SUCCESS, !=, Get<T>(fieldId, fieldValue), ("field " + TypeToString(fieldId)));
return fieldValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_floating_point<T>, T>::type FieldMap::Get(const FieldId fieldId) const
{
T fieldValue;
ACTIV_THROW_RESULT_WITH_MESSAGE_IF(STATUS_CODE_SUCCESS, !=, Get<T>(fieldId, fieldValue), ("field " + TypeToString(fieldId)));
return fieldValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_same<String, T>, String>::type FieldMap::Get(const FieldId fieldId) const
{
T fieldValue;
ACTIV_THROW_RESULT_WITH_MESSAGE_IF(STATUS_CODE_SUCCESS, !=, this->Get<String>(fieldId, fieldValue),
("field " + TypeToString(fieldId)));
return fieldValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool FieldMap::operator!=(const FieldMap &rhs) const
{
return !(*this == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline FieldMap::ConstIterator FieldMap::begin() const
{
return m_map.begin();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline FieldMap::ConstIterator FieldMap::end() const
{
return m_map.end();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void FieldMap::Reset()
{
m_map.clear();
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void FieldMap::Clear()
{
FieldMap::Reset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool FieldMap::IsValidSerializedBodyLength(const size_t serializedBodyLength)
{
return (serializedBodyLength <= Boost::integer_traits<uint32_t>::const_max);
}
} // namespace Activ
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
namespace ACTIV_BOOST_NAMESPACE
{
// For BOOST_FOREACH support, mainly.
template<>
struct range_const_iterator<Activ::FieldMap>
{
typedef Activ::FieldMap::ConstIterator type;
};
template<>
struct range_mutable_iterator<Activ::FieldMap>
{
// There is no mutable iterator; use const.
typedef Activ::FieldMap::ConstIterator type;
};
namespace iterators
{
template<>
struct iterator_reference<Activ::FieldMap>
{
typedef const Activ::FieldMap::ValueType &type;
};
} // namespace iterators
} // namespace ACTIV_BOOST_NAMESPACE
#endif // (!defined ACTIV_BASE_FIELD_TYPES_FIELD_MAP_H)
@@ -1,121 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/FieldTypeFactory.h
*
* @brief Header file for the field type factory class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_FIELD_TYPE_FACTORY_H)
#define ACTIV_BASE_FIELD_TYPES_FIELD_TYPE_FACTORY_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/ActivBase/FieldTypes/IFieldType.h"
#include "ActivMiddleware/CxxYZ/memory.h"
#include "ActivMiddleware/Misc/Singleton.h"
//! Activ namespace.
namespace Activ
{
//! Field type factory class.
class FieldTypeFactory : public Singleton<FieldTypeFactory>
{
public:
/**
* @brief Create a field type object.
*
* @param type the field type.
*
* @return A unique_ptr to the object.
*/
CxxYZ::unique_ptr<IFieldType> Create(const FieldType type) const;
/**
* @brief Create a field type object and populate its value from a string using IFieldType::FromString().
*
* @param type the field type.
* @param string
*
* @return A unique_ptr to the object.
*/
CxxYZ::unique_ptr<IFieldType> CreateFromString(const FieldType type, const String &string) const;
/**
* @brief Clone an existing field type object.
*
* @param iFieldType the object to clone.
*
* @return A unique_ptr to the cloned object.
*/
CxxYZ::unique_ptr<IFieldType> Clone(const IFieldType &iFieldType) const;
/**
* @brief Create a field type object of a particular type and attempt populate its value from another IFieldType using
* IFieldType::Convert().
*
* @param type the field type to create.
* @param iFieldType the object to clone.
*
* @return A unique_ptr to the object.
*/
CxxYZ::unique_ptr<IFieldType> Convert(const FieldType type, const IFieldType &iFieldType) const;
//! Get a reference to the singleton instance.
ACTIV_BASE_API static FieldTypeFactory &GetInstance();
private:
//! Default constructor.
ACTIV_BASE_API FieldTypeFactory();
ACTIV_BASE_API IFieldType *InternalCreate(const FieldType fieldType) const;
ACTIV_BASE_API IFieldType *InternalClone(const IFieldType &iFieldType) const;
friend class Singleton<FieldTypeFactory>;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline CxxYZ::unique_ptr<IFieldType> FieldTypeFactory::Create(const FieldType type) const
{
CxxYZ::unique_ptr<IFieldType> pFieldType(InternalCreate(type));
return ACTIV_MOVE_RETURN(CxxYZ::unique_ptr<IFieldType>, pFieldType);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline CxxYZ::unique_ptr<IFieldType> FieldTypeFactory::CreateFromString(const FieldType type, const String &string) const
{
CxxYZ::unique_ptr<IFieldType> pFieldType(Create(type));
if (pFieldType)
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, pFieldType->FromString(string));
return ACTIV_MOVE_RETURN(CxxYZ::unique_ptr<IFieldType>, pFieldType);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline CxxYZ::unique_ptr<IFieldType> FieldTypeFactory::Clone(const IFieldType &iFieldType) const
{
CxxYZ::unique_ptr<IFieldType> pFieldType(InternalClone(iFieldType));
return ACTIV_MOVE_RETURN(CxxYZ::unique_ptr<IFieldType>, pFieldType);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline CxxYZ::unique_ptr<IFieldType> FieldTypeFactory::Convert(const FieldType type, const IFieldType &iFieldType) const
{
CxxYZ::unique_ptr<IFieldType> pFieldType(Create(type));
if (pFieldType && (STATUS_CODE_SUCCESS != pFieldType->Convert(&iFieldType)))
pFieldType.reset();
return ACTIV_MOVE_RETURN(CxxYZ::unique_ptr<IFieldType>, pFieldType);
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_FIELD_TYPE_FACTORY_H)
@@ -1,716 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/FieldTypeList.h
*
* @brief Header file for the FieldTypeList class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_FIELD_LIST_H)
#define ACTIV_BASE_FIELD_TYPES_FIELD_LIST_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/IFieldType.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Boolean.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Double.h"
#include "ActivMiddleware/ActivBase/FieldTypes/TextString.h"
#include "ActivMiddleware/ActivBase/FieldTypes/UInt.h"
#include "ActivMiddleware/CxxYZ/vector.h"
#include "ActivMiddleware/CxxYZ/memory.h"
#include ACTIV_BOOST_INCLUDE(range/const_iterator.hpp)
#include ACTIV_BOOST_INCLUDE(range/iterator.hpp)
//! Activ namespace.
namespace Activ
{
//! Field type list class.
class FieldTypeList : public IFieldType
{
public:
static const FieldType FIELD_TYPE = FIELD_TYPE_FIELD_TYPE_LIST; ///< The field type.
//! The underlying list type.
typedef CxxYZ::vector<CxxYZ::unique_ptr<IFieldType> > List;
//! The const iterator type.
typedef List::const_iterator ConstIterator;
//! The value type type.
typedef List::value_type ValueType;
using IFieldType::FromString;
using IFieldType::Serialize;
using IFieldType::SerializeBody;
using IFieldType::SerializeLengthAndBody;
using IFieldType::Deserialize;
using IFieldType::DeserializeBody;
using IFieldType::DeserializeLengthAndBody;
//! Default constructor.
FieldTypeList(const size_t initialCapacity = 0);
/**
* @brief Copy constructor.
*
* @param rhs the value to assign to this object.
*/
ACTIV_BASE_API FieldTypeList(const FieldTypeList &rhs);
#if (!defined ACTIV_BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
/**
* @brief Constructor from an initializer list.
*
* @param list the values to put into this object.
*/
template<typename T>
FieldTypeList(std::initializer_list<T> list);
#endif
/**
* @brief Push a field to an initialized value at the end of the list. It can invalidate iterators.
*
* If @a value is not initialized an exception is thrown.
*
* @param value the new value to set.
*
* @throw Exception
*/
ACTIV_BASE_API void PushBack(const IFieldType &value);
/**
* @brief Push a field to an initialized value at the end of the list. It can invalidate iterators.
*
* If @a value is not initialized an exception is thrown.
*
* @param value the new value to set.
*
* @throw Exception
*/
template<typename T>
typename Boost::enable_if_c<Boost::is_integral<T>::value && !Boost::is_same<bool, T>::value, void>::type
PushBack(const T value);
/**
* @brief Push a field to an initialized value at the end of the list. It can invalidate iterators.
*
* If @a value is not initialized an exception is thrown.
*
* @param value the new value to set.
*
* @throw Exception
*/
template<typename T>
typename Boost::enable_if<Boost::is_same<bool, T>, void>::type PushBack(const T value);
/**
* @brief Push a field to an initialized value at the end of the list. It can invalidate iterators.
*
* If @a value is not initialized an exception is thrown.
*
* @param value the new value to set.
*
* @throw Exception
*/
template<typename T>
typename Boost::enable_if<Boost::is_floating_point<T>, void>::type PushBack(const T value);
/**
* @brief Push a field to an initialized value at the end of the list. It can invalidate iterators.
*
* If @a value is not initialized an exception is thrown.
*
* @param value the new value to set.
*
* @throw Exception
*/
template<typename T>
typename Boost::enable_if<Boost::is_same<String, T>, void>::type PushBack(const T value);
/**
* @brief Push a field to an initialized value at the end of the list. It can invalidate iterators.
*
* If @a value is not initialized an exception is thrown.
*
* @param value the new value to set.
*
* @throw Exception
*/
void PushBack(const char *value);
/**
* @brief Set a value at position to be undefined.
*
* If the field doesn't exists, exception is thrown.
*
* @param position the position of the value.
*
* @throw Exception
*/
ACTIV_BASE_API void SetUndefined(const size_t position);
/**
* @brief Remove a value at position from the list. It will invalidate iterators.
*
* @param position the position to remove.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_OUT_OF_RANGE
*/
ACTIV_BASE_API StatusCode Erase(const size_t position);
/**
* @brief Get a field from the list.
*
* A pointer is passed back to the field value in the list. Uninitialized field values should not be present in the list.
* The field value must not be cleared and assigned to an uninitialized value.
*
* @param position the position of the field to get.
* @param pFieldType reference to IFieldType pointer to receive the field value.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_OUT_OF_RANGE
* @retval STATUS_CODE_UNDEFINED_FIELD
*/
ACTIV_BASE_API StatusCode Get(const size_t position, IFieldType *&pFieldType);
/**
* @brief Get a const field from the list.
*
* @param position the position of the field to get.
* @param pFieldType reference to IFieldType pointer to receive the field value.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_UNDEFINED_FIELD
*/
ACTIV_BASE_API StatusCode Get(const size_t position, const IFieldType *&pFieldType) const;
/**
* @brief Get a field from the list.
*
* @param position the field position to get.
* @param pFieldType reference to IFieldType pointer to receive the field value.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
*/
template <typename T>
typename Boost::enable_if<IsFieldType<T>, StatusCode>::type Get(const size_t position, T *&pFieldType);
/**
* @brief Get a const field from the list.
*
* @param position the field position to get.
* @param pFieldType reference to IFieldType pointer to receive the field value.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
*/
template <typename T>
typename Boost::enable_if<IsFieldType<T>, StatusCode>::type Get(const size_t position, const T *&pFieldType) const;
/**
* @brief Get a field from the list.
*
* @param position the field position to get.
* @param value reference where the value will be returned.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
* @retval STATUS_CODE_OUT_OF_RANGE
*/
template<typename T>
ACTIV_BASE_API typename Boost::enable_if<Boost::is_signed<T>, StatusCode>::type Get(const size_t position, T &value) const;
/**
* @brief Get a field from the list.
*
* @param position the field position to get.
* @param value reference where the value will be returned.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
* @retval STATUS_CODE_OUT_OF_RANGE
*/
template<typename T>
ACTIV_BASE_API typename Boost::enable_if_c<Boost::is_unsigned<T>::value && !Boost::is_same<bool, T>::value, StatusCode>::type
Get(const size_t position, T &value) const;
/**
* @brief Get a field from the list.
*
* @param position the field position to get.
* @param value reference where the value will be returned.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
* @retval STATUS_CODE_OUT_OF_RANGE
*/
template<typename T>
ACTIV_BASE_API typename Boost::enable_if<Boost::is_floating_point<T>, StatusCode>::type Get(const size_t position, T &value) const;
/**
* @brief Get a field from the list.
*
* @param position the field position to get.
* @param value reference where the value will be returned.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
* @retval STATUS_CODE_OUT_OF_RANGE
*/
template<typename T>
ACTIV_BASE_API typename Boost::enable_if<Boost::is_same<bool, T>, StatusCode>::type Get(const size_t position, T &value) const;
/**
* @brief Get a field from the list.
*
* @param position the field position to get.
* @param value reference where the value will be returned.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_UNDEFINED_FIELD
* @retval STATUS_CODE_OUT_OF_RANGE
*/
template<typename T>
ACTIV_BASE_API typename Boost::enable_if<Boost::is_same<String, T>, StatusCode>::type Get(const size_t position, T &value) const;
/**
* @brief Get a non-const defined field from the list.
*
* @param position the field position to get.
*
* @return non-const reference to the defined field.
*
* @throw Exception
*/
template <typename T>
typename Boost::enable_if<IsFieldType<T>, T>::type &Get(const size_t position);
/**
* @brief Get a const defined field from the list.
*
* @param position the field position to get.
*
* @return const reference to the defined field.
*
* @throw Exception
*/
template <typename T>
const typename Boost::enable_if<IsFieldType<T>, T>::type &Get(const size_t position) const;
/**
* @brief Get a const defined field from the list.
*
* @param position the field position to get.
*
* @return value of the defined field.
*
* @throw Exception
*/
template<typename T>
typename Boost::enable_if<Boost::is_integral<T>, T>::type Get(const size_t position) const;
/**
* @brief Get a const defined field from the list.
*
* @param position the field position to get.
*
* @return value of the defined field.
*
* @throw Exception
*/
template<typename T>
typename Boost::enable_if<Boost::is_floating_point<T>, T>::type Get(const size_t position) const;
/**
* @brief Get a const defined field from the list.
*
* @param position the field position to get.
*
* @return value of the defined field.
*
* @throw Exception
*/
template<typename T>
typename Boost::enable_if<Boost::is_same<String, T>, String>::type Get(const size_t position) const;
/**
* @brief Return size of the list. 0 if not initialized.
*/
size_t Size() const;
/**
* @brief Add new field from @a position @a fieldTypeList.
*
* @param position the position of the field to copy from.
* @param fieldTypeList the field type list to copy new field from.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_OUT_OF_RANGE
* @retval STATUS_CODE_UNDEFINED_FIELD
* @retval ...
*
* @throw Exception
*/
ACTIV_BASE_API StatusCode CopyFrom(const size_t position, const FieldTypeList &fieldTypeList);
/**
* @brief Equality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*/
ACTIV_BASE_API bool operator==(const FieldTypeList &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*/
bool operator!=(const FieldTypeList &rhs) const;
/**
* @brief Assignment operator.
*
* @param rhs the value to assign to this object.
*
* @return a reference to this object.
*/
ACTIV_BASE_API FieldTypeList &operator=(const FieldTypeList &rhs);
//! Get an iterator to the first field in the list.
ConstIterator begin() const;
//! Get an iterator that points to beyond the last field in the list.
ConstIterator end() const;
/**
* @brief Compare.
*
* @param rhs the object to compare with.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API StatusCode Compare(const FieldTypeList &rhs, int &result) const;
// IFieldType interface
virtual void Reset() ACTIV_OVERRIDE;
virtual void Clear() ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Compare(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Convert(const IFieldType * const pIFieldType) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode AppendAsString(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode FromString(MessageValidator &messageValidator) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String GetFromStringFormat() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetSerializedLength() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetSerializedBodyLength() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode IsDifferent(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, bool &isDifferent) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetMemoryUsage() const ACTIV_OVERRIDE;
/**
* @brief Validate the serialized length and body.
*
* @param messageValidator the message validator.
* @param serializedBodyOffset the serialized body offset.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode ValidateSerializedLengthAndBody(MessageValidator &messageValidator, size_t &serializedBodyOffset, size_t &serializedBodyLength);
/**
* @brief Is valid serialized body length.
*
* @param serializedBodyLength the serialized body length.
*
* @return whether the serialized body length is valid.
*/
static bool IsValidSerializedBodyLength(const size_t serializedBodyLength);
/**
* @brief Get a usage string for the format supported by FromString().
*
* @return String, may be empty.
*/
ACTIV_BASE_API static String FromStringFormat();
private:
/**
* @brief Internal serialize body.
*
* @param messageBuilder
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
StatusCode SerializeBody(MessageBuilder &messageBuilder) const;
/**
* @brief Internal deserialize body.
*
* @param messageValidator
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
StatusCode DeserializeBody(MessageValidator &messageValidator);
List m_list; ///< The underlying list.
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline FieldTypeList::FieldTypeList(const size_t initialCapacity) :
IFieldType(FIELD_TYPE_FIELD_TYPE_LIST)
{
m_isInitialized = false;
m_list.reserve(initialCapacity);
}
// ---------------------------------------------------------------------------------------------------------------------------------
#if (!defined ACTIV_BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
template<typename T>
inline FieldTypeList::FieldTypeList(std::initializer_list<T> list) :
FieldTypeList(list.size())
{
ACTIV_FOREACH(const T&item, list)
PushBack(item);
}
#endif
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if_c<Boost::is_integral<T>::value && !Boost::is_same<bool, T>::value, void>::type
FieldTypeList::PushBack(const T value)
{
if (ACTIV_UNLIKELY(value < 0))
ACTIV_THROW(StatusCodeException, STATUS_CODE_OUT_OF_RANGE);
PushBack(UInt(static_cast<uint64_t>(value)));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_same<bool, T>, void>::type
FieldTypeList::PushBack(const T value)
{
PushBack(Boolean(value));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_floating_point<T>, void>::type
FieldTypeList::PushBack(const T value)
{
PushBack(Double(value));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_same<String, T>, void>::type
FieldTypeList::PushBack(const T value)
{
PushBack(TextString(value));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void FieldTypeList::PushBack(const char *value)
{
PushBack(TextString(value));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T>
inline typename Boost::enable_if<IsFieldType<T>, StatusCode>::type FieldTypeList::Get(const size_t position, T *&pFieldType)
{
IFieldType *pIFieldType;
ACTIV_RETURN_RESULT_IF(STATUS_CODE_SUCCESS, !=, Get(position, pIFieldType));
if (ACTIV_UNLIKELY(T::FIELD_TYPE != pIFieldType->GetType()))
return STATUS_CODE_INVALID_FIELD_TYPE;
pFieldType = static_cast<T *>(pIFieldType);
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T>
inline typename Boost::enable_if<IsFieldType<T>, StatusCode>::type
FieldTypeList::Get(const size_t position, const T *&pFieldType) const
{
const IFieldType *pIFieldType;
ACTIV_RETURN_RESULT_IF(STATUS_CODE_SUCCESS, !=, Get(position, pIFieldType));
if (ACTIV_UNLIKELY(T::FIELD_TYPE != pIFieldType->GetType()))
return STATUS_CODE_INVALID_FIELD_TYPE;
pFieldType = static_cast<const T *>(pIFieldType);
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T>
inline typename Boost::enable_if<IsFieldType<T>, T>::type &FieldTypeList::Get(const size_t position)
{
T *pFieldValue;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Get<T>(position, pFieldValue));
return *pFieldValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T>
inline const typename Boost::enable_if<IsFieldType<T>, T>::type &FieldTypeList::Get(const size_t position) const
{
const T *pFieldValue;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, != , Get(position, pFieldValue));
return *pFieldValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_integral<T>, T>::type FieldTypeList::Get(const size_t position) const
{
T fieldValue;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, != , Get<T>(position, fieldValue));
return fieldValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_floating_point<T>, T>::type FieldTypeList::Get(const size_t position) const
{
T fieldValue;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, != , Get<T>(position, fieldValue));
return fieldValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_same<String, T>, String>::type FieldTypeList::Get(const size_t position) const
{
T fieldValue;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, != , this->Get<String>(position, fieldValue));
return fieldValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t FieldTypeList::Size() const
{
return m_list.size();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool FieldTypeList::operator!=(const FieldTypeList &rhs) const
{
return !(*this == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline FieldTypeList::ConstIterator FieldTypeList::begin() const
{
return m_list.begin();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline FieldTypeList::ConstIterator FieldTypeList::end() const
{
return m_list.end();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void FieldTypeList::Reset()
{
m_list.clear();
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void FieldTypeList::Clear()
{
FieldTypeList::Reset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool FieldTypeList::IsValidSerializedBodyLength(const size_t serializedBodyLength)
{
return (serializedBodyLength <= Boost::integer_traits<uint32_t>::const_max);
}
} // namespace Activ
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
namespace ACTIV_BOOST_NAMESPACE
{
// For BOOST_FOREACH support, mainly.
template<>
struct range_const_iterator<Activ::FieldTypeList>
{
typedef Activ::FieldTypeList::ConstIterator type;
};
template<>
struct range_mutable_iterator<Activ::FieldTypeList>
{
// There is no mutable iterator; use const.
typedef Activ::FieldTypeList::ConstIterator type;
};
namespace iterators
{
template<>
struct iterator_reference<Activ::FieldTypeList>
{
typedef const Activ::FieldTypeList::ValueType &type;
};
} // namespace iterators
} // namespace ACTIV_BOOST_NAMESPACE
#endif // (!defined ACTIV_BASE_FIELD_TYPES_FIELD_LIST_H)
@@ -1,162 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/FieldTypeSerializationHelper.h
*
* @brief Header file for the field type serialization helper class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_FIELD_TYPE_SERIALIZATION_HELPER_H)
#define ACTIV_BASE_FIELD_TYPES_FIELD_TYPE_SERIALIZATION_HELPER_H
#include "ActivMiddleware/ActivBase/FieldTypes/ActivFieldTypes.h"
#include "ActivMiddleware/ActivBase/MessageBuilder.h"
#include "ActivMiddleware/ActivBase/MessageValidator.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Field type serialization helper class.
*
* @param FIELD_TYPE field type to serialize.
*/
class FieldTypeSerializationHelper
{
public:
/**
* @brief Serialize the object's initialization status and (if initialized) body into the supplied message builder.
*
* @param fieldType the field type.
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
template <typename FIELD_TYPE>
static StatusCode SerializeStatusAndBody(const FIELD_TYPE &fieldType, MessageBuilder &messageBuilder,
const size_t maxSerializedBodyLength = IFieldType::MAX_SERIALIZED_BODY_LENGTH_UNDEFINED);
/**
* @brief Serialize the object's initialization status and (if initialized) length and body into the supplied message builder.
*
* @param fieldType the field type.
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
template <typename FIELD_TYPE>
static StatusCode SerializeStatusLengthAndBody(const FIELD_TYPE &fieldType, MessageBuilder &messageBuilder,
const size_t maxSerializedBodyLength = IFieldType::MAX_SERIALIZED_BODY_LENGTH_UNDEFINED);
/**
* @brief Deserialize the object's initialization status and (if initialized) body from the supplied message validator.
*
* @param fieldType the field type.
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
template <typename FIELD_TYPE>
static StatusCode DeserializeStatusAndBody(FIELD_TYPE &fieldType, MessageValidator &messageValidator,
const size_t maxSerializedBodyLength = IFieldType::MAX_SERIALIZED_BODY_LENGTH_UNDEFINED);
/**
* @brief Deserialize the object's initialization status and (if initialized) length and body from the
* supplied message validator.
*
* @param fieldType the field type.
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
template <typename FIELD_TYPE>
static StatusCode DeserializeStatusLengthAndBody(FIELD_TYPE &fieldType, MessageValidator &messageValidator,
const size_t maxSerializedBodyLength = IFieldType::MAX_SERIALIZED_BODY_LENGTH_UNDEFINED);
};
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename FIELD_TYPE>
inline StatusCode FieldTypeSerializationHelper::SerializeStatusAndBody(const FIELD_TYPE &fieldType, MessageBuilder &messageBuilder,
const size_t maxSerializedBodyLength)
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, != , messageBuilder.AppendBoolean(fieldType.IsInitialized()));
if (fieldType.IsInitialized())
{
return fieldType.Serialize(messageBuilder, maxSerializedBodyLength);
}
else
{
return STATUS_CODE_SUCCESS;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename FIELD_TYPE>
inline StatusCode FieldTypeSerializationHelper::SerializeStatusLengthAndBody(const FIELD_TYPE &fieldType,
MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength)
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, != , messageBuilder.AppendBoolean(fieldType.IsInitialized()));
if (fieldType.IsInitialized())
{
return fieldType.SerializeLengthAndBody(messageBuilder, maxSerializedBodyLength);
}
else
{
return STATUS_CODE_SUCCESS;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename FIELD_TYPE>
inline StatusCode FieldTypeSerializationHelper::DeserializeStatusAndBody(FIELD_TYPE &fieldType,
MessageValidator &messageValidator, const size_t maxSerializedBodyLength)
{
bool isInitialized;
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, messageValidator.ValidateBoolean(isInitialized));
if (isInitialized)
{
return fieldType.Deserialize(messageValidator, maxSerializedBodyLength);
}
else
{
fieldType.Reset();
return STATUS_CODE_SUCCESS;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename FIELD_TYPE>
inline StatusCode FieldTypeSerializationHelper::DeserializeStatusLengthAndBody(FIELD_TYPE &fieldType,
MessageValidator &messageValidator, const size_t maxSerializedBodyLength)
{
bool isInitialized;
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, messageValidator.ValidateBoolean(isInitialized));
if (isInitialized)
{
return fieldType.DeserializeLengthAndBody(messageValidator, maxSerializedBodyLength);
}
else
{
fieldType.Reset();
return STATUS_CODE_SUCCESS;
}
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_FIELD_TYPE_SERIALIZATION_HELPER_H)
@@ -1,485 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/IFieldType.h
*
* @brief Header file for the field type interface class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_IFIELD_TYPE_H)
#define ACTIV_BASE_FIELD_TYPES_IFIELD_TYPE_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/ActivFieldTypes.h"
#include "ActivMiddleware/ActivBase/MessageBuilder.h"
#include "ActivMiddleware/ActivBase/MessageValidator.h"
//! Activ namespace.
namespace Activ
{
//! Field type interface class.
class IFieldType
{
public:
static const size_t MAX_SERIALIZED_BODY_LENGTH_UNDEFINED = static_cast<const size_t>(~0); ///< The undefined max serialized body length.
//! Destructor.
virtual ~IFieldType() = 0;
/**
* @brief Reset the object.
*
* Sets the field to uninitialized, but does not deallocate any underlying storage that has been allocated.
*/
virtual void Reset() = 0;
/**
* @brief Clear the object.
*
* Deallocates any underlying storage that has been allocated for the field type and sets the field to uninitialized.
*/
virtual void Clear() = 0;
/**
* @brief Compare.
*
* @param pRhsSerializedBody the buffer containing the rhs serialized version of the object's body in.
* @param rhsSerializedBodyLength the rhs serialized body length.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
virtual StatusCode Compare(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result) const = 0;
/**
* @brief Assign the value of this from another IFieldType object.
*
* @param pIFieldType the value to assign from.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_MISMATCH
* @retval ...
*/
ACTIV_BASE_API StatusCode Assign(const IFieldType * const pIFieldType);
/**
* @brief Convert another IFieldType object to this type.
*
* @param pIFieldType the value to assign from.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_MISMATCH
* @retval ...
*/
virtual StatusCode Convert(const IFieldType * const pIFieldType) = 0;
//! Get the field type.
FieldType GetType() const;
/**
* @brief Convert the object to a string.
*
* @return the object as a string.
*/
virtual String ToString() const = 0;
/**
* @brief Append the object to a message builder as a string.
*
* @param messageBuilder the message builder.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_FIELD_TYPE
* @retval STATUS_CODE_INVALID_LENGTH
* @retval ...
*/
virtual StatusCode AppendAsString(MessageBuilder &messageBuilder) const = 0;
/**
* @brief Convert the object from a string.
*
* @param messageValidator the message validator.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_FIELD_TYPE
* @retval STATUS_CODE_INVALID_LENGTH
* @retval ...
*/
virtual StatusCode FromString(MessageValidator &messageValidator) = 0;
/**
* @brief Convert the object from a string.
*
* @param field the field as a string.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
StatusCode FromString(const String &field);
/**
* @brief Get a usage string for the format supported by FromString().
*
* @return String, may be empty.
*/
virtual String GetFromStringFormat() const = 0;
/**
* @brief Serialize the object into the supplied message builder.
*
* @param fieldType the field type.
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode Serialize(const FieldType fieldType, MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength) const;
/**
* @brief Serialize the object into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
virtual StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength) const = 0;
/**
* @brief Serialize the object's body into the supplied data buffer.
*
* @param fieldType the field type.
* @param pSerializedBody the buffer to store a serialized version of the object's body in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode SerializeBody(const FieldType fieldType, void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength) const;
/**
* @brief Serialize the object's body into the supplied data buffer.
*
* @param pSerializedBody the buffer to store a serialized version of the object's body in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
virtual StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength) const = 0;
/**
* @brief Serialize the object's length and body into the supplied message builder.
*
* @param fieldType the field type.
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode SerializeLengthAndBody(const FieldType fieldType, MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) const;
/**
* @brief Serialize the object's length and body into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
virtual StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) const = 0;
/**
* @brief Deserialize the object from the supplied message validator.
*
* @param fieldType the field type.
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode Deserialize(const FieldType fieldType, MessageValidator &messageValidator, const size_t maxSerializedBodyLength);
/**
* @brief Deserialize the object from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
virtual StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength) = 0;
/**
* @brief Deserialize the object's body from the supplied data buffer.
*
* @param fieldType the field type.
* @param pSerializedBody the buffer from which the object's body will be extracted.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode DeserializeBody(const FieldType fieldType, const void * const pSerializedBody, const size_t serializedBodyLength);
/**
* @brief Deserialize the object's body from the supplied data buffer.
*
* @param pSerializedBody the buffer from which the object's body will be extracted.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
virtual StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength) = 0;
/**
* @brief Deserialize the object's length and body from the supplied message validator.
*
* @param fieldType the field type.
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode DeserializeLengthAndBody(const FieldType fieldType, MessageValidator &messageValidator, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED);
/**
* @brief Deserialize the object's length and body from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
virtual StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) = 0;
/**
* @brief Get the serialized length of the object.
*
* @return the serialized length of the object.
*/
virtual size_t GetSerializedLength() const = 0;
/**
* @brief Get the serialized length of the object's body.
*
* @return the serialized length of the object's body.
*/
virtual size_t GetSerializedBodyLength() const = 0;
//! Is the object initialized.
bool IsInitialized() const;
/**
* @brief Is different.
*
* @param pRhsSerializedBody the buffer containing the rhs serialized version of the object's body in.
* @param rhsSerializedBodyLength the rhs serialized body length.
* @param isDifferent indicates whether the two objects are different.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
virtual StatusCode IsDifferent(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, bool &isDifferent) const = 0;
//! Get the approximate amount of memory used by the object.
virtual size_t GetMemoryUsage() const = 0;
/**
* @brief Serialize the object into the supplied message builder.
*
* @param fieldType the field type.
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval STATUS_CODE_NOT_SUPPORTED
* @retval ...
*/
ACTIV_BASE_API static StatusCode Serialize(const FieldType fieldType, MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Serialize the object's body into the supplied data buffer.
*
* @param fieldType the field type.
* @param pSerializedBody the buffer to store a serialized version of the object's body in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param serializedBodyLength the serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval STATUS_CODE_NOT_SUPPORTED
* @retval ...
*/
ACTIV_BASE_API static StatusCode SerializeBody(const FieldType fieldType, void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Serialize the object's length and body into the supplied message builder.
*
* @param fieldType the field type.
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval STATUS_CODE_NOT_SUPPORTED
* @retval ...
*/
ACTIV_BASE_API static StatusCode SerializeLengthAndBody(const FieldType fieldType, MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Validate the serialized length and body.
*
* @param fieldType the field type.
* @param messageValidator the message validator.
* @param serializedBodyOffset the serialized body offset.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode ValidateSerializedLengthAndBody(const FieldType fieldType, MessageValidator &messageValidator, size_t &serializedBodyOffset, size_t &serializedBodyLength);
/**
* @brief Is valid serialized body length.
*
* @param fieldType the field type.
* @param serializedBodyLength the serialized body length.
*
* @return whether the serialized body length is valid.
*/
ACTIV_BASE_API static bool IsValidSerializedBodyLength(const FieldType fieldType, const size_t serializedBodyLength);
/**
* @brief Compare field type objects of the same type.
*
* @param lhs
* @param rhs
* @param result the result of the comparison.
*
* @return STATUS_CODE_SUCCESS
* @return STATUS_CODE_MISMATCH
* @return ...
*/
ACTIV_BASE_API static StatusCode Compare(const IFieldType &lhs, const IFieldType &rhs, int &result);
protected:
/**
* @brief Constructor.
*
* @param fieldType the field type.
*/
explicit IFieldType(const FieldType fieldType);
/**
* Copy constructor.
*
* @param fieldType
*/
explicit IFieldType(const IFieldType &fieldType);
/**
* @brief Assignment operator.
*
* @param rhs the value to assign to this object.
*
* @return a reference to this object.
*/
IFieldType &operator=(const IFieldType &rhs);
//! Get the value used for uninitialized field types.
static const char * GetNotInitializedString();
bool m_isInitialized; ///< Indicates whether the object is initialized.
private:
FieldType m_fieldType; ///< The field type.
#if (defined ACTIV_PLATFORM_WASM)
friend class Wasm::FieldTypeAccessor;
#endif
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline IFieldType::~IFieldType()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline FieldType IFieldType::GetType() const
{
return m_fieldType;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode IFieldType::FromString(const String &field)
{
MessageValidator messageValidator(field.c_str(), field.length());
return FromString(messageValidator);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool IFieldType::IsInitialized() const
{
return m_isInitialized;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline IFieldType::IFieldType(const FieldType fieldType) :
m_fieldType(fieldType)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline IFieldType::IFieldType(const IFieldType &fieldType) :
m_isInitialized(fieldType.m_isInitialized),
m_fieldType(fieldType.m_fieldType)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline IFieldType &IFieldType::operator=(const IFieldType &rhs)
{
assert(m_fieldType == rhs.m_fieldType);
m_isInitialized = rhs.m_isInitialized;
return *this;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const char * IFieldType::GetNotInitializedString()
{
return "[NotInitialized]";
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_IFIELD_TYPE_H)
@@ -1,645 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/JsonFieldTypeTranslation.h
*
* @brief JSON support for FieldTypes.
*/
#if (!defined ACTIV_MIDDLEWARE_ACTIV_BASE_FIELD_TYPES_JSON_FIELD_TYPE_TRANSLATION_H)
#define ACTIV_MIDDLEWARE_ACTIV_BASE_FIELD_TYPES_JSON_FIELD_TYPE_TRANSLATION_H
#include "ActivMiddleware/ActivBase/FieldTypes/All.h"
#include "ActivMiddleware/CxxYZ/type_traits.h"
#include "ActivMiddleware/Misc/RapidJsonHelper.h"
namespace Activ
{
namespace Json
{
namespace Detail
{
template<typename W, typename T>
void FieldTypeToHexString(W &writer, const T &value)
{
StatusCode statusCode;
const uint8_t *pData;
size_t dataLength;
statusCode = value.Get(pData, dataLength);
if (ACTIV_UNLIKELY(STATUS_CODE_SUCCESS != statusCode))
{
ACTIV_BOOST_THROW_EXCEPTION(Exception() << Exception::StatusCodeInfo(statusCode) <<
Exception::DescriptionInfo("failed to convert <" + value.ToString() + "> to JSON"));
}
MessageBuilder messageBuilder;
for (size_t i = 0; i < dataLength; ++i)
{
statusCode = messageBuilder.AppendPrintf("%02x", pData[i]);
if (ACTIV_UNLIKELY(STATUS_CODE_SUCCESS != statusCode))
{
ACTIV_BOOST_THROW_EXCEPTION(Exception() << Exception::StatusCodeInfo(statusCode) <<
Exception::DescriptionInfo("failed to convert <" + value.ToString() + "> to JSON"));
}
}
if (ACTIV_UNLIKELY(!writer.String(reinterpret_cast<const char *>(messageBuilder.GetMessage()),
static_cast<rapidjson::SizeType>(messageBuilder.GetLength()))))
{
ACTIV_BOOST_THROW_EXCEPTION(Exception() <<
Exception::DescriptionInfo("failed to convert <" + value.ToString() + "> to JSON"));
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
void HexStringToFieldType(const Value &value, T &fieldType)
{
StatusCode statusCode;
// This is not round the houses. This is round the whole estate.
CxxYZ::string_view hexStringView;
Json::ValidateValue(value, hexStringView);
const auto makeException(
[&]()
{
return Exception() << Exception::StatusCodeInfo(statusCode) <<
Exception::DescriptionInfo("failed to convert <" + hexStringView + "> from JSON");
});
MessageValidator messageValidator(hexStringView.data(), hexStringView.length());
MessageBuilder messageBuilder;
while (!messageValidator.IsEndOfMessage())
{
uint8_t byteValue;
statusCode = messageValidator.ValidateAsciiHexadecimalIntegral<MessageHandler::ENDIAN_LITTLE>(2, byteValue);
if (ACTIV_UNLIKELY(STATUS_CODE_SUCCESS != statusCode))
ACTIV_BOOST_THROW_EXCEPTION(makeException());
statusCode = messageBuilder.Append(byteValue);
if (ACTIV_UNLIKELY(STATUS_CODE_SUCCESS != statusCode))
ACTIV_BOOST_THROW_EXCEPTION(makeException());
}
statusCode = fieldType.Set(reinterpret_cast<const byte_t *>(messageBuilder.GetMessage()), messageBuilder.GetLength());
if (ACTIV_UNLIKELY(STATUS_CODE_SUCCESS != statusCode))
ACTIV_BOOST_THROW_EXCEPTION(makeException());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDate(W &writer, const Date &date)
{
AppendArrayValues(writer, date.GetYear(), date.GetMonth(), date.GetDay());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void ValidateDate(const Value &value, Date &date)
{
if (ACTIV_UNLIKELY(value.Size() < 3))
ACTIV_BOOST_THROW_EXCEPTION(Exception() << Exception::DescriptionInfo("not enough array members for Date"));
uint32_t year, month, day;
Json::ValidateValue(value[0], year);
Json::ValidateValue(value[1], month);
Json::ValidateValue(value[2], day);
StatusCode statusCode = date.Set(year, month, day);
if (ACTIV_UNLIKELY(STATUS_CODE_SUCCESS != statusCode))
ACTIV_BOOST_THROW_EXCEPTION(Exception() << Exception::StatusCodeInfo(statusCode));
}
// ---------------------------------------------------------------------------------------------------------------------------------
using SecondResolutionString = ACTIV_MAKE_STRING_LITERAL("s");
using MillisecondResolutionString = ACTIV_MAKE_STRING_LITERAL("m");
using MicrosecondResolutionString = ACTIV_MAKE_STRING_LITERAL("u");
using NanosecondResolutionString = ACTIV_MAKE_STRING_LITERAL("n");
template<typename W>
void AppendTime(W &writer, const Time &time)
{
switch (time.GetResolution())
{
case Time::RESOLUTION_SECOND:
AppendArrayValues(writer, time.GetTotal<Time::Seconds>(), SecondResolutionString());
break;
case Time::RESOLUTION_MILLISECOND:
AppendArrayValues(writer, time.GetTotal<Time::Milliseconds>(), MillisecondResolutionString());
break;
case Time::RESOLUTION_MICROSECOND:
AppendArrayValues(writer, time.GetTotal<Time::Microseconds>(), MicrosecondResolutionString());
break;
case Time::RESOLUTION_NANOSECOND:
AppendArrayValues(writer, time.GetTotal<Time::Nanoseconds>(), NanosecondResolutionString());
break;
default:
ACTIV_BOOST_THROW_EXCEPTION(Exception() <<
Exception::DescriptionInfo("invalid resolution <" + TypeToString(time.GetResolution()) + ">"));
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<size_t INITIAL_INDEX>
inline void ValidateTime(const Value &value, Time &time)
{
if (ACTIV_UNLIKELY(value.Size() < (INITIAL_INDEX + 2)))
ACTIV_BOOST_THROW_EXCEPTION(Exception() << Exception::DescriptionInfo("not enough array members for Time"));
uint64_t durationInDay;
Json::ValidateValue(value[static_cast<rapidjson::SizeType>(INITIAL_INDEX + 0)], durationInDay);
CxxYZ::string_view resolutionString;
Json::ValidateValue(value[static_cast<rapidjson::SizeType>(INITIAL_INDEX + 1)], resolutionString);
if (ACTIV_UNLIKELY(1 != resolutionString.length()))
{
ACTIV_BOOST_THROW_EXCEPTION(Exception() <<
Exception::DescriptionInfo("invalid resolution <" + resolutionString + ">"));
}
StatusCode statusCode;
switch (resolutionString[0])
{
case SecondResolutionString::ArrayOperator<0>():
statusCode = time.SetT<Time::Seconds>(durationInDay);
break;
case MillisecondResolutionString::ArrayOperator<0>():
statusCode = time.SetT<Time::Milliseconds>(durationInDay);
break;
case MicrosecondResolutionString::ArrayOperator<0>():
statusCode = time.SetT<Time::Microseconds>(durationInDay);
break;
case NanosecondResolutionString::ArrayOperator<0>():
statusCode = time.SetT<Time::Nanoseconds>(durationInDay);
break;
default:
ACTIV_BOOST_THROW_EXCEPTION(Exception() <<
Exception::DescriptionInfo("unknown resolution <" + resolutionString + ">"));
}
if (ACTIV_UNLIKELY(STATUS_CODE_SUCCESS != statusCode))
ACTIV_BOOST_THROW_EXCEPTION(Exception() << Exception::StatusCodeInfo(statusCode));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendRational(W &writer, const Rational &rational)
{
AppendArrayValues(writer, rational.GetNumerator(), rational.GetDenominator());
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const Date &value)
{
const auto scopedArray(MakeScopedArray(writer));
AppendDate(writer, value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const Time &value)
{
const auto scopedArray(MakeScopedArray(writer));
AppendTime(writer, value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const DateTime &value)
{
const auto scopedArray(MakeScopedArray(writer));
AppendDate(writer, value.GetDate());
AppendTime(writer, value.GetTime());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const SInt &value)
{
Json::AppendValue(writer, value.Get());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const UInt &value)
{
Json::AppendValue(writer, value.Get());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const Rational &value)
{
const auto scopedArray(MakeScopedArray(writer));
AppendRational(writer, value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const TRational &value)
{
const auto scopedArray(MakeScopedArray(writer));
AppendRational(writer, value);
bool hasAppendedTick = false, hasAppendedTrendOnDay = false, hasAppendedTrendOnPrevious = false;
const auto appendTick(
[&]()
{
if (!hasAppendedTick)
{
Json::AppendValue(writer, value.GetTick());
hasAppendedTick = true;
}
});
const auto appendTrendOnDay(
[&]()
{
if (!hasAppendedTrendOnDay)
{
Json::AppendValue(writer, value.GetTrendOnDay());
hasAppendedTrendOnDay = true;
}
});
const auto appendTrendOnPrevious(
[&]()
{
if (!hasAppendedTrendOnPrevious)
{
Json::AppendValue(writer, value.GetTrendOnPrevious());
hasAppendedTrendOnPrevious = true;
}
});
if (TRational::TICK_UNDEFINED != value.GetTick())
appendTick();
if (TRational::TREND_UNDEFINED != value.GetTrendOnDay())
{
appendTick();
appendTrendOnDay();
}
if (TRational::TREND_UNDEFINED != value.GetTrendOnPrevious())
{
appendTick();
appendTrendOnDay();
appendTrendOnPrevious();
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const TextString &value)
{
FieldTypeToHexString(writer, value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const TextArray &value)
{
FieldTypeToHexString(writer, value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const BinaryString &value)
{
FieldTypeToHexString(writer, value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const BinaryArray &value)
{
FieldTypeToHexString(writer, value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const Blob &value)
{
FieldTypeToHexString(writer, value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const CrcBlob &value)
{
FieldTypeToHexString(writer, value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const Boolean &value)
{
if (ACTIV_UNLIKELY(!writer.Bool(value.Get())))
ACTIV_BOOST_THROW_EXCEPTION(Exception());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendDefinedFieldType(W &writer, const IFieldType &value)
{
#define ACTIV_RAPID_JSON_HELPER_FIELD_TYPE_DETAIL_DECLARE_CASE(r, data, tuple) \
case ACTIV_FIELD_TYPE_TUPLE_GET_TYPE(tuple): \
return AppendDefinedFieldType(writer, \
static_cast<const ACTIV_FIELD_TYPE_TUPLE_GET_NAME(tuple) &>(value));
switch (value.GetType())
{
ACTIV_BOOST_PP_SEQ_FOR_EACH(ACTIV_RAPID_JSON_HELPER_FIELD_TYPE_DETAIL_DECLARE_CASE, , ACTIV_FIELD_TYPE_TUPLE_LIST)
default:
assert(false);
ACTIV_BOOST_THROW_EXCEPTION(Exception());
}
#undef ACTIV_RAPID_JSON_HELPER_FIELD_TYPE_DETAIL_DECLARE_CASE
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, Date &date)
{
ValidateDate(value, date);
}
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, Time &time)
{
ValidateTime<0>(value, time);
}
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, DateTime &dateTime)
{
Date date;
ValidateDate(value, date);
Time time;
ValidateTime<3>(value, time);
dateTime.SetDate(date);
dateTime.SetTime(time);
}
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, UInt &uint)
{
uint64_t tempValue;
Json::ValidateValue(value, tempValue);
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, uint.Set(tempValue));
}
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, SInt &sint)
{
int64_t tempValue;
Json::ValidateValue(value, tempValue);
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, sint.Set(tempValue));
}
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, Boolean &boolean)
{
bool tempValue;
Json::ValidateValue(value, tempValue);
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, boolean.Set(tempValue));
}
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, TextArray &textArray)
{
HexStringToFieldType(value, textArray);
}
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, TextString &textString)
{
HexStringToFieldType(value, textString);
}
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, BinaryArray &binaryArray)
{
HexStringToFieldType(value, binaryArray);
}
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, BinaryString &binaryString)
{
HexStringToFieldType(value, binaryString);
}
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, Blob &blob)
{
HexStringToFieldType(value, blob);
}
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, CrcBlob &crcBlob)
{
HexStringToFieldType(value, crcBlob);
}
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, Rational &rational)
{
if (ACTIV_UNLIKELY(value.Size() < 2))
ACTIV_BOOST_THROW_EXCEPTION(Exception() << Exception::DescriptionInfo("not enough array members for Rational"));
int64_t numerator;
Json::ValidateValue(value[0], numerator);
Rational::Denominator denominator;
Json::ValidateValue(value[1], denominator);
StatusCode statusCode = rational.Set(numerator, denominator);
if (ACTIV_UNLIKELY(STATUS_CODE_SUCCESS != statusCode))
ACTIV_BOOST_THROW_EXCEPTION(Exception() << Exception::StatusCodeInfo(statusCode));
}
// ---------------------------------------------------------------------------------------------------------------------------------
void ValidateDefinedFieldType(const Value &value, TRational &trational)
{
const auto arraySize(value.Size());
if (ACTIV_UNLIKELY(arraySize < 2))
ACTIV_BOOST_THROW_EXCEPTION(Exception() << Exception::DescriptionInfo("not enough array members for TRational"));
int64_t numerator;
Json::ValidateValue(value[0], numerator);
Rational::Denominator denominator;
Json::ValidateValue(value[1], denominator);
TRational::Tick tick(TRational::TICK_UNDEFINED);
if (arraySize >= 3)
Json::ValidateValue(value[2], tick);
TRational::Trend trendOnDay(TRational::TREND_UNDEFINED);
if (arraySize >= 4)
Json::ValidateValue(value[3], trendOnDay);
TRational::Trend trendOnPrevious(TRational::TREND_UNDEFINED);
if (arraySize >= 5)
Json::ValidateValue(value[4], trendOnPrevious);
StatusCode statusCode = trational.Set(numerator, denominator, tick, trendOnDay, trendOnPrevious);
if (ACTIV_UNLIKELY(STATUS_CODE_SUCCESS != statusCode))
ACTIV_BOOST_THROW_EXCEPTION(Exception() << Exception::StatusCodeInfo(statusCode));
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! Tag for FieldType types.
class FieldTypeTag { };
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
class CategoryTag<T, typename CxxYZ::enable_if<IsFieldType<T>::value>::type>
{
public:
using type = FieldTypeTag;
};
// ---------------------------------------------------------------------------------------------------------------------------------
template<>
class CategoryTag<IFieldType>
{
public:
using type = FieldTypeTag;
};
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W, typename T>
void AppendValue(W &writer, const T &value, FieldTypeTag)
{
// Extension point for Json::AppendValue().
if (value.IsInitialized())
{
AppendDefinedFieldType(writer, value);
}
else
{
if (!writer.Null())
ACTIV_BOOST_THROW_EXCEPTION(Exception());
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename W>
void AppendValue(W &writer, const IFieldType &value, FieldTypeTag)
{
// Extension point for Json::AppendValue().
if (value.IsInitialized())
{
#define ACTIV_RAPID_JSON_HELPER_FIELD_TYPE_DETAIL_DECLARE_CASE(r, data, tuple) \
case ACTIV_FIELD_TYPE_TUPLE_GET_TYPE(tuple): \
return AppendDefinedFieldType(writer, static_cast<const ACTIV_FIELD_TYPE_TUPLE_GET_NAME(tuple) &>(value));
switch (value.GetType())
{
ACTIV_BOOST_PP_SEQ_FOR_EACH(ACTIV_RAPID_JSON_HELPER_FIELD_TYPE_DETAIL_DECLARE_CASE, , ACTIV_FIELD_TYPE_TUPLE_LIST)
default:
assert(false);
ACTIV_BOOST_THROW_EXCEPTION(Exception());
}
#undef ACTIV_RAPID_JSON_HELPER_FIELD_TYPE_DETAIL_DECLARE_CASE
}
else
{
if (!writer.Null())
ACTIV_BOOST_THROW_EXCEPTION(Exception());
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
void ValidateValue(const Value &value, T &target, FieldTypeTag)
{
// Extension point for Json::ValidateValue().
if (!value.IsNull())
ValidateDefinedFieldType(value, target);
else
target.Reset();
}
} // namespace Detail
} // namespace Json
} // namespace Activ
#endif // (!defined ACTIV_MIDDLEWARE_ACTIV_BASE_FIELD_TYPES_JSON_FIELD_TYPE_TRANSLATION_H)
File diff suppressed because it is too large. Load diff
@@ -1,743 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/SInt.h
*
* @brief Header file for the signed integer class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_SINT_H)
#define ACTIV_BASE_FIELD_TYPES_SINT_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/IFieldType.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/Misc/MemoryHelper.h"
//! Activ namespace.
namespace Activ
{
class Rational;
// ---------------------------------------------------------------------------------------------------------------------------------
//! Signed integer class.
class SInt ACTIV_FINAL : public IFieldType
{
public:
static const FieldType FIELD_TYPE = FIELD_TYPE_SINT; ///< The field type.
using IFieldType::FromString;
using IFieldType::Serialize;
using IFieldType::SerializeBody;
using IFieldType::SerializeLengthAndBody;
using IFieldType::Deserialize;
using IFieldType::DeserializeBody;
using IFieldType::DeserializeLengthAndBody;
//! Default constructor.
SInt();
/**
* @brief Constructor.
*
* @param value the value.
*/
SInt(const int64_t value);
//! Destructor.
virtual ~SInt() ACTIV_OVERRIDE;
/**
* @brief Equality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator==(const SInt &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator!=(const SInt &rhs) const;
/**
* @brief Less than operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator<(const SInt &rhs) const;
/**
* @brief Less than or equal to operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator<=(const SInt &rhs) const;
/**
* @brief Greater than operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator>(const SInt &rhs) const;
/**
* @brief Greater than or equal to operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator>=(const SInt &rhs) const;
/**
* @brief Addition assignment operator.
*
* @param rhs the value to add to this object.
*
* @return a reference to this object.
*
* @throw StatusCodeException
*/
SInt& operator+=(const SInt &rhs);
/**
* @brief Subtraction assignment operator.
*
* @param rhs the value to subtract from this object.
*
* @return a reference to this object.
*
* @throw StatusCodeException
*/
SInt& operator-=(const SInt &rhs);
/**
* @brief Multiplication assignment operator.
*
* @param rhs the value to multiply this object by.
*
* @return a reference to this object.
*
* @throw StatusCodeException
*/
SInt& operator*=(const SInt &rhs);
/**
* @brief Division assignment operator.
*
* @param rhs the value to divide this object by.
*
* @return a reference to this object.
*
* @throw StatusCodeException
*/
SInt& operator/=(const SInt &rhs);
//! Rational conversion operator.
ACTIV_BASE_API operator const Rational() const;
/**
* @brief Set a new value.
*
* @param value the value.
*
* @retval STATUS_CODE_SUCCESS
*/
StatusCode Set(const int64_t value);
/**
* @brief Get the value.
*
* @param value the value.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
*/
StatusCode Get(int64_t &value) const;
/**
* @brief Get the value.
*
* @return the value.
*
* @throw StatusCodeException
*/
int64_t Get() const;
/**
* @brief Add.
*
* @param rhs the value to add to this object.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval STATUS_CODE_OUT_OF_RANGE
*/
ACTIV_BASE_API StatusCode Add(const SInt &rhs);
/**
* @brief Subtract.
*
* @param rhs the value to subtract from this object.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval STATUS_CODE_OUT_OF_RANGE
*/
ACTIV_BASE_API StatusCode Subtract(const SInt &rhs);
/**
* @brief Multiply.
*
* @param rhs the value to multiply this object by.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval STATUS_CODE_OUT_OF_RANGE
*/
ACTIV_BASE_API StatusCode Multiply(const SInt &rhs);
/**
* @brief Divide.
*
* @param rhs the value to divide this object by.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval STATUS_CODE_OUT_OF_RANGE
*/
ACTIV_BASE_API StatusCode Divide(const SInt &rhs);
virtual void Reset() ACTIV_OVERRIDE;
virtual void Clear() ACTIV_OVERRIDE;
/**
* @brief Compare.
*
* @param rhs the object to compare with.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API StatusCode Compare(const SInt &rhs, int &result) const;
ACTIV_BASE_API virtual StatusCode Compare(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Convert(const IFieldType * const pIFieldType) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode AppendAsString(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode FromString(MessageValidator &messageValidator) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String GetFromStringFormat() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) ACTIV_OVERRIDE;
virtual size_t GetSerializedLength() const ACTIV_OVERRIDE;
virtual size_t GetSerializedBodyLength() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode IsDifferent(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, bool &isDifferent) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetMemoryUsage() const ACTIV_OVERRIDE;
/**
* @brief Get the maximum serialized length of the object.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object.
*/
static size_t GetMaxSerializedLength(const size_t size);
/**
* @brief Get the maximum serialized length of the object's body.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object's body.
*/
static size_t GetMaxSerializedBodyLength(const size_t size);
/**
* @brief Compare two objects serialized bodies.
*
* @param pLhsSerializedBody the buffer containing the lhs serialized version of the object's body in.
* @param lhsSerializedBodyLength the lhs serialized body length.
* @param pRhsSerializedBody the buffer containing the rhs serialized version of the object's body in.
* @param rhsSerializedBodyLength the rhs serialized body length.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API static StatusCode Compare(const void * const pLhsSerializedBody, const size_t lhsSerializedBodyLength, const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result);
/**
* @brief Validate the serialized length and body.
*
* @param messageValidator the message validator.
* @param serializedBodyOffset the serialized body offset.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode ValidateSerializedLengthAndBody(MessageValidator &messageValidator, size_t &serializedBodyOffset, size_t &serializedBodyLength);
/**
* @brief Serialize a value's length and body into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param value the value to serialize.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
template<typename T>
static StatusCode SerializeValueLengthAndBody(MessageBuilder &messageBuilder, const T value);
/**
* @brief Is valid serialized body length.
*
* @param serializedBodyLength the serialized body length.
*
* @return whether the serialized body length is valid.
*/
static bool IsValidSerializedBodyLength(const size_t serializedBodyLength);
/**
* @brief Get a usage string for the format supported by FromString().
*
* @return String, may be empty.
*/
ACTIV_BASE_API static String FromStringFormat();
private:
//! Get the compressed value size.
size_t GetCompressedValueSize() const;
/**
* @brief Serialize the object's body into the supplied data buffer.
*
* This will serialize to a fixed size buffer (GetMaxSerializedLength<T>()).
*
* @param pSerializedBody the buffer to store a serialized version of the object in.
*
* @retval STATUS_CODE_SUCCESS
*/
template <typename T> StatusCode SerializeBody(void *pSerializedBody) const;
/**
* @brief Deserialize the object's body from the supplied data buffer.
*
* This will deserialize from a fixed size buffer (GetMaxSerializedLength<T>()).
*
* @param pSerializedBody the buffer from which the object will be extracted.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_FORMAT
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval STATUS_CODE_OUT_OF_RANGE
*/
template <typename T> StatusCode DeserializeBody(const void * const pSerializedBody);
/**
* @brief Serialize a value's length and body into the supplied message builder to a given length (given by T) with
* a check for maximum serialized length.
*
* T is the smallest signed integral type which will hold the absolute value of the numerator.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param value
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
template<typename T>
static StatusCode InternalSerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength,
const T value);
/**
* @brief Serialize a value's length and body into the supplied message builder to a given length (given by T).
*
* T is the smallest signed integral type which will hold the absolute value of the numerator.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param value
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
template<typename T>
static StatusCode InternalSerializeLengthAndBody(MessageBuilder &messageBuilder, const T value);
int64_t m_value; ///< The value.
#if (defined ACTIV_PLATFORM_WASM)
friend class Wasm::FieldTypeAccessor;
#endif
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline SInt::SInt() :
IFieldType(FIELD_TYPE)
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline SInt::SInt(const int64_t value) :
IFieldType(FIELD_TYPE)
{
(void) Set(value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline SInt::~SInt()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool SInt::operator==(const SInt &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (0 == result);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool SInt::operator!=(const SInt &rhs) const
{
return !((*this) == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool SInt::operator<(const SInt &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (result < 0);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool SInt::operator<=(const SInt &rhs) const
{
return !((*this) > rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool SInt::operator>(const SInt &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (result > 0);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool SInt::operator>=(const SInt &rhs) const
{
return !((*this) < rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline SInt& SInt::operator+=(const SInt &rhs)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Add(rhs));
return (*this);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline SInt& SInt::operator-=(const SInt &rhs)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Subtract(rhs));
return (*this);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline SInt& SInt::operator*=(const SInt &rhs)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Multiply(rhs));
return (*this);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline SInt& SInt::operator/=(const SInt &rhs)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Divide(rhs));
return (*this);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode SInt::Set(const int64_t value)
{
m_value = value;
m_isInitialized = true;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode SInt::Get(int64_t &value) const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
return STATUS_CODE_NOT_INITIALIZED;
value = m_value;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline int64_t SInt::Get() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_value;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void SInt::Reset()
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void SInt::Clear()
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t SInt::GetSerializedLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedLength(GetCompressedValueSize());
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t SInt::GetSerializedBodyLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedBodyLength(GetCompressedValueSize());
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t SInt::GetMaxSerializedLength(const size_t size)
{
return GetMaxSerializedBodyLength(size);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t SInt::GetMaxSerializedBodyLength(const size_t size)
{
return size;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline StatusCode SInt::SerializeValueLengthAndBody(MessageBuilder &messageBuilder, const T value)
{
if ((value >= Boost::integer_traits<int8_t>::const_min) && (value <= Boost::integer_traits<int8_t>::const_max))
return InternalSerializeLengthAndBody(messageBuilder, static_cast<int8_t>(value));
else if ((value >= Boost::integer_traits<int16_t>::const_min) && (value <= Boost::integer_traits<int16_t>::const_max))
return InternalSerializeLengthAndBody(messageBuilder, static_cast<int16_t>(value));
else if ((value >= Boost::integer_traits<int32_t>::const_min) && (value <= Boost::integer_traits<int32_t>::const_max))
return InternalSerializeLengthAndBody(messageBuilder, static_cast<int32_t>(value));
else
return InternalSerializeLengthAndBody(messageBuilder, value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool SInt::IsValidSerializedBodyLength(const size_t serializedBodyLength)
{
return ((GetMaxSerializedBodyLength(sizeof(int64_t)) == serializedBodyLength) || (GetMaxSerializedBodyLength(sizeof(int32_t)) == serializedBodyLength) || (GetMaxSerializedBodyLength(sizeof(int16_t)) == serializedBodyLength) || (GetMaxSerializedBodyLength(sizeof(int8_t)) == serializedBodyLength));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t SInt::GetCompressedValueSize() const
{
if ((m_value >= Boost::integer_traits<int8_t>::const_min) && (m_value <= Boost::integer_traits<int8_t>::const_max))
return sizeof(int8_t);
if ((m_value >= Boost::integer_traits<int16_t>::const_min) && (m_value <= Boost::integer_traits<int16_t>::const_max))
return sizeof(int16_t);
if ((m_value >= Boost::integer_traits<int32_t>::const_min) && (m_value <= Boost::integer_traits<int32_t>::const_max))
return sizeof(int32_t);
return sizeof(int64_t);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T> inline StatusCode SInt::SerializeBody(void *pSerializedBody) const
{
CopyValueToUnalignedPointer(pSerializedBody, HostToLittleEndianOrder(static_cast<T>(m_value)));
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T> inline StatusCode SInt::DeserializeBody(const void * const pSerializedBody)
{
return Set(static_cast<int64_t>(LittleEndianToHostOrder(GetValueFromUnalignedPointer<T>(pSerializedBody))));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
StatusCode SInt::InternalSerializeLengthAndBody(MessageBuilder &messageBuilder, const T value)
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=,
messageBuilder.Append<MessageBuilder::ENDIAN_LITTLE>(static_cast<uint8_t>(sizeof(T))));
return messageBuilder.Append<MessageBuilder::ENDIAN_LITTLE>(value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Addition operator for the signed integer object.
*
* @param lhs the left hand side value.
* @param rhs the right hand side value.
*
* @return an object containing the result of the operation.
*
* @throw StatusCodeException
*/
inline SInt operator+(const SInt &lhs, const SInt &rhs)
{
return SInt(lhs) += rhs;
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Subtraction operator for the signed integer object.
*
* @param lhs the left hand side value.
* @param rhs the right hand side value.
*
* @return an object containing the result of the operation.
*
* @throw StatusCodeException
*/
inline SInt operator-(const SInt &lhs, const SInt &rhs)
{
return SInt(lhs) -= rhs;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Multiplication operator for the signed integer object.
*
* @param lhs the left hand side value.
* @param rhs the right hand side value.
*
* @return an object containing the result of the operation.
*
* @throw StatusCodeException
*/
inline SInt operator*(const SInt &lhs, const SInt &rhs)
{
return SInt(lhs) *= rhs;
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Division operator for the signed integer object.
*
* @param lhs the left hand side value.
* @param rhs the right hand side value.
*
* @return an object containing the result of the operation.
*
* @throw StatusCodeException
*/
inline SInt operator/(const SInt &lhs, const SInt &rhs)
{
return SInt(lhs) /= rhs;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private Template specialization to map from FIELD_TYPE_SINT to SInt class.
template<>
class FieldTypeToClass<FIELD_TYPE_SINT>
{
public:
typedef SInt Type;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_SINT_H)
File diff suppressed because it is too large. Load diff
@@ -1,583 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/TextArray.h
*
* @brief Header file for the text array class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_TEXT_ARRAY_H)
#define ACTIV_BASE_FIELD_TYPES_TEXT_ARRAY_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/IFieldType.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/CxxYZ/string_view.h"
#include "ActivMiddleware/Misc/BitFields.h"
#include "ActivMiddleware/Misc/MemoryHelper.h"
//! Activ namespace.
namespace Activ
{
//! Text array class.
class TextArray ACTIV_FINAL : public IFieldType
{
public:
static const FieldType FIELD_TYPE = FIELD_TYPE_TEXT_ARRAY; ///< The field type.
using IFieldType::FromString;
using IFieldType::Serialize;
using IFieldType::SerializeBody;
using IFieldType::SerializeLengthAndBody;
using IFieldType::Deserialize;
using IFieldType::DeserializeBody;
using IFieldType::DeserializeLengthAndBody;
//! Default constructor.
TextArray();
/**
* @brief Constructor.
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @throw StatusCodeException
*/
TextArray(const uint8_t * const pData, const size_t size);
/**
* @brief Copy constructor.
*
* @param rhs the value to assign to this object.
*/
TextArray(const TextArray &rhs);
//! Destructor.
virtual ~TextArray() ACTIV_OVERRIDE;
/**
* @brief Equality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*/
bool operator==(const TextArray &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*/
bool operator!=(const TextArray &rhs) const;
/**
* @brief Assignment operator.
*
* @param rhs the value to assign to this object.
*
* @return a reference to this object.
*/
TextArray &operator=(const TextArray &rhs);
/**
* @brief Set the data and size.
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_PARAMETER
*/
StatusCode Set(const uint8_t * const pData, const size_t size);
/**
* @brief Get the data and size.
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
*/
StatusCode Get(const uint8_t *&pData, size_t &size) const;
/**
* @brief Get the data.
*
* @return the pointer to the data.
*
* @throw StatusCodeException
*/
const uint8_t *GetData() const;
/**
* @brief Get the size.
*
* @return the size of the data.
*
* @throw StatusCodeException
*/
size_t GetSize() const;
virtual void Reset() ACTIV_OVERRIDE;
virtual void Clear() ACTIV_OVERRIDE;
/**
* @brief Compare.
*
* @param rhs the object to compare with.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API StatusCode Compare(const TextArray &rhs, int &result) const;
ACTIV_BASE_API virtual StatusCode Compare(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Convert(const IFieldType * const pIFieldType) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode AppendAsString(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode FromString(MessageValidator &messageValidator) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String GetFromStringFormat() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) ACTIV_OVERRIDE;
virtual size_t GetSerializedLength() const ACTIV_OVERRIDE;
virtual size_t GetSerializedBodyLength() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode IsDifferent(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, bool &isDifferent) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetMemoryUsage() const ACTIV_OVERRIDE;
/**
* @brief Create a CxxYZ::string_view.
*
* @return the object as a CxxYZ::string_view.
*/
CxxYZ::string_view ToStringView() const;
/**
* @brief Get the maximum serialized length of the object.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object.
*/
static size_t GetMaxSerializedLength(const size_t size);
/**
* @brief Get the maximum serialized length of the object's body.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object's body.
*/
static size_t GetMaxSerializedBodyLength(const size_t size);
/**
* @brief Compare two objects serialized bodies.
*
* @param pLhsSerializedBody the buffer containing the lhs serialized version of the object's body in.
* @param lhsSerializedBodyLength the lhs serialized body length.
* @param pRhsSerializedBody the buffer containing the rhs serialized version of the object's body in.
* @param rhsSerializedBodyLength the rhs serialized body length.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API static StatusCode Compare(const void * const pLhsSerializedBody, const size_t lhsSerializedBodyLength, const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result);
/**
* @brief Serialize the object into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Serialize the object's body into the supplied data buffer.
*
* @param pSerializedBody the buffer to store a serialized version of the object's body in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param serializedBodyLength the serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Serialize the object's length and body into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Deserialize the object from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength, const uint8_t *&pData, size_t &size);
/**
* @brief Deserialize the object's body from the supplied data buffer.
*
* @param pSerializedBody the buffer from which the object's body will be extracted.
* @param serializedBodyLength the serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API static StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength, const uint8_t *&pData, size_t &size);
/**
* @brief Deserialize the object's length and body from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength, const uint8_t *&pData, size_t &size);
/**
* @brief Validate the serialized length and body.
*
* @param messageValidator the message validator.
* @param serializedBodyOffset the serialized body offset.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode ValidateSerializedLengthAndBody(MessageValidator &messageValidator, size_t &serializedBodyOffset, size_t &serializedBodyLength);
/**
* @brief Is valid serialized body length.
*
* @param serializedBodyLength the serialized body length.
*
* @return whether the serialized body length is valid.
*/
static bool IsValidSerializedBodyLength(const size_t serializedBodyLength);
/**
* @brief Get a usage string for the format supported by FromString().
*
* @return String, may be empty.
*/
ACTIV_BASE_API static String FromStringFormat();
private:
struct UnknownLengthBitmap : public Bitmap<8, MsbOrigin>
{
typedef BitField<UnknownLengthBitmap, 1> IsMultiByteLength;
typedef BitField<IsMultiByteLength, 1> IsFourByteLength;
};
struct OneByteLengthBitmap : public Bitmap<8, MsbOrigin>
{
typedef BitField<OneByteLengthBitmap, 1> IsMultiByteLength;
typedef BitField<IsMultiByteLength, 7> Length;
};
struct TwoByteLengthBitmap : public Bitmap<16, MsbOrigin>
{
typedef BitField<TwoByteLengthBitmap, 1> IsMultiByteLength;
typedef BitField<IsMultiByteLength, 1> IsFourByteLength;
typedef BitField<IsFourByteLength, 14> Length;
};
struct FourByteLengthBitmap : public Bitmap<32, MsbOrigin>
{
typedef BitField<FourByteLengthBitmap, 1> IsMultiByteLength;
typedef BitField<IsMultiByteLength, 1> IsFourByteLength;
typedef BitField<IsFourByteLength, 30> Length;
};
static const size_t RESERVED_BUFFER_SIZE = 32; ///< The reserved buffer size.
/**
* @brief Compare two buffers.
*
* @param pLhsBuffer the lhs buffer.
* @param lhsBufferLength the lhs buffer length.
* @param pRhsBuffer the rhs buffer.
* @param rhsBufferLength the rhs buffer length.
*
* @return result the result of the comparison.
*/
static int Compare(const void * const pLhsBuffer, const size_t lhsBufferLength, const void * const pRhsBuffer, const size_t rhsBufferLength);
uint8_t m_reservedBuffer[RESERVED_BUFFER_SIZE]; ///< The reserved buffer.
size_t m_allocatedSize; ///< The allocated size of the data.
uint8_t * m_pData; ///< Pointer to the data.
size_t m_size; ///< The size of the data.
#if (defined ACTIV_PLATFORM_WASM)
friend class Wasm::FieldTypeAccessor;
#endif
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline TextArray::TextArray() :
IFieldType(FIELD_TYPE),
m_allocatedSize(0),
m_pData(m_reservedBuffer)
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline TextArray::TextArray(const uint8_t * const pData, const size_t size) :
IFieldType(FIELD_TYPE),
m_allocatedSize(0),
m_pData(m_reservedBuffer)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(pData, size));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline TextArray::TextArray(const TextArray &rhs) :
IFieldType(FIELD_TYPE),
m_allocatedSize(0),
m_pData(m_reservedBuffer)
{
if (rhs.IsInitialized())
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(rhs.m_pData, rhs.m_size));
else
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline TextArray::~TextArray()
{
if (0 != m_allocatedSize)
std::free(m_pData);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool TextArray::operator==(const TextArray &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (0 == result);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool TextArray::operator!=(const TextArray &rhs) const
{
return !(*this == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline TextArray &TextArray::operator=(const TextArray &rhs)
{
if (this != &rhs)
{
if (rhs.IsInitialized())
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(rhs.m_pData, rhs.m_size));
}
else
{
Reset();
}
}
return *this;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode TextArray::Set(const uint8_t * const pData, const size_t size)
{
// TODO: range check?
if (ACTIV_UNLIKELY(0 == size))
return STATUS_CODE_INVALID_PARAMETER;
if (ACTIV_UNLIKELY(size > GetMaximum<size_t>(m_allocatedSize, size_t(RESERVED_BUFFER_SIZE))))
{
const size_t allocatedSize = (4 * (((std::max<size_t>(m_allocatedSize + (m_allocatedSize / 2), size) - 1) / 4) + 1));
uint8_t * const pAllocated = static_cast<uint8_t *>(((0 != m_allocatedSize) ? std::realloc(m_pData, allocatedSize) : std::malloc(allocatedSize)));
if (0 == pAllocated)
return STATUS_CODE_HEAP_EMPTY;
m_allocatedSize = allocatedSize;
m_pData = pAllocated;
}
MemoryCopy(m_pData, pData, size);
m_size = size;
m_isInitialized = true;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode TextArray::Get(const uint8_t *&pData, size_t &size) const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
return STATUS_CODE_NOT_INITIALIZED;
pData = m_pData;
size = m_size;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const uint8_t *TextArray::GetData() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_pData;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t TextArray::GetSize() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_size;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void TextArray::Reset()
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void TextArray::Clear()
{
if (0 != m_allocatedSize)
{
std::free(m_pData);
m_allocatedSize = 0;
}
m_pData = m_reservedBuffer;
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline CxxYZ::string_view TextArray::ToStringView() const
{
if (IsInitialized())
return CxxYZ::string_view(reinterpret_cast<const char *>(m_pData), m_size);
else
return CxxYZ::string_view(GetNotInitializedString());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t TextArray::GetSerializedLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedLength(m_size);
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t TextArray::GetSerializedBodyLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedBodyLength(m_size);
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t TextArray::GetMaxSerializedLength(const size_t size)
{
return GetMaxSerializedBodyLength(size);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t TextArray::GetMaxSerializedBodyLength(const size_t size)
{
return size;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool TextArray::IsValidSerializedBodyLength(const size_t serializedBodyLength)
{
return (0 != serializedBodyLength);
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private Template specialization to map from FIELD_TYPE_TEXT_ARRAY to TextArray class.
template<>
class FieldTypeToClass<FIELD_TYPE_TEXT_ARRAY>
{
public:
typedef TextArray Type;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_TEXT_ARRAY_H)
@@ -1,604 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/TextString.h
*
* @brief Header file for the text string class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_TEXT_STRING_H)
#define ACTIV_BASE_FIELD_TYPES_TEXT_STRING_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/IFieldType.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/CxxYZ/string_view.h"
#include "ActivMiddleware/Misc/MemoryHelper.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Text string class.
*/
class TextString ACTIV_FINAL : public IFieldType
{
public:
static const FieldType FIELD_TYPE = FIELD_TYPE_TEXT_STRING; ///< The field type.
using IFieldType::FromString;
using IFieldType::Serialize;
using IFieldType::SerializeBody;
using IFieldType::SerializeLengthAndBody;
using IFieldType::Deserialize;
using IFieldType::DeserializeBody;
using IFieldType::DeserializeLengthAndBody;
/**
* @brief Default constructor.
*/
TextString();
/**
* @brief Constructor.
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @throw StatusCodeException
*/
TextString(const uint8_t * const pData, const size_t size);
/**
* @brief Constructor.
*
* @param str reference to a String to copy data from.
*
* @throw StatusCodeException
*/
TextString(const String &str);
/**
* @brief Copy constructor.
*
* @param rhs the value to assign to this object.
*/
TextString(const TextString &rhs);
/**
* @brief Destructor.
*/
virtual ~TextString() ACTIV_OVERRIDE;
/**
* @brief Equality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*/
bool operator==(const TextString &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*/
bool operator!=(const TextString &rhs) const;
/**
* @brief Assignment operator.
*
* @param rhs the value to assign to this object.
*
* @return a reference to this object.
*/
TextString& operator=(const TextString &rhs);
/**
* @brief Set the data and size.
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_PARAMETER
*/
StatusCode Set(const uint8_t * const pData, const size_t size);
/**
* @brief Set the data and size.
*
* @param str reference to a String to copy data from.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_PARAMETER
*/
StatusCode Set(const String &str);
/**
* @brief Get the data and size.
*
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
*/
StatusCode Get(const uint8_t *&pData, size_t &size) const;
/**
* @brief Get the data.
*
* @return the pointer to the data.
*
* @throw StatusCodeException
*/
const uint8_t *GetData() const;
/**
* @brief Get the size.
*
* @return the size of the data.
*
* @throw StatusCodeException
*/
size_t GetSize() const;
virtual void Reset() ACTIV_OVERRIDE;
virtual void Clear() ACTIV_OVERRIDE;
/**
* @brief Compare.
*
* @param rhs the object to compare with.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API StatusCode Compare(const TextString &rhs, int &result) const;
ACTIV_BASE_API virtual StatusCode Compare(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Convert(const IFieldType * const pIFieldType) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode AppendAsString(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode FromString(MessageValidator &messageValidator) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String GetFromStringFormat() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) ACTIV_OVERRIDE;
virtual size_t GetSerializedLength() const ACTIV_OVERRIDE;
virtual size_t GetSerializedBodyLength() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode IsDifferent(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, bool &isDifferent) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetMemoryUsage() const ACTIV_OVERRIDE;
/**
* @brief Create a CxxYZ::string_view.
*
* @return the object as a CxxYZ::string_view.
*/
CxxYZ::string_view ToStringView() const;
/**
* @brief Get the maximum serialized length of the object.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object.
*/
static size_t GetMaxSerializedLength(const size_t size);
/**
* @brief Get the maximum serialized length of the object's body.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object's body.
*/
static size_t GetMaxSerializedBodyLength(const size_t size);
/**
* @brief Compare two objects serialized bodies.
*
* @param pLhsSerializedBody the buffer containing the lhs serialized version of the object's body in.
* @param lhsSerializedBodyLength the lhs serialized body length.
* @param pRhsSerializedBody the buffer containing the rhs serialized version of the object's body in.
* @param rhsSerializedBodyLength the rhs serialized body length.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API static StatusCode Compare(const void * const pLhsSerializedBody, const size_t lhsSerializedBodyLength, const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result);
/**
* @brief Serialize the object into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Serialize the object's body into the supplied data buffer.
*
* @param pSerializedBody the buffer to store a serialized version of the object's body in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param serializedBodyLength the serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Serialize the object's length and body into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength, const uint8_t * const pData, const size_t size);
/**
* @brief Deserialize the object from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength, const uint8_t *&pData, size_t &size);
/**
* @brief Deserialize the object's body from the supplied data buffer.
*
* @param pSerializedBody the buffer from which the object's body will be extracted.
* @param serializedBodyLength the serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API static StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength, const uint8_t *&pData, size_t &size);
/**
* @brief Deserialize the object's length and body from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param pData pointer to the data.
* @param size the size of the data.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength, const uint8_t *&pData, size_t &size);
/**
* @brief Validate the serialized length and body.
*
* @param messageValidator the message validator.
* @param serializedBodyOffset the serialized body offset.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode ValidateSerializedLengthAndBody(MessageValidator &messageValidator, size_t &serializedBodyOffset, size_t &serializedBodyLength);
/**
* @brief Is valid serialized body length.
*
* @param serializedBodyLength the serialized body length.
*
* @return whether the serialized body length is valid.
*/
static bool IsValidSerializedBodyLength(const size_t serializedBodyLength);
/**
* @brief Get a usage string for the format supported by FromString().
*
* @return String, may be empty.
*/
ACTIV_BASE_API static String FromStringFormat();
private:
static const size_t RESERVED_BUFFER_SIZE = 32; ///< The reserved buffer size.
/**
* @brief Compare two buffers.
*
* @param pLhsBuffer the lhs buffer.
* @param lhsBufferLength the lhs buffer length.
* @param pRhsBuffer the rhs buffer.
* @param rhsBufferLength the rhs buffer length.
*
* @return result the result of the comparison.
*/
static int Compare(const void * const pLhsBuffer, const size_t lhsBufferLength, const void * const pRhsBuffer, const size_t rhsBufferLength);
uint8_t m_reservedBuffer[RESERVED_BUFFER_SIZE]; ///< The reserved buffer.
size_t m_allocatedSize; ///< The allocated size of the data.
uint8_t * m_pData; ///< Pointer to the data.
size_t m_size; ///< The size of the data.
#if (defined ACTIV_PLATFORM_WASM)
friend class Wasm::FieldTypeAccessor;
#endif
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline TextString::TextString() :
IFieldType(FIELD_TYPE),
m_allocatedSize(0),
m_pData(m_reservedBuffer)
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline TextString::TextString(const uint8_t * const pData, const size_t size) :
IFieldType(FIELD_TYPE),
m_allocatedSize(0),
m_pData(m_reservedBuffer)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(pData, size));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline TextString::TextString(const String &str) :
IFieldType(FIELD_TYPE),
m_allocatedSize(0),
m_pData(m_reservedBuffer)
{
if (0 != str.length())
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(str));
else
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline TextString::TextString(const TextString &rhs) :
IFieldType(FIELD_TYPE),
m_allocatedSize(0),
m_pData(m_reservedBuffer)
{
if (rhs.IsInitialized())
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(rhs.m_pData, rhs.m_size));
else
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline TextString::~TextString()
{
if (0 != m_allocatedSize)
std::free(m_pData);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool TextString::operator==(const TextString &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (0 == result);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool TextString::operator!=(const TextString &rhs) const
{
return !(*this == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline TextString& TextString::operator=(const TextString &rhs)
{
if (this != &rhs)
{
if (rhs.IsInitialized())
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(rhs.m_pData, rhs.m_size));
}
else
{
Reset();
}
}
return *this;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode TextString::Set(const uint8_t * const pData, const size_t size)
{
// TODO: range check?
if (ACTIV_UNLIKELY(0 == size))
return STATUS_CODE_INVALID_PARAMETER;
if (ACTIV_UNLIKELY(size > GetMaximum<size_t>(m_allocatedSize, size_t(RESERVED_BUFFER_SIZE))))
{
const size_t allocatedSize = (4 * (((std::max<size_t>(m_allocatedSize + (m_allocatedSize / 2), size) - 1) / 4) + 1));
uint8_t * const pAllocated = static_cast<uint8_t *>(((0 != m_allocatedSize) ? std::realloc(m_pData, allocatedSize) : std::malloc(allocatedSize)));
if (0 == pAllocated)
return STATUS_CODE_HEAP_EMPTY;
m_allocatedSize = allocatedSize;
m_pData = pAllocated;
}
MemoryCopy(m_pData, pData, size);
m_size = size;
m_isInitialized = true;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode TextString::Set(const String &str)
{
if (0 != str.length())
return Set(reinterpret_cast<const uint8_t *>(str.c_str()), str.length());
Reset();
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode TextString::Get(const uint8_t *&pData, size_t &size) const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
return STATUS_CODE_NOT_INITIALIZED;
pData = m_pData;
size = m_size;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const uint8_t *TextString::GetData() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_pData;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t TextString::GetSize() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_size;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void TextString::Reset()
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void TextString::Clear()
{
if (0 != m_allocatedSize)
{
std::free(m_pData);
m_allocatedSize = 0;
}
m_pData = m_reservedBuffer;
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline CxxYZ::string_view TextString::ToStringView() const
{
if (IsInitialized())
return CxxYZ::string_view(reinterpret_cast<const char *>(m_pData), m_size);
else
return CxxYZ::string_view(GetNotInitializedString());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t TextString::GetSerializedLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedLength(m_size);
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t TextString::GetSerializedBodyLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedBodyLength(m_size);
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t TextString::GetMaxSerializedLength(const size_t size)
{
return (sizeof(uint8_t) + GetMaxSerializedBodyLength(size));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t TextString::GetMaxSerializedBodyLength(const size_t size)
{
return size;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool TextString::IsValidSerializedBodyLength(const size_t serializedBodyLength)
{
return ((serializedBodyLength > 0) && (serializedBodyLength <= UINT8_MAX));
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private Template specialization to map from FIELD_TYPE_TEXT_STRING to TextString class.
template<>
class FieldTypeToClass<FIELD_TYPE_TEXT_STRING>
{
public:
typedef TextString Type;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_TEXT_STRING_H)
File diff suppressed because it is too large. Load diff
@@ -1,418 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/TimeCommon.h
*
* @brief Header file for the common time classes and functions.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_TIME_COMMON_H)
#define ACTIV_BASE_FIELD_TYPES_TIME_COMMON_H
#include "ActivMiddleware/ActivBase/External.h"
//! Activ namespace.
namespace Activ
{
//! TimeCommon namespace.
namespace TimeCommon
{
//! The Julian day number at the unix epoch (1970-01-01).
static const int32_t JULIAN_DAYS_AT_UNIX_EPOCH = 2440588;
// ---------------------------------------------------------------------------------------------------------------------------------
//! Resolution enumeration. Values are Time serialized lengths for the resolution. Used as an optimization in Time.
#if (ACTIV_CPLUSPLUS >= ACTIV_CPLUSPLUS_11)
enum Resolution : uint8_t
#else
enum Resolution
#endif
{
RESOLUTION_UNKNOWN = 0,
RESOLUTION_SECOND = 3,
RESOLUTION_MILLISECOND = 4,
RESOLUTION_MICROSECOND = 5,
RESOLUTION_NANOSECOND = 7
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Get a string representation of a resolution.
ACTIV_BASE_API String ResolutionToString(const Resolution resolution);
// ---------------------------------------------------------------------------------------------------------------------------------
//! Base class for all super-second ResolutionTraits.
class ResolutionTraitsSuperSecondBase
{
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Base class for all sub-second ResolutionTraits.
class ResolutionTraitsSubSecondBase
{
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Resolution traits class.
template<Resolution RESOLUTION>
class ResolutionTraits;
// ---------------------------------------------------------------------------------------------------------------------------------
//! Second resolution traits specialization.
template<>
class ResolutionTraits<RESOLUTION_SECOND> : public ResolutionTraitsSuperSecondBase
{
public:
typedef uint32_t UnsignedType;
static const Resolution RESOLUTION = RESOLUTION_SECOND;
static const size_t SERIALIZED_LENGTH = RESOLUTION;
static const uint32_t NUMBER_PER_SECOND = 1;
static const uint32_t NUMBER_PER_DAY = 86400;
static const uint32_t MILLISECONDS_PER_UNIT = 1000;
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Millisecond resolution traits specialization.
template<>
class ResolutionTraits<RESOLUTION_MILLISECOND> : public ResolutionTraitsSubSecondBase
{
public:
typedef ResolutionTraits<RESOLUTION_SECOND> PARENT;
typedef uint32_t UnsignedType;
static const Resolution RESOLUTION = RESOLUTION_MILLISECOND;
static const size_t SERIALIZED_LENGTH = RESOLUTION;
static const uint32_t NUMBER_PER_SECOND = 1000;
static const uint32_t NUMBER_PER_DAY = NUMBER_PER_SECOND * ResolutionTraits<RESOLUTION_SECOND>::NUMBER_PER_DAY;
static const uint32_t MILLISECONDS_PER_UNIT = 1;
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Microsecond resolution traits specialization.
template<>
class ResolutionTraits<RESOLUTION_MICROSECOND> : public ResolutionTraitsSubSecondBase
{
public:
typedef ResolutionTraits<RESOLUTION_MILLISECOND> PARENT;
typedef uint64_t UnsignedType;
static const Resolution RESOLUTION = RESOLUTION_MICROSECOND;
static const size_t SERIALIZED_LENGTH = RESOLUTION;
static const uint32_t NUMBER_PER_MILLISECOND = 1000;
static const uint64_t NUMBER_PER_SECOND = NUMBER_PER_MILLISECOND * ResolutionTraits<RESOLUTION_MILLISECOND>::NUMBER_PER_SECOND;
static const uint64_t NUMBER_PER_DAY = NUMBER_PER_SECOND * ResolutionTraits<RESOLUTION_SECOND>::NUMBER_PER_DAY;
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Nanosecond resolution traits specialization.
template<>
class ResolutionTraits<RESOLUTION_NANOSECOND> : public ResolutionTraitsSubSecondBase
{
public:
typedef ResolutionTraits<RESOLUTION_MICROSECOND> PARENT;
typedef uint64_t UnsignedType;
static const Resolution RESOLUTION = RESOLUTION_NANOSECOND;
static const size_t SERIALIZED_LENGTH = RESOLUTION;
static const uint32_t NUMBER_PER_MICROSECOND = 1000;
static const uint32_t NUMBER_PER_MILLISECOND =
NUMBER_PER_MICROSECOND * ResolutionTraits<RESOLUTION_MICROSECOND>::NUMBER_PER_MILLISECOND;
static const uint64_t NUMBER_PER_SECOND = NUMBER_PER_MILLISECOND * ResolutionTraits<RESOLUTION_MILLISECOND>::NUMBER_PER_SECOND;
static const uint64_t NUMBER_PER_DAY = NUMBER_PER_SECOND * ResolutionTraits<RESOLUTION_SECOND>::NUMBER_PER_DAY;
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Days class.
class Days : public ResolutionTraitsSuperSecondBase
{
public:
/**
* @brief Constructor.
*
* @param value the value.
*/
explicit Days(const int32_t value) :
m_value(value)
{
}
static const uint32_t NUMBER_PER_DAY = 1;
static const uint32_t DAYS_PER_UNIT = 1;
static const uint32_t HOURS_PER_UNIT = DAYS_PER_UNIT * 24;
static const uint32_t MINUTES_PER_UNIT = HOURS_PER_UNIT * 60;
static const uint32_t SECONDS_PER_UNIT = MINUTES_PER_UNIT * 60;
static const uint64_t MILLISECONDS_PER_UNIT = SECONDS_PER_UNIT * 1000;
static const uint64_t MICROSECONDS_PER_UNIT = MILLISECONDS_PER_UNIT * 1000;
const int32_t m_value;
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Hours class.
class Hours : public ResolutionTraitsSuperSecondBase
{
public:
/**
* @brief Constructor.
*
* @param value the value.
*/
explicit Hours(const int32_t value) :
m_value(value)
{
}
static const uint32_t NUMBER_PER_DAY = 24;
static const uint32_t HOURS_PER_UNIT = 1;
static const uint32_t MINUTES_PER_UNIT = HOURS_PER_UNIT * 60;
static const uint32_t SECONDS_PER_UNIT = MINUTES_PER_UNIT * 60;
static const uint64_t MILLISECONDS_PER_UNIT = SECONDS_PER_UNIT * 1000;
static const uint64_t MICROSECONDS_PER_UNIT = MILLISECONDS_PER_UNIT * 1000;
const int32_t m_value;
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Minutes class.
class Minutes : public ResolutionTraitsSuperSecondBase
{
public:
/**
* @brief Constructor.
*
* @param value the value.
*/
explicit Minutes(const int32_t value) :
m_value(value)
{
}
static const uint32_t NUMBER_PER_HOUR = 60;
static const uint32_t NUMBER_PER_DAY = NUMBER_PER_HOUR * Hours::NUMBER_PER_DAY;
static const uint32_t MINUTES_PER_UNIT = 1;
static const uint32_t SECONDS_PER_UNIT = MINUTES_PER_UNIT * 60;
static const uint64_t MILLISECONDS_PER_UNIT = SECONDS_PER_UNIT * 1000;
static const uint64_t MICROSECONDS_PER_UNIT = MILLISECONDS_PER_UNIT * 1000;
const int32_t m_value;
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Seconds class.
class Seconds : public ResolutionTraits<RESOLUTION_SECOND>
{
public:
/**
* @brief Constructor.
*
* @param value the value.
*/
explicit Seconds(const int64_t value) :
m_value(value)
{
}
static const uint32_t NUMBER_PER_MINUTE = 60;
static const uint32_t NUMBER_PER_HOUR = NUMBER_PER_MINUTE * Minutes::NUMBER_PER_HOUR;
static const uint32_t SECONDS_PER_UNIT = 1;
static const uint64_t MILLISECONDS_PER_UNIT = SECONDS_PER_UNIT * 1000;
static const uint64_t MICROSECONDS_PER_UNIT = MILLISECONDS_PER_UNIT * 1000;
ACTIV_BOOST_STATIC_ASSERT(NUMBER_PER_DAY == (NUMBER_PER_HOUR * Hours::NUMBER_PER_DAY));
const int64_t m_value;
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Milliseconds class.
class Milliseconds : public ResolutionTraits<RESOLUTION_MILLISECOND>
{
public:
/**
* @brief Constructor.
*
* @param value the value.
*/
explicit Milliseconds(const int64_t value) :
m_value(value)
{
}
/**
* @brief Convert a millisecond duration to a string.
*
* @param duration the number of milliseconds.
*
* @return string containing the formatted duration.
*/
ACTIV_BASE_API static const String DurationToString(const uint64_t duration);
static const uint32_t NUMBER_PER_MINUTE = NUMBER_PER_SECOND * Seconds::NUMBER_PER_MINUTE;
static const uint32_t NUMBER_PER_HOUR = NUMBER_PER_MINUTE * Minutes::NUMBER_PER_HOUR;
static const uint64_t MILLISECONDS_PER_UNIT = 1;
static const uint64_t MICROSECONDS_PER_UNIT = MILLISECONDS_PER_UNIT * 1000;
ACTIV_BOOST_STATIC_ASSERT(NUMBER_PER_DAY == (NUMBER_PER_HOUR * Hours::NUMBER_PER_DAY));
const int64_t m_value;
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Microseconds class.
class Microseconds : public ResolutionTraits<RESOLUTION_MICROSECOND>
{
public:
/**
* @brief Constructor.
*
* @param value the value.
*/
explicit Microseconds(const int64_t value) :
m_value(value)
{
}
static const uint64_t NUMBER_PER_MINUTE = NUMBER_PER_SECOND * Seconds::NUMBER_PER_MINUTE; ///< The number per minute.
static const uint64_t NUMBER_PER_HOUR = NUMBER_PER_MINUTE * Minutes::NUMBER_PER_HOUR; ///< The number per hour.
static const uint64_t MICROSECONDS_PER_UNIT = 1;
ACTIV_BOOST_STATIC_ASSERT(NUMBER_PER_DAY == (NUMBER_PER_HOUR * static_cast<uint64_t>(Hours::NUMBER_PER_DAY)));
const int64_t m_value;
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Nanoseconds class.
class Nanoseconds : public ResolutionTraits<RESOLUTION_NANOSECOND>
{
public:
/**
* @brief Constructor.
*
* @param value the value.
*/
explicit Nanoseconds(const int64_t value) :
m_value(value)
{
}
static const uint64_t NUMBER_PER_MINUTE = NUMBER_PER_SECOND * Seconds::NUMBER_PER_MINUTE; ///< The number per minute.
static const uint64_t NUMBER_PER_HOUR = NUMBER_PER_MINUTE * Minutes::NUMBER_PER_HOUR; ///< The number per hour.
ACTIV_BOOST_STATIC_ASSERT(NUMBER_PER_DAY == (NUMBER_PER_HOUR * static_cast<uint64_t>(Hours::NUMBER_PER_DAY)));
const int64_t m_value;
};
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Convert between resolutions where the destination resolution is greater than or equal to the source.
*
* @tparam SOURCE the resolution of @a value.
* @tparam TARGET the resolution of the returned value.
* @tparam T the type of @a value.
*
* @param value the value to convert.
*
* @return the converted value.
*/
template<typename SOURCE, typename TARGET, typename T>
static typename Boost::enable_if_c<(TARGET::NUMBER_PER_SECOND > SOURCE::NUMBER_PER_SECOND), T>::type
ConvertResolution(const T value)
{
ACTIV_BOOST_STATIC_ASSERT(Boost::is_integral<T>::value);
ACTIV_BOOST_STATIC_ASSERT(
(TARGET::NUMBER_PER_SECOND / SOURCE::NUMBER_PER_SECOND) < static_cast<uint64_t>(Boost::integer_traits<T>::const_max));
return value * static_cast<T>(TARGET::NUMBER_PER_SECOND / SOURCE::NUMBER_PER_SECOND);
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Convert between resolutions where the destination resolution is less than the source.
*
* @tparam SOURCE the resolution of @a value.
* @tparam TARGET the resolution of the returned value.
* @tparam T the type of @a value.
*
* @param value the value to convert.
*
* @return the converted value.
*/
template<typename SOURCE, typename TARGET, typename T>
static typename Boost::enable_if_c<(TARGET::NUMBER_PER_SECOND <= SOURCE::NUMBER_PER_SECOND), T>::type
ConvertResolution(const T value)
{
ACTIV_BOOST_STATIC_ASSERT(Boost::is_integral<T>::value);
ACTIV_BOOST_STATIC_ASSERT(
(SOURCE::NUMBER_PER_SECOND / TARGET::NUMBER_PER_SECOND) < static_cast<uint64_t>(Boost::integer_traits<T>::const_max));
return value / static_cast<T>(SOURCE::NUMBER_PER_SECOND / TARGET::NUMBER_PER_SECOND);
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get sub-second component.
*
* @tparam RESOLUTION the resolution of @a value.
* @tparam T the type of @a value.
*
* @param value the value to get the sub-second component for.
*
* @return the sub-second component of @a value
*/
template<typename RESOLUTION, typename T>
static T GetSubSecondComponent(const T value)
{
ACTIV_BOOST_STATIC_ASSERT(Boost::is_integral<T>::value);
ACTIV_BOOST_STATIC_ASSERT(RESOLUTION::NUMBER_PER_SECOND < static_cast<uint64_t>(Boost::integer_traits<T>::const_max));
return value % static_cast<T>(RESOLUTION::NUMBER_PER_SECOND);
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get resolution component. For a nanosecond value of 123456789 will return 789.
*
* @tparam RESOLUTION the resolution of @a value.
*
* @param value the value to get the component of.
*
* @return the resolution component of @a value
*/
template<typename RESOLUTION>
static uint32_t GetResolutionComponent(const uint32_t value)
{
ACTIV_BOOST_STATIC_ASSERT((RESOLUTION::NUMBER_PER_SECOND / RESOLUTION::PARENT::NUMBER_PER_SECOND) <
Boost::integer_traits<uint32_t>::const_max);
return value % static_cast<uint32_t>(RESOLUTION::NUMBER_PER_SECOND / RESOLUTION::PARENT::NUMBER_PER_SECOND);
}
} // namespace TimeCommon
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_TIME_COMMON_H)
@@ -1,144 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/TimeHelper.h
*
* @brief Header file for the time helper class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_TIME_HELPER_H)
#define ACTIV_BASE_FIELD_TYPES_TIME_HELPER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/DateTime.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Time.h"
#include "ActivMiddleware/ActivBase/MessageBuilder.h"
#include "ActivMiddleware/ActivBase/MessageValidator.h"
#include "ActivMiddleware/Misc/BitFields.h"
//! Activ namespace.
namespace Activ
{
//! Time helper class.
class TimeHelper
{
public:
//! Nanosecond encoding bitmap.
class NanosecondEncodingBitmap : public Bitmap<48, LsbOrigin>
{
public:
typedef BitField<NanosecondEncodingBitmap, 30> Nanoseconds;
typedef BitField<Nanoseconds, 17> Seconds;
typedef BitField<Seconds, 1> Unused;
};
/**
* @brief Serialize time to non-standard six byte format. Assumes parameters have been pre-validated.
*
* Note: this format is incompatible with all deserialize functions other then DeserializeSixByteFormat().
*
* @param secondsInDay
* @param nanosecondsInSecond
* @param messageBuilder
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval STATUS_CODE_HEAP_EMPTY
*/
static StatusCode SerializeSixByteFormat(const uint32_t secondsInDay, const uint32_t nanosecondsInSecond,
MessageBuilder &messageBuilder);
/**
* @brief Serialize time to non-standard six byte format.
*
* Note: this format is incompatible with all deserialize functions other then SerializeSixByteFormat().
*
* @param time
* @param messageBuilder
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval STATUS_CODE_HEAP_EMPTY
*/
static StatusCode SerializeSixByteFormat(const Time &time, MessageBuilder &messageBuilder);
/**
* @brief Deserialize nanoseconds from six bytes.
*
* Note: this function can only be used to deserialize a time object serialized with SerializeSixByteFormat().
*
* @param time
* @param messageValidator
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval STATUS_CODE_HEAP_EMPTY
*/
static StatusCode DeserializeSixByteFormat(Time &time, MessageValidator &messageValidator);
//! Get Nanosecond encoding header.
static uint8_t GetNanosecondHeader();
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode TimeHelper::SerializeSixByteFormat(const uint32_t secondsInDay, const uint32_t nanosecondsInSecond,
MessageBuilder &messageBuilder)
{
assert(secondsInDay < Time::Seconds::NUMBER_PER_DAY);
assert(nanosecondsInSecond < Time::Nanoseconds::NUMBER_PER_SECOND);
ACTIV_BOOST_STATIC_ASSERT(BitsToMinimumBytes<NanosecondEncodingBitmap::numberOfBits>::value == 6);
NanosecondEncodingBitmap::Type bitmap(0);
NanosecondEncodingBitmap::Seconds::Set(bitmap, secondsInDay);
NanosecondEncodingBitmap::Nanoseconds::Set(bitmap, nanosecondsInSecond);
return messageBuilder.Append<MessageBuilder::ENDIAN_BIG,
BitsToMinimumBytes<NanosecondEncodingBitmap::numberOfBits>::value>(bitmap);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode TimeHelper::SerializeSixByteFormat(const Time &time, MessageBuilder &messageBuilder)
{
if (ACTIV_UNLIKELY(!time.IsInitialized()))
return STATUS_CODE_NOT_INITIALIZED;
ACTIV_BOOST_STATIC_ASSERT(BitsToMinimumBytes<NanosecondEncodingBitmap::numberOfBits>::value == 6);
NanosecondEncodingBitmap::Type bitmap(0);
NanosecondEncodingBitmap::Seconds::Set(bitmap, time.InternalGetTotal<Time::Seconds>());
NanosecondEncodingBitmap::Nanoseconds::Set(bitmap, time.InternalGetSubSecond<Time::Nanoseconds>());
return messageBuilder.Append<MessageBuilder::ENDIAN_BIG,
BitsToMinimumBytes<NanosecondEncodingBitmap::numberOfBits>::value>(bitmap);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode TimeHelper::DeserializeSixByteFormat(Time &time, MessageValidator &messageValidator)
{
NanosecondEncodingBitmap::Type bitmap(0);
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=,
(messageValidator.ValidateBinaryIntegral<BitsToMinimumBytes<NanosecondEncodingBitmap::numberOfBits>::value,
MessageValidator::ENDIAN_BIG>(bitmap)));
assert(NanosecondEncodingBitmap::Seconds::GetShifted(bitmap) < Time::Seconds::NUMBER_PER_DAY);
assert(NanosecondEncodingBitmap::Nanoseconds::GetShifted(bitmap) < Time::Nanoseconds::NUMBER_PER_SECOND);
// Use Set to ensure the correct resolution is set.
return time.SetT<Time::Nanoseconds>(NanosecondEncodingBitmap::Seconds::GetShifted(bitmap),
NanosecondEncodingBitmap::Nanoseconds::GetShifted(bitmap));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint8_t TimeHelper::GetNanosecondHeader()
{
return Time::NANOSECOND_ENCODING_HEADER;
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_TIME_HELPER_H)
@@ -1,832 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FieldTypes/UInt.h
*
* @brief Header file for the unsigned integer class.
*/
#if (!defined ACTIV_BASE_FIELD_TYPES_UINT_H)
#define ACTIV_BASE_FIELD_TYPES_UINT_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/IFieldType.h"
#include "ActivMiddleware/ActivBase/MessageBuilder.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/Misc/MemoryHelper.h"
//! Activ namespace.
namespace Activ
{
class Rational;
class SInt;
//! @private
template<typename T>
class SerializeValueLengthAndBodyHelper;
// ---------------------------------------------------------------------------------------------------------------------------------
//! Unsigned integer class.
class UInt ACTIV_FINAL : public IFieldType
{
public:
static const FieldType FIELD_TYPE = FIELD_TYPE_UINT; ///< The field type.
using IFieldType::FromString;
using IFieldType::Serialize;
using IFieldType::SerializeBody;
using IFieldType::SerializeLengthAndBody;
using IFieldType::Deserialize;
using IFieldType::DeserializeBody;
using IFieldType::DeserializeLengthAndBody;
//! Default constructor.
UInt();
/**
* @brief Constructor.
*
* @param value the value.
*/
UInt(const uint64_t value);
//! Destructor.
virtual ~UInt() ACTIV_OVERRIDE;
/**
* @brief Equality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator==(const UInt &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator!=(const UInt &rhs) const;
/**
* @brief Less than operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator<(const UInt &rhs) const;
/**
* @brief Less than or equal to operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator<=(const UInt &rhs) const;
/**
* @brief Greater than operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator>(const UInt &rhs) const;
/**
* @brief Greater than or equal to operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator>=(const UInt &rhs) const;
/**
* @brief Addition assignment operator.
*
* @param rhs the value to add to this object.
*
* @return a reference to this object.
*
* @throw StatusCodeException
*/
UInt& operator+=(const UInt &rhs);
/**
* @brief Subtraction assignment operator.
*
* @param rhs the value to subtract from this object.
*
* @return a reference to this object.
*
* @throw StatusCodeException
*/
UInt& operator-=(const UInt &rhs);
/**
* @brief Multiplication assignment operator.
*
* @param rhs the value to multiply this object by.
*
* @return a reference to this object.
*
* @throw StatusCodeException
*/
UInt& operator*=(const UInt &rhs);
/**
* @brief Division assignment operator.
*
* @param rhs the value to divide this object by.
*
* @return a reference to this object.
*
* @throw StatusCodeException
*/
UInt& operator/=(const UInt &rhs);
/**
* @brief Rational conversion operator.
*
* @throw StatusCodeException
*/
ACTIV_BASE_API operator const Rational() const;
/**
* @brief SInt conversion operator.
*
* @throw StatusCodeException
*/
ACTIV_BASE_API operator const SInt() const;
/**
* @brief Set a new value.
*
* @param value the value.
*
* @retval STATUS_CODE_SUCCESS
*/
StatusCode Set(const uint64_t value);
/**
* @brief Get the value.
*
* @param value the value.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
*/
StatusCode Get(uint64_t &value) const;
/**
* @brief Get the value.
*
* @return the value.
*
* @throw StatusCodeException
*/
uint64_t Get() const;
/**
* @brief Add.
*
* @param rhs the value to add to this object.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval STATUS_CODE_OUT_OF_RANGE
*/
ACTIV_BASE_API StatusCode Add(const UInt &rhs);
/**
* @brief Subtract.
*
* @param rhs the value to subtract from this object.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval STATUS_CODE_OUT_OF_RANGE
*/
ACTIV_BASE_API StatusCode Subtract(const UInt &rhs);
/**
* @brief Multiply.
*
* @param rhs the value to multiply this object by.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval STATUS_CODE_OUT_OF_RANGE
*/
ACTIV_BASE_API StatusCode Multiply(const UInt &rhs);
/**
* @brief Divide.
*
* @param rhs the value to divide this object by.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval STATUS_CODE_OUT_OF_RANGE
*/
ACTIV_BASE_API StatusCode Divide(const UInt &rhs);
virtual void Reset() ACTIV_OVERRIDE;
virtual void Clear() ACTIV_OVERRIDE;
/**
* @brief Compare.
*
* @param rhs the object to compare with.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API StatusCode Compare(const UInt &rhs, int &result) const;
ACTIV_BASE_API virtual StatusCode Compare(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Convert(const IFieldType * const pIFieldType) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode AppendAsString(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode FromString(MessageValidator &messageValidator) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual String GetFromStringFormat() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) ACTIV_OVERRIDE;
virtual size_t GetSerializedLength() const ACTIV_OVERRIDE;
virtual size_t GetSerializedBodyLength() const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode IsDifferent(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, bool &isDifferent) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual size_t GetMemoryUsage() const ACTIV_OVERRIDE;
/**
* @brief Get the maximum serialized length of the object.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object.
*/
static size_t GetMaxSerializedLength(const size_t size);
/**
* @brief Get the maximum serialized length of the object's body.
*
* @param size the size of the data.
*
* @return the maximum serialized length of the object's body.
*/
static size_t GetMaxSerializedBodyLength(const size_t size);
/**
* @brief Compare two objects serialized bodies.
*
* @param pLhsSerializedBody the buffer containing the lhs serialized version of the object's body in.
* @param lhsSerializedBodyLength the lhs serialized body length.
* @param pRhsSerializedBody the buffer containing the rhs serialized version of the object's body in.
* @param rhsSerializedBodyLength the rhs serialized body length.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API static StatusCode Compare(const void * const pLhsSerializedBody, const size_t lhsSerializedBodyLength, const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result);
/**
* @brief Validate the serialized length and body.
*
* @param messageValidator the message validator.
* @param serializedBodyOffset the serialized body offset.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API static StatusCode ValidateSerializedLengthAndBody(MessageValidator &messageValidator, size_t &serializedBodyOffset, size_t &serializedBodyLength);
/**
* @brief Serialize a value's length and body into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param value the value to serialize.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
template<typename T>
static StatusCode SerializeValueLengthAndBody(MessageBuilder &messageBuilder, const T value);
/**
* @brief Is valid serialized body length.
*
* @param serializedBodyLength the serialized body length.
*
* @return whether the serialized body length is valid.
*/
static bool IsValidSerializedBodyLength(const size_t serializedBodyLength);
/**
* @brief Get a usage string for the format supported by FromString().
*
* @return String, may be empty.
*/
ACTIV_BASE_API static String FromStringFormat();
private:
/**
* @brief Serialize the object's body into the supplied data buffer.
*
* This will serialize to a fixed size buffer (GetMaxSerializedLength<T>()).
*
* @param pSerializedBody the buffer to store a serialized version of the object in.
*
* @retval STATUS_CODE_SUCCESS
*/
template <typename T> StatusCode SerializeBody(void *pSerializedBody) const;
/**
* @brief Deserialize the object's body from the supplied data buffer.
*
* This will deserialize from a fixed size buffer (GetMaxSerializedLength<T>()).
*
* @param pSerializedBody the buffer from which the object will be extracted.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_FORMAT
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval STATUS_CODE_OUT_OF_RANGE
*/
template <typename T> StatusCode DeserializeBody(const void * const pSerializedBody);
/**
* @brief Serialize a value's length and body into the supplied message builder to a given length (given by T) with
* a check for maximum serialized length.
*
* T is the smallest unsigned integral type which will hold the absolute value of the numerator.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param value
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
template<typename T>
static StatusCode InternalSerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength,
const T value);
/**
* @brief Serialize a value's length and body into the supplied message builder to a given length (given by T).
*
* T is the smallest unsigned integral type which will hold the absolute value of the numerator.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param value
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
template<typename T>
static StatusCode InternalSerializeLengthAndBody(MessageBuilder &messageBuilder, const T value);
//! Get the minimum size in bytes that could hold the current value.
size_t GetCompressedValueSize() const;
uint64_t m_value; ///< The value.
template<typename T>
friend class SerializeValueLengthAndBodyHelper;
#if (defined ACTIV_PLATFORM_WASM)
friend class Wasm::FieldTypeAccessor;
#endif
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline UInt::UInt() :
IFieldType(FIELD_TYPE)
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline UInt::UInt(const uint64_t value) :
IFieldType(FIELD_TYPE)
{
(void) Set(value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline UInt::~UInt()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool UInt::operator==(const UInt &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (0 == result);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool UInt::operator!=(const UInt &rhs) const
{
return !((*this) == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool UInt::operator<(const UInt &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (result < 0);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool UInt::operator<=(const UInt &rhs) const
{
return !((*this) > rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool UInt::operator>(const UInt &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (result > 0);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool UInt::operator>=(const UInt &rhs) const
{
return !((*this) < rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline UInt& UInt::operator+=(const UInt &rhs)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Add(rhs));
return (*this);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline UInt& UInt::operator-=(const UInt &rhs)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Subtract(rhs));
return (*this);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline UInt& UInt::operator*=(const UInt &rhs)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Multiply(rhs));
return (*this);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline UInt& UInt::operator/=(const UInt &rhs)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Divide(rhs));
return (*this);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode UInt::Set(const uint64_t value)
{
m_value = value;
m_isInitialized = true;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode UInt::Get(uint64_t &value) const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
return STATUS_CODE_NOT_INITIALIZED;
value = m_value;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint64_t UInt::Get() const
{
if (ACTIV_UNLIKELY(!IsInitialized()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return m_value;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void UInt::Reset()
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void UInt::Clear()
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t UInt::GetSerializedLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedLength(GetCompressedValueSize());
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t UInt::GetSerializedBodyLength() const
{
if (ACTIV_LIKELY(IsInitialized()))
return GetMaxSerializedBodyLength(GetCompressedValueSize());
else
return 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t UInt::GetMaxSerializedLength(const size_t size)
{
return GetMaxSerializedBodyLength(size);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t UInt::GetMaxSerializedBodyLength(const size_t size)
{
return size;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline StatusCode UInt::SerializeValueLengthAndBody(MessageBuilder &messageBuilder, const T value)
{
return SerializeValueLengthAndBodyHelper<T>()(messageBuilder, value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline StatusCode UInt::InternalSerializeLengthAndBody(MessageBuilder &messageBuilder, const T value)
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=,
messageBuilder.Append<MessageBuilder::ENDIAN_LITTLE>(static_cast<uint8_t>(sizeof(T))));
return messageBuilder.Append<MessageBuilder::ENDIAN_LITTLE>(value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool UInt::IsValidSerializedBodyLength(const size_t serializedBodyLength)
{
return ((GetMaxSerializedBodyLength(sizeof(uint64_t)) == serializedBodyLength) || (GetMaxSerializedBodyLength(sizeof(uint32_t)) == serializedBodyLength) || (GetMaxSerializedBodyLength(sizeof(uint16_t)) == serializedBodyLength) || (GetMaxSerializedBodyLength(sizeof(uint8_t)) == serializedBodyLength));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T> inline StatusCode UInt::SerializeBody(void *pSerializedBody) const
{
CopyValueToUnalignedPointer(pSerializedBody, HostToLittleEndianOrder(static_cast<T>(m_value)));
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T> inline StatusCode UInt::DeserializeBody(const void * const pSerializedBody)
{
return Set(static_cast<uint64_t>(LittleEndianToHostOrder(GetValueFromUnalignedPointer<T>(pSerializedBody))));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t UInt::GetCompressedValueSize() const
{
if (m_value <= Boost::integer_traits<uint8_t>::const_max)
return sizeof(uint8_t);
if (m_value <= Boost::integer_traits<uint16_t>::const_max)
return sizeof(uint16_t);
if (m_value <= Boost::integer_traits<uint32_t>::const_max)
return sizeof(uint32_t);
return sizeof(uint64_t);
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private
template<typename T>
class SerializeValueLengthAndBodyHelper
{
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private
template<>
class SerializeValueLengthAndBodyHelper<uint8_t>
{
public:
StatusCode operator()(MessageBuilder &messageBuilder, const uint8_t value)
{
return UInt::InternalSerializeLengthAndBody(messageBuilder, value);
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private
template<>
class SerializeValueLengthAndBodyHelper<uint16_t>
{
public:
StatusCode operator()(MessageBuilder &messageBuilder, const uint16_t value)
{
if (value <= Boost::integer_traits<uint8_t>::const_max)
return UInt::InternalSerializeLengthAndBody(messageBuilder, static_cast<uint8_t>(value));
else
return UInt::InternalSerializeLengthAndBody(messageBuilder, value);
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private
template<>
class SerializeValueLengthAndBodyHelper<uint32_t>
{
public:
StatusCode operator()(MessageBuilder &messageBuilder, const uint32_t value)
{
if (value <= Boost::integer_traits<uint8_t>::const_max)
return UInt::InternalSerializeLengthAndBody(messageBuilder, static_cast<uint8_t>(value));
else if (value <= Boost::integer_traits<uint16_t>::const_max)
return UInt::InternalSerializeLengthAndBody(messageBuilder, static_cast<uint16_t>(value));
else
return UInt::InternalSerializeLengthAndBody(messageBuilder, value);
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private
template<>
class SerializeValueLengthAndBodyHelper<uint64_t>
{
public:
StatusCode operator()(MessageBuilder &messageBuilder, const uint64_t value)
{
if (value <= Boost::integer_traits<uint8_t>::const_max)
return UInt::InternalSerializeLengthAndBody(messageBuilder, static_cast<uint8_t>(value));
else if (value <= Boost::integer_traits<uint16_t>::const_max)
return UInt::InternalSerializeLengthAndBody(messageBuilder, static_cast<uint16_t>(value));
else if (value <= Boost::integer_traits<uint32_t>::const_max)
return UInt::InternalSerializeLengthAndBody(messageBuilder, static_cast<uint32_t>(value));
else
return UInt::InternalSerializeLengthAndBody(messageBuilder, value);
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Addition operator for the unsigned integer object.
*
* @param lhs the left hand side value.
* @param rhs the right hand side value.
*
* @return an object containing the result of the operation.
*
* @throw StatusCodeException
*/
inline UInt operator+(const UInt &lhs, const UInt &rhs)
{
return UInt(lhs) += rhs;
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Subtraction operator for the unsigned integer object.
*
* @param lhs the left hand side value.
* @param rhs the right hand side value.
*
* @return an object containing the result of the operation.
*
* @throw StatusCodeException
*/
inline UInt operator-(const UInt &lhs, const UInt &rhs)
{
return UInt(lhs) -= rhs;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Multiplication operator for the unsigned integer object.
*
* @param lhs the left hand side value.
* @param rhs the right hand side value.
*
* @return an object containing the result of the operation.
*
* @throw StatusCodeException
*/
inline UInt operator*(const UInt &lhs, const UInt &rhs)
{
return UInt(lhs) *= rhs;
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Division operator for the unsigned integer object.
*
* @param lhs the left hand side value.
* @param rhs the right hand side value.
*
* @return an object containing the result of the operation.
*
* @throw StatusCodeException
*/
inline UInt operator/(const UInt &lhs, const UInt &rhs)
{
return UInt(lhs) /= rhs;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! @private Template specialization to map from FIELD_TYPE_UINT to UInt class.
template<>
class FieldTypeToClass<FIELD_TYPE_UINT>
{
public:
typedef UInt Type;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_FIELD_TYPES_UINT_H)
@@ -1,298 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/File.h
*
* @brief Header file for file class.
*/
#if (!defined ACTIV_BASE_FILE_H)
#define ACTIV_BASE_FILE_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/IFile.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief File class.
*/
class File ACTIV_FINAL : public IFile
{
ACTIV_BOOST_MOVABLE_BUT_NOT_COPYABLE(File)
public:
static const FileType FILE_TYPE = FILE_TYPE_NORMAL; ///< The file type.
//! Default constructor.
ACTIV_BASE_API File();
/**
* @brief Move constructor.
*
* @param rhs transfer ownership of the underlying file managed by @a rhs to this.
*/
File(ACTIV_BOOST_RV_REF(File) rhs) :
IFile(ACTIV_BOOST_MOVE_BASE(IFile, rhs))
{
// Inline here for G++.
}
/**
* @brief Move assignment operator.
*
* Transfer ownership of a file from another IFile object to this.
*
* If this object has a file open, it is closed. The underlying file associated with rhs is transferred to this object,
* and no file is then associated with rhs.
*
* @param rhs the file to transfer to this object.
*
* @return *this
*/
File &operator=(ACTIV_BOOST_RV_REF(File) rhs)
{
// Inline here for G++.
if (this != &rhs)
IFile::operator=(ACTIV_BOOST_MOVE_BASE(IFile, rhs));
return *this;
}
using IFile::GetSize;
using IFile::GetLastWriteDateTime;
using IFile::GetCreationDateTime;
using IFile::GetLastAccessDateTime;
/**
* @brief Copy a file.
*
* @param sourceFileName the name of the existing file.
* @param targetFileName the name of the new file.
* @param replaceExisting whether an existing file should be overwritten.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval ...
*/
ACTIV_BASE_API static StatusCode Copy(const String &sourceFileName, const String &targetFileName, bool replaceExisting = false);
/**
* @brief Remove a file.
*
* @param fileName the file to remove.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode Remove(const String &fileName);
/**
* @brief Rename a file.
*
* @param sourceFileName the name of the existing file.
* @param targetFileName the name of the new file.
* @param replaceExisting whether an existing file should be overwritten.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode Rename(const String &sourceFileName, const String &targetFileName,
bool replaceExisting = false);
/**
* @brief Get the size of a file.
*
* @param fileName the file name.
* @param size the size of the file.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval STATUS_CODE_FAILURE
* @retval ...
*/
ACTIV_BASE_API static StatusCode GetSize(const String &fileName, uint64_t &size);
/**
* @brief Get the last write date time of a file.
*
* @param fileName the file name.
* @param tm reference to a tm structure to receive the UTC date / time.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API static StatusCode GetLastWriteDateTime(const String &fileName, std::tm &tm);
/**
* @brief Get the creation date time of a file.
*
* @param fileName the file name.
* @param tm reference to a tm structure to receive the UTC date / time.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API static StatusCode GetCreationDateTime(const String &fileName, std::tm &tm);
/**
* @brief Get the last access date time of a file.
*
* @param fileName the file name.
* @param tm reference to a tm structure to receive the UTC date / time.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API static StatusCode GetLastAccessDateTime(const String &fileName, std::tm &tm);
/**
* @brief Does a file exist?
*
* @param fileName the file to find.
*
* @return whether the file exists.
*/
ACTIV_BASE_API static bool IsFound(const String &fileName);
/**
* @brief Is a path a directory?
*
* @param pathName path to check.
*
* @return boolean.
*/
ACTIV_BASE_API static bool IsDirectory(const String &pathName);
/**
* @brief Is a path absolute?
*
* @param pathName path to check.
*
* @return boolean.
*/
ACTIV_BASE_API static bool IsAbsolutePath(const String &pathName);
//! Get the end of line characters for this platform.
ACTIV_BASE_API static const String &GetEndOfLine();
//! Get directory separator character for this platform.
ACTIV_BASE_API static char GetDirectorySeparator();
/**
* @brief Get temporary directory path.
*
* Note the returned path may or may not contain a trailing directory separator,
* so use File::MakePath() to construct the path of a file in the temporary directory.
*
* @return Temporary directory path.
*/
ACTIV_BASE_API static String GetTemporaryPath();
/**
* @brief Create a path from directory and file name.
*
* @param directory the directory.
* @param fileName the file name.
*
* @return Full pathname.
*/
ACTIV_BASE_API static String MakePath(const String &directory, const String &fileName);
/**
* @brief Create an absolute path from a relative one.
*
* @param path The relative path.
*
* @return Absolute pathname with no trailing directory separator, unless a root directory.
*/
ACTIV_BASE_API static String MakeAbsolutePath(const String &path);
/**
* @brief Get the directory and filename from a path.
*
* SplitPath() will not append a trailing directory separator to @a directory unless it is a root directory. Some examples:
* \verbatim
path directory fileName
file file
c: c:
c:\ c:\
\ \
\file \ file
.\file . file
..\..\ ..\..
c:\dir1\dir2\file c:\dir1\dir2 file
dir1\dir2\file dir1\dir2 file
/ /
/file / file
./file . file
../../ ../..
/dir1/dir2/file /dir1/dir2 file
dir1/dir2/file dir1/dir2 file
~ ~
~/file ~ file
~/dir/ ~/dir
~/dir/file ~/dir file
~user ~user
~user/file ~user file
~user/dir/ ~user/dir
~user/dir/file ~user/dir file
\endverbatim
* SplitPath() does not do any checking that the trailing path component is in fact a file.
* For instance, the following is possible:
* \verbatim
/dir1/dir2/dir3 /dir1/dir2 dir3
\endverbatim
* @param path the path to split.
* @param directory to receive the directory component of @a path.
* @param fileName to receive the file name component of @a path.
*/
ACTIV_BASE_API static void SplitPath(const String &path, String &directory, String &fileName);
/**
* @brief Expand ~ in a path.
*
* @param path the path to expand.
*
* @return The path with a leading ~ expanded, if possible.
*/
ACTIV_BASE_API static String ExpandPath(const String &path);
/**
* @brief Search the current path for a file.
*
* NB the current directory is always included in the search.
*
* @param fileName the file (without any directory component) to search for.
* @param fullyQualifiedFileName reference to a string to receive the path + filename of the found file.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval STATUS_CODE_FAILURE
* @retval ...
*/
ACTIV_BASE_API static StatusCode SearchPath(const String &fileName, String &fullyQualifiedFileName);
/**
* @brief Is the provided path name just a file name?
*
* @param pathName path to check.
*
* @return true if \a pathName is just a file name.
*/
ACTIV_BASE_API static bool IsFileNameOnly(const String &pathName);
protected:
ACTIV_BASE_API virtual StatusCode Decode(void *pBuffer, const size_t nBytesToRead, size_t &nBytesRead) ACTIV_OVERRIDE;
ACTIV_BASE_API virtual StatusCode Encode(const void *pBuffer, const size_t nBytesToWrite, size_t &nBytesWritten) ACTIV_OVERRIDE;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_FILE_H)
@@ -1,77 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FileMappedMemoryFactory.h
*
* @brief Header file for the file mapped memory factory class.
*/
#if (!defined ACTIV_BASE_FILE_MAPPED_MEMORY_FACTORY_H)
#define ACTIV_BASE_FILE_MAPPED_MEMORY_FACTORY_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/IFileMappedMemory.h"
#include "ActivMiddleware/ActivBase/Timeout.h"
#include "ActivMiddleware/Misc/Singleton.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief File mapped memory factory class.
*/
class FileMappedMemoryFactory : public Singleton<FileMappedMemoryFactory>
{
public:
/**
* @brief Create a memory mapped file that can be shared via name.
*
* @param fileName the name of the file to map into memory.
* @param size the size to the memory segment to be mapped.
* @param canShare flag indicating whether the memory mapped file can be shared.
* @param fileFlags flags to use when creating or opening the file.
* @param mappingFlags flags to use when creating the mapped memory segment.
*
* @return Pointer to an object providing an IFileMappedMemory interface.
*
* @throw Exception
*/
ACTIV_BASE_API IFileMappedMemory *Create(const String &fileName, const size_t size, const bool canShare,
const IFileMappedMemory::FileFlags::Type fileFlags = IFileMappedMemory::FileFlags::None(),
const IMappedMemory::MappingFlags::Type mappingFlags = IMappedMemory::MappingFlags::None());
/**
* @brief Open an existing memory mapped file.
*
* @param fileName the name of the file to map into memory.
* @param fileFlags flags to use when creating or opening the file.
* @param mappingFlags flags to use when creating the mapped memory segment.
* @param timeout object specifying how long to wait for the memory mapped file to exist, in ms.
*
* @return pointer to an object providing an IFileMappedMemory interface.
*
* @throw Exception
*/
ACTIV_BASE_API IFileMappedMemory *Open(const String &fileName,
const IFileMappedMemory::FileFlags::Type fileFlags = IFileMappedMemory::FileFlags::None(),
const IMappedMemory::MappingFlags::Type mappingFlags = IMappedMemory::MappingFlags::None(),
Timeout &timeout = Timeout::GetInfinite());
/**
* @brief Get a reference to the singleton instance.
*
* @return Reference.
*/
ACTIV_BASE_API static FileMappedMemoryFactory &GetInstance();
private:
/**
* @brief Default constructor.
*/
ACTIV_BASE_API FileMappedMemoryFactory();
friend class Singleton<FileMappedMemoryFactory>;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_FILE_MAPPED_MEMORY_FACTORY_H)
@@ -1,126 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/FileTypeHelper.h
*
* @brief Header file for the file type helper template class.
*/
#if (!defined ACTIV_BASE_FILE_TYPE_HELPER_H)
#define ACTIV_BASE_FILE_TYPE_HELPER_H
#include "File.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief FileTypeHelper class.
*
* A class that adds helper functions for a File class implementation in order to allow checking if a given file
* matches the file type.
*
* Implemented as a CRTP base class.
*
* @tparam FILE the codec type.
*/
template<typename FILE>
class FileTypeHelper : public IFile
{
ACTIV_BOOST_MOVABLE_BUT_NOT_COPYABLE(FileTypeHelper)
public:
/**
* @brief Check if the file matches the FILE format.
*
* @param fileName the name of the file.
*
* @return whether the file matches FILE.
*/
static bool IsFileType(const String &fileName);
/**
* @brief Check if the file matches the FILE format.
*
* @param file the file object.
*
* @return whether the file matches FILE.
*/
static bool IsFileType(IFile &file);
protected:
/**
* @brief Constructor.
*
* @param fileType the file type.
*/
explicit FileTypeHelper(FileType fileType);
/**
* @brief Move constructor.
*
* @param rhs transfer ownership of the underlying file managed by @a rhs to this.
*/
FileTypeHelper(ACTIV_BOOST_RV_REF(FileTypeHelper) rhs) :
IFile(ACTIV_BOOST_MOVE_BASE(IFile, rhs))
{
}
/**
* @brief Move assignment operator.
*
* Transfer ownership of a file from another ZlibFile object to this.
*
* If this object has a file open, it is closed. The underlying file associated with rhs is transferred to this object,
* and no file is then associated with rhs.
*
* @param rhs the file to transfer to this object.
*
* @return *this
*/
FileTypeHelper& operator=(ACTIV_BOOST_RV_REF(FileTypeHelper) rhs)
{
if (this != &rhs)
{
IFile::operator=(static_cast<ACTIV_BOOST_RV_REF(IFile)>(rhs));
}
return *this;
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename FILE>
FileTypeHelper<FILE>::FileTypeHelper(FileType fileType) :
IFile(fileType)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename FILE>
inline bool FileTypeHelper<FILE>::IsFileType(const String &fileName)
{
File file;
ACTIV_RETURN_RESULT_IF(STATUS_CODE_SUCCESS, !=, file.Open(fileName, File::AccessFlags::Read(), File::ShareFlags::Read() | File::ShareFlags::Write()));
return IsFileType(file);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename FILE>
inline bool FileTypeHelper<FILE>::IsFileType(IFile &file)
{
byte_t header[FILE::HEADER_SIZE];
size_t headerBytesRead;
ACTIV_RETURN_RESULT_IF(STATUS_CODE_SUCCESS, !=, file.Read(&header[0], FILE::HEADER_SIZE, headerBytesRead));
return FILE::IsFileType(&header[0], FILE::HEADER_SIZE);
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_FILE_TYPE_HELPER_H)
@@ -1,142 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/HighAccuracyWait.h
*
* @brief High accuracy wait function object.
*/
#if (!defined ACTIV_BASE_HIGH_ACCURACY_WAIT_H)
#define ACTIV_BASE_HIGH_ACCURACY_WAIT_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/IntervalTimer.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Do a smooth, high(er) accuracy wait.
*
* RETURN_TYPE the return type of the function operator and the wait function passed to it.
* TIMEOUT_RETURN_VALUE the value that indicated a timeout from the sleep function passed to the function operator.
*/
template<typename RETURN_TYPE, RETURN_TYPE TIMEOUT_RETURN_VALUE>
class HighAccuracyWait
{
public:
//! Infinite timeout constant.
static const uint64_t infiniteTimeout = Boost::integer_traits<uint64_t>::const_max;
/**
* @brief Function operator.
*
* The function will wait at least timeoutPeriod milliseconds, unless waitFn returns something other than
* TIMEOUT_RETURN_VALUE.
*
* May invoke the provided waitFn multiple times in order to achieve an accurate wait of the requested period.
*
* @param timeoutPeriod period to wait, in milliseconds.
* @param waitFn wait function object returning TIMEOUT_RETURN_VALUE if it times out. waitFn should take
* a uint64_t parameter with the *microseconds* to wait.
*
* @return TIMEOUT_RETURN_VALUE, or the value returned by waitFn if not TIMEOUT_RETURN_VALUE.
*/
template<typename SLEEP_FN>
const RETURN_TYPE operator()(const uint32_t timeoutPeriod, const SLEEP_FN &waitFn) const
{
const uint64_t maxSmoothWaitMicroseconds = 50000;
#if (defined ACTIV_PLATFORM_WINDOWS)
const uint64_t clockResolution = IntervalTimer::GetClockResolution();
#else
const uint64_t clockResolution = GetMaximum<uint64_t>(IntervalTimer::GetClockResolution(), 50);
#endif
const uint64_t halfClockResolution = clockResolution / 2;
const uint64_t startTimeStamp = IntervalTimer::GetTimeStamp();
const uint64_t targetTimeStamp = startTimeStamp + ((timeoutPeriod * IntervalTimer::GetFrequency()) / 1000);
uint64_t currentTimeStamp = startTimeStamp;
bool isDone = false;
size_t numberOfWaits = 0;
while (!isDone)
{
uint64_t thisTimeoutUs;
if (0 == timeoutPeriod)
{
// With a 0 timeout, we still want to wait/sleep at least once so don't break out immediately.
thisTimeoutUs = 0;
isDone = true;
}
#if (defined ACTIV_PLATFORM_WINDOWS)
else if ((1 == timeoutPeriod) && (0 == numberOfWaits))
{
// Initial wait must be of at least 1ms, otherwise we could be busy waiting a lot.
// Downside is 1 ms waits might not be particularly accurate, depending on the clock resolution.
thisTimeoutUs = 1000;
}
#endif
else if (ACTIV_WAIT_INFINITE == timeoutPeriod)
{
thisTimeoutUs = infiniteTimeout;
}
else
{
if (ACTIV_LIKELY(targetTimeStamp >= startTimeStamp))
{
if ((currentTimeStamp >= targetTimeStamp) || (currentTimeStamp < startTimeStamp))
break;
}
else
{
if ((currentTimeStamp >= targetTimeStamp) && (currentTimeStamp < startTimeStamp))
break;
}
// Remaining period in microseconds.
thisTimeoutUs = ((targetTimeStamp - currentTimeStamp) * 1000000) / IntervalTimer::GetFrequency();
if (thisTimeoutUs < maxSmoothWaitMicroseconds)
{
const uint64_t resolutionRemainder = (thisTimeoutUs % clockResolution);
if (resolutionRemainder >= halfClockResolution)
{
if (thisTimeoutUs >= clockResolution)
thisTimeoutUs -= clockResolution;
else if (numberOfWaits > 0)
thisTimeoutUs = 0;
}
else
{
if (thisTimeoutUs >= halfClockResolution)
thisTimeoutUs -= halfClockResolution;
else if (numberOfWaits > 0)
thisTimeoutUs = 0;
}
}
else
{
// Quite a big wait. Just wait the whole period - super accuracy not as important with long waits.
}
}
const RETURN_TYPE returnValue = waitFn(thisTimeoutUs);
++numberOfWaits;
if (TIMEOUT_RETURN_VALUE != returnValue)
return returnValue;
currentTimeStamp = IntervalTimer::GetTimeStamp();
}
return TIMEOUT_RETURN_VALUE;
}
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_HIGH_ACCURACY_WAIT_H)
@@ -1,597 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Http.h
*
* @brief Header file for various HTTP-related classes.
*/
#if (!defined ACTIV_BASE_HTTP_H)
#define ACTIV_BASE_HTTP_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/CxxYZ/unordered_map.h"
#include "ActivMiddleware/Misc/FunctionObjects.h"
#include "ActivMiddleware/Misc/Singleton.h"
#include "ActivMiddleware/Misc/StlHelper.h"
#include <vector>
//! Activ namespace.
namespace Activ
{
// Forward references of some HTTP classes.
template<typename T>
class HttpValidatorBase;
class HttpRequest;
class HttpResponse;
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief List of HTTP verbs.
*/
#define ACTIV_HTTP_VERB_LIST(d) \
d(HEAD) \
d(GET) \
d(POST) \
d(PUT) \
d(DELETE) \
d(TRACE) \
d(OPTIONS) \
d(CONNECT)
#define ACTIV_MAKE_HTTP_VERB_ENUM_VALUE(v) HTTP_VERB_##v,
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Enumeration of HTTP verbs.
*/
enum HttpVerb
{
ACTIV_HTTP_VERB_LIST(ACTIV_MAKE_HTTP_VERB_ENUM_VALUE)
NUMBER_OF_HTTP_VERBS,
HTTP_VERB_UNKNOWN = -1
};
#undef ACTIV_MAKE_HTTP_VERB_ENUM_VALUE
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Enumeration of HTTP status codes.
*/
enum HttpStatusCode
{
HTTP_STATUS_CODE_UNDEFINED = 0,
// Success codes.
HTTP_STATUS_CODE_OK = 200,
// Client error codes.
HTTP_STATUS_CODE_BAD_REQUEST = 400,
HTTP_STATUS_CODE_UNAUTHORIZED = 401,
HTTP_STATUS_CODE_NOT_FOUND = 404,
// Server error codes.
HTTP_STATUS_CODE_INTERNAL_SERVER_ERROR = 500
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief HTTP helper singleton for verb mappings, etc.
*/
class HttpHelper : private Singleton<HttpHelper>
{
public:
/**
* @brief Get the HttpVerb from a string.
*
* @param str
*
* @return HttpVerb.
*/
HttpVerb StringToHttpVerb(const String &str) const;
/**
* @brief Get the HttpVerb from a pointer and length.
*
* @param pStr
* @param length
*
* @return HttpVerb.
*/
HttpVerb StringToHttpVerb(const char *pStr, const size_t length) const;
/**
* @brief Get a string representation of an HttpVerb.
*
* @param httpVerb
*
* @return String.
*/
const String &HttpVerbToString(const HttpVerb httpVerb) const;
/**
* @brief Singleton accessor.
*
* @return HttpHelper reference.
*/
ACTIV_BASE_API static HttpHelper &GetInstance();
/**
* @brief Get a standard http success (200) header for html content.
*
* @param bodyLength the length of the http response body.
*
* @return String.
*/
ACTIV_BASE_API static String GetStandardHtmlSuccessHttpHeader(const size_t bodyLength);
/**
* @brief Get a standard http not found (404) header.
*
* @param bodyLength the length of the http response body.
*
* @return String.
*/
ACTIV_BASE_API static String GetStandardNotFoundHttpHeader(const size_t bodyLength);
/**
* @brief Get a standard http internal server error (500) header.
*
* @param bodyLength the length of the http response body.
*
* @return String.
*/
ACTIV_BASE_API static String GetStandardInternalServerErrorHttpHeader(const size_t bodyLength);
private:
typedef std::vector<String> VerbNameList;
typedef CxxYZ::unordered_map<size_t, HttpVerb> VerbMap;
/**
* @brief Constructor.
*/
HttpHelper();
/**
* @brief Make list of verb strings.
*/
static const VerbNameList MakeVerbNameList();
/**
* @brief Make a map from verb-hash to string.
*/
static const VerbMap MakeVerbMap(const VerbNameList &verbNameList);
const VerbNameList m_verbNameList;
const VerbMap m_verbMap;
friend class Singleton<HttpHelper>;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline HttpVerb HttpHelper::StringToHttpVerb(const String &str) const
{
return StringToHttpVerb(str.c_str(), str.length());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline HttpVerb HttpHelper::StringToHttpVerb(const char *pStr, const size_t length) const
{
const size_t hashValue = Boost::hash_range<const char *>(pStr, pStr + length);
const VerbMap::const_iterator iter = m_verbMap.find(hashValue);
if (ACTIV_LIKELY(iter != m_verbMap.end()))
return iter->second;
return HTTP_VERB_UNKNOWN;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &HttpHelper::HttpVerbToString(const HttpVerb httpVerb) const
{
if (ACTIV_LIKELY(httpVerb >= static_cast<HttpVerb>(0)) && ACTIV_LIKELY(httpVerb < NUMBER_OF_HTTP_VERBS))
return m_verbNameList[httpVerb];
return m_verbNameList[NUMBER_OF_HTTP_VERBS];
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief HTTP Exception.
*/
class HttpException : public Exception
{
public:
/**
* @brief Constructor.
*
* @param file the file which raised the exception.
* @param function the function which raised the exception.
* @param line the line number which raised the exception.
* @param errorCode the exception specific error code, in this case an HttpStatusCode value.
* @param reasonPhrase HTTP reason phrase.
*/
ACTIV_BASE_API HttpException(const char *file, const char *function, const uint_fast32_t line, const uint_fast32_t errorCode,
const String &reasonPhrase);
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief HTTP message.
*/
class HttpMessage
{
public:
typedef std::pair<String, String> HeaderPair; ///< Key,value header pair.
typedef std::vector<HeaderPair> HeaderList; ///< List of header key,value pairs.
/**
* @brief Default constructor.
*/
HttpMessage();
/**
* @brief Destructor.
*/
virtual ~HttpMessage();
/**
* @brief Reset.
*
* Clears down fields in this class.
*/
void Reset();
/**
* @brief Sort headers.
*
* Headers must be sorted before using GetHeaderValue().
*/
void SortHeaders();
/**
* @brief Get the value of a header field.
*
* @param keyName
*
* @return Reference to the key's value.
*
* @throw Exception if key is not found.
*/
const String &GetHeaderValue(const String &keyName) const;
/**
* @brief Get an iterator to the the first header.
*
* @return Iterator.
*/
const HeaderList::const_iterator begin() const;
/**
* @brief Get an iterator to past the the last header.
*
* @return Iterator.
*/
const HeaderList::const_iterator end() const;
/**
* @brief Get the HTTP version string.
*
* @return String reference.
*/
const String &GetHttpVersion() const;
protected:
/**
* @brief Callback invoked by HttpValidator on receipt of HTTP body.
*
* @param statusCode STATUS_CODE_SUCCESS if message type can have no body, or if content-length is defined
* and all body has (now) been received. STATUS_CODE_PENDING if the message type can have a content-length, it is
* defined but we've not yet received the whole body. STATUS_CODE_UNDEFINED_LENGTH for messages that can have a body
* but there was no content-length field (body is everything until the underlying connection is closed).
* @param pBody
* @param bodyLength
*
* @retval STATUS_CODE_SUCCESS
* @retval ... cause immediate return from HttpValidator::ConsumeBytes() with this status code.
*/
ACTIV_BASE_API virtual StatusCode OnBody(const StatusCode statusCode, const void * const pBody, const size_t bodyLength);
private:
typedef PairComparisonObject<HeaderPair, CaseInsensitiveLessThanStringComparisonObject, SelectFirst> Sorter;
/**
* @brief Reset.
*
* Clears down fields in this class.
*/
void InternalReset();
String m_httpVersion;
HeaderList m_headerList; ///< List of header fields.
friend class HttpValidatorBase<HttpRequest>;
friend class HttpValidatorBase<HttpResponse>;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline HttpMessage::HttpMessage()
{
InternalReset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline HttpMessage::~HttpMessage()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpMessage::Reset()
{
InternalReset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpMessage::SortHeaders()
{
std::sort(m_headerList.begin(), m_headerList.end(), Sorter());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &HttpMessage::GetHeaderValue(const String &keyName) const
{
const std::pair<HeaderList::const_iterator, HeaderList::const_iterator> res =
std::equal_range(m_headerList.begin(), m_headerList.end(), keyName, Sorter());
if (res.first != res.second)
return res.first->second;
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_FOUND);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const HttpMessage::HeaderList::const_iterator HttpMessage::begin() const
{
return m_headerList.begin();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const HttpMessage::HeaderList::const_iterator HttpMessage::end() const
{
return m_headerList.end();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &HttpMessage::GetHttpVersion() const
{
return m_httpVersion;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpMessage::InternalReset()
{
m_httpVersion.clear();
m_headerList.clear();
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief HTTP request.
*/
class HttpRequest : public HttpMessage
{
public:
typedef HttpRequest Self; ///< This type.
/**
* @brief Default constructor.
*/
HttpRequest();
/**
* @brief Reset.
*
* Clears down fields in this class and base.
*/
void Reset();
/**
* @brief Get the HTTP verb for this request.
*
* @return HttpVerb.
*/
HttpVerb GetHttpVerb() const;
/**
* @brief Get the URI.
*
* @return String reference.
*/
const String &GetUri() const;
/**
* @brief Get the URI.
*
* @return String reference.
*/
String &GetUri();
private:
/**
* @brief Reset.
*
* Clears down fields in this class.
*/
void InternalReset();
HttpVerb m_httpVerb;
String m_uri;
friend class HttpValidatorBase<HttpRequest>;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline HttpRequest::HttpRequest()
{
InternalReset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpRequest::Reset()
{
HttpMessage::Reset();
InternalReset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline HttpVerb HttpRequest::GetHttpVerb() const
{
return m_httpVerb;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &HttpRequest::GetUri() const
{
return m_uri;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline String &HttpRequest::GetUri()
{
return m_uri;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpRequest::InternalReset()
{
m_httpVerb = HTTP_VERB_UNKNOWN;
m_uri.clear();
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief HTTP response.
*/
class HttpResponse : public HttpMessage
{
public:
typedef HttpResponse Self; ///< This type.
/**
* @brief Default constructor.
*/
HttpResponse();
/**
* @brief Reset.
*
* Clears down fields in this class and base.
*/
void Reset();
/**
* @brief Get the HTTP response status code.
*
* @return Status code.
*/
HttpStatusCode GetStatusCode() const;
/**
* @brief Get the HTTP reason reason phrase.
*
* @return String reference.
*/
const String &GetReasonPhrase() const;
private:
/**
* @brief Reset.
*
* Clears down fields in this class.
*/
void InternalReset();
HttpStatusCode m_httpStatusCode;
String m_reasonPhrase;
friend class HttpValidatorBase<HttpResponse>;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline HttpResponse::HttpResponse()
{
InternalReset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpResponse::Reset()
{
HttpMessage::Reset();
InternalReset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline HttpStatusCode HttpResponse::GetStatusCode() const
{
return m_httpStatusCode;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &HttpResponse::GetReasonPhrase() const
{
return m_reasonPhrase;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HttpResponse::InternalReset()
{
m_httpStatusCode = HTTP_STATUS_CODE_UNDEFINED;
m_reasonPhrase.clear();
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_HTTP_H)
@@ -1,172 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/HttpValidator.h
*
* @brief Header file for the HTTP validator classes.
*/
#if (!defined ACTIV_BASE_HTTP_VALIDATOR_H)
#define ACTIV_BASE_HTTP_VALIDATOR_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Http.h"
#include "ActivMiddleware/ActivBase/MessageValidator.h"
#include "ActivMiddleware/ActivBase/FieldTypes/UInt.h"
#include "ActivMiddleware/Misc/StlHelper.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief HTTO validator base.
*
* @param T an HttpRequest or HttpResponse derived class.
*/
template<typename T>
class HttpValidatorBase
{
public:
/**
* @brief Reset.
*/
ACTIV_BASE_API void Reset();
/**
* @brief Consume some bytes.
*
* The OnBody() callback in the HttpMessage passed to the constructor will be invoked with any data which is in the
* body of the HTTP message stream.
*
* @param pData
* @param dataLength
*
* @retval STATUS_CODE_SUCCESS bytes are valid HTTP.
* @retval STATUS_CODE_INVALID_FORMAT invalid HTTP; connection should be closed.
*/
ACTIV_BASE_API StatusCode ConsumeBytes(const void * const pData, const size_t dataLength);
protected:
/**
* @brief Constructor.
*
* @param httpMessage an HttpRequest or HttpResponse to validate against.
*/
ACTIV_BASE_API HttpValidatorBase(T &httpMessage);
private:
static const char CR = 0x0d;
static const char LF = 0x0a;
/**
* @brief Parsing states.
*/
enum State
{
STATE_INITIAL_LINE,
STATE_HEADERS,
STATE_BODY
};
/**
* @brief Line parsing states.
*/
enum LineState
{
LINE_STATE_W4_CR,
LINE_STATE_W4_LF
};
/**
* @brief Set a new state.
*
* @param state
*/
void SetState(const State state);
/**
* @brief Validate a line.
*
* @retval STATUS_CODE_SUCCESS complete line in m_line.
* @retval STATUS_CODE_END_OF_DATA more data required to parse complete line.
* @retval STATUS_CODE_INVALID_FORMAT
* @retval STATUS_CODE_FAILURE internal error.
*/
StatusCode ValidateLine();
/**
* @brief Validate the initial line of an HTTP message.
*
* Specializations for HttpRequest and HttpResponse are provided.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_COMMAND for HttpRequest; unknown verb.
* @retval STATUS_CODE_INVALID_FORMAT
*/
StatusCode ValidateInitialLine();
/**
* @brief Validate header lines of an HTTP message.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FORMAT not for the form "key: value"
*/
StatusCode ValidateMessageHeader();
/**
* @brief Validate body of message.
*
* Specializations for HttpRequest and HttpResponse are provided.
*
* @param pContent to receive a pointer to the body content.
* @param contentLength to receive the (partial) content length.
*
* @retval STATUS_CODE_SUCCESS complete content-length has been received.
* @retval STATUS_CODE_END_OF_DATA more data required to complete content-length, or no content-length received.
*/
StatusCode ValidateBody();
/**
* @brief Validate body of message, common to requests and responses.
*
* @param pContent to receive a pointer to the body content.
* @param contentLength to receive the (partial) content length.
*
* @retval STATUS_CODE_SUCCESS complete content-length has been received.
* @retval STATUS_CODE_END_OF_DATA more data required to complete content-length, or no content-length received.
*/
StatusCode InternalValidateBody();
T & m_httpMessage;
MessageValidator m_messageValidator;
State m_state; ///< Current receive state.
LineState m_lineState; ///< Current line-parsing state.
String m_line; ///< Current line.
const byte_t * m_pData; ///< Start of current buffer passed to ConsumeBytes().
const byte_t * m_pNextByte; ///< Next byte to parse.
size_t m_bytesLeft; ///< Number of bytes left of m_pData to parse.
UInt m_headerContentLength; ///< Content-length from header.
uint64_t m_totalNumberOfBytesBodyReceived; ///< Number of bytes content received in total.
const void * m_pBody; ///< Body to pass back to user.
size_t m_bodyLength; ///< Body length to pass back to user.
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
class HttpValidator : public HttpValidatorBase<typename T::Self>
{
public:
HttpValidator(T &httpMessage) :
HttpValidatorBase<typename T::Self>(httpMessage)
{
}
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_HTTP_VALIDATOR_H)
@@ -1,83 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/IEvent.h
*
* @brief Header file for the event interface class.
*/
#if (!defined ACTIV_BASE_IEVENT_H)
#define ACTIV_BASE_IEVENT_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/Misc/TypeSafeFlags.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Abstract base event class.
*/
class IEvent : private Boost::noncopyable
{
public:
//! Flags for event creation.
class Flags : public TypeSafeFlags::Underlying<uint32_t>
{
public:
typedef TypeSafeFlags::Value<Flags, 0x00000000> None;
typedef TypeSafeFlags::Value<Flags, 0x00000001> Manual; ///< Manual reset event.
typedef TypeSafeFlags::Value<Flags, 0x00000002> OverrideIpcGroupId; ///< Use group id as set in environment variable as owner of the mapped memory file (Posix only).
typedef TypeSafeFlags::Type<Flags, None> Type;
};
//! Destructor.
virtual ~IEvent() = 0;
/**
* @brief Set the event.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
*/
virtual StatusCode Set() = 0;
/**
* @brief Clear the event.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
*/
virtual StatusCode Clear() = 0;
/**
* @brief Wait for the event to be signaled.
*
* @param timeout how long to wait for the event, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_TIMEOUT
*/
virtual StatusCode Wait(const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) = 0;
/**
* @brief Get the underlying handle, if available.
*
* @param handle reference to receive the handle.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_SUPPORTED the object does not support an exportable handle.
*/
virtual StatusCode GetHandle(HANDLE &handle) const = 0;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline IEvent::~IEvent()
{
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_IEVENT_H)
@@ -1,582 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/IFile.h
*
* @brief Header file for file class.
*/
#if (!defined ACTIV_BASE_IFILE_H)
#define ACTIV_BASE_IFILE_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/ActivFileTypes.h"
#include "ActivMiddleware/Misc/TypeSafeFlags.h"
#include ACTIV_BOOST_INCLUDE(move/move.hpp)
#include ACTIV_BOOST_INCLUDE(container/vector.hpp)
#include <ctime>
#include <sys/stat.h>
//! Activ namespace.
namespace Activ
{
/**
* @brief IFile class.
*/
class IFile
{
ACTIV_BOOST_MOVABLE_BUT_NOT_COPYABLE(IFile)
public:
typedef int32_t CompressionLevel; ///< The compression level typedef.
//! Activ compression level defines.
static const CompressionLevel COMPRESSION_LEVEL_NONE = Boost::integer_traits<CompressionLevel>::const_max;
static const CompressionLevel COMPRESSION_LEVEL_BEST = COMPRESSION_LEVEL_NONE - 1;
static const CompressionLevel COMPRESSION_LEVEL_FAST = COMPRESSION_LEVEL_NONE - 2;
static const CompressionLevel COMPRESSION_LEVEL_DEFAULT = COMPRESSION_LEVEL_NONE - 3;
//! Access flags.
class AccessFlags : public TypeSafeFlags::Underlying<uint32_t>
{
public:
typedef TypeSafeFlags::Value<AccessFlags, 0x00000000> None;
typedef TypeSafeFlags::Value<AccessFlags, 0x00000001> Read; ///< Open/create file with read access.
typedef TypeSafeFlags::Value<AccessFlags, 0x00000002> Write; ///< Open/create file with write access.
typedef TypeSafeFlags::Value<AccessFlags, 0x00000006> Append; ///< Open/create file with append access. This flag contains the Write bit
typedef TypeSafeFlags::Type<AccessFlags, None> Type;
};
//! Share flags.
class ShareFlags : public TypeSafeFlags::Underlying<uint32_t>
{
public:
typedef TypeSafeFlags::Value<ShareFlags, 0x00000000> None;
typedef TypeSafeFlags::Value<ShareFlags, 0x00000001> Read; ///< Open/create file with read sharing access.
typedef TypeSafeFlags::Value<ShareFlags, 0x00000002> Write; ///< Open/create file with write sharing access.
typedef TypeSafeFlags::Type<ShareFlags, None> Type;
};
//! Seek method.
enum SeekMethod
{
SEEK_METHOD_BEGIN,
SEEK_METHOD_END,
SEEK_METHOD_CURRENT
};
#if (defined ACTIV_PLATFORM_POSIX)
//! Actions for ModifyMode().
enum ModifyModeAction
{
MODIFY_MODE_ACTION_SET, ///< Set permission bits to provided value.
MODIFY_MODE_ACTION_ADD, ///< Add permission bits to existing.
MODIFY_MODE_ACTION_REMOVE ///< Remove permission bits from existing.
};
#endif
//! Helper class that will delete an open IFile when this object goes out of scope.
class ScopedDelete
{
public:
/**
* @brief Constructor.
*
* @param file the IFile to delete.
*/
ACTIV_BASE_API ScopedDelete(IFile &file);
/**
* @brief Destructor.
*
* If the IFile passed to the constructor is open, delete it.
*/
ACTIV_BASE_API ~ScopedDelete();
private:
IFile &m_file;
};
//! Destructor.
ACTIV_BASE_API virtual ~IFile();
/**
* @brief Create the file.
*
* Derived implementations need to handle cleaning up the base file descriptor upon failure.
*
* @param fileName the file name.
* @param accessFlags the file access flags.
* @param shareFlags the file sharing flags.
* @param shouldFailIfExists if true, fail if the file already exists.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_ALREADY_OPEN
* @retval STATUS_CODE_ALREADY_EXISTS if shouldFailIfExists true and the file exists.
* @retval ...
*/
ACTIV_BASE_API virtual StatusCode Create(const String &fileName, const AccessFlags::Type accessFlags,
const ShareFlags::Type shareFlags, const bool shouldFailIfExists = false);
/**
* @brief Create the file if it doesn't exist, otherwise open it.
*
* @param fileName the file name.
* @param accessFlags the file access flags.
* @param shareFlags the file sharing flags.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_ALREADY_OPEN
* @retval ...
*/
ACTIV_BASE_API StatusCode CreateOrOpen(const String &fileName, const AccessFlags::Type accessFlags,
const ShareFlags::Type shareFlags);
/**
* @brief Open the file.
*
* Derived implementations need to handle cleaning up the base file descriptor upon failure.
*
* @param fileName the file name.
* @param accessFlags the file access flags.
* @param shareFlags the file sharing flags.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_ALREADY_OPEN
* @retval ...
*/
ACTIV_BASE_API virtual StatusCode Open(const String &fileName, const AccessFlags::Type accessFlags,
const ShareFlags::Type shareFlags);
/**
* @brief Close the file.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API virtual StatusCode Close();
#if (defined ACTIV_PLATFORM_POSIX)
/**
* @brief Modify the permission mode of the file.
*
* @param modifyModeAction whether to set, add or remove permission bits.
* @param mode the permission bits to add or remove.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API StatusCode ModifyMode(const ModifyModeAction modifyModeAction, const mode_t mode);
/**
* @brief Modify the permission mode of a file or directory.
*
* @param path the path to the file or directory.
* @param modifyModeAction whether to set, add or remove permission bits.
* @param mode the permission bits to add or remove.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode ModifyMode(const String &path, const ModifyModeAction modifyModeAction, const mode_t mode);
#endif
/**
* @brief Read from a file.
*
* @param pBuffer the buffer to read into.
* @param nBytesToRead the number of bytes to read.
* @param nBytesRead the number of bytes read.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API StatusCode Read(void *pBuffer, const size_t nBytesToRead, size_t &nBytesRead);
/**
* @brief Read from a file.
*
* @param pBuffer the buffer to read into.
* @param nBytesToRead the number of bytes to read.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval STATUS_CODE_FAILURE
* @retval ...
*/
ACTIV_BASE_API StatusCode Read(void *pBuffer, const size_t nBytesToRead);
/**
* @brief Read a line from a file.
*
* @param line the buffer to read the line into.
* @param endOfLine the buffer to read the end of line into.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval STATUS_CODE_END_OF_DATA
* @retval STATUS_CODE_NOT_SUPPORTED
* @retval ...
*/
ACTIV_BASE_API StatusCode ReadLine(String &line, String &endOfLine);
/**
* @brief Read a line from a file.
*
* @param line the buffer to read the line into. End of line characters are not stored.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval STATUS_CODE_END_OF_DATA
* @retval ...
*/
ACTIV_BASE_API StatusCode ReadLine(String &line);
/**
* @brief Write to a file.
*
* @param pBuffer the buffer to write from.
* @param nBytesToWrite the number of bytes to write.
* @param nBytesWritten the number of bytes written.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API StatusCode Write(const void *pBuffer, const size_t nBytesToWrite, size_t &nBytesWritten);
/**
* @brief Write to a file.
*
* @param pBuffer the buffer to write from.
* @param nBytesToWrite the number of bytes to write.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval STATUS_CODE_FAILURE
* @retval ...
*/
ACTIV_BASE_API StatusCode Write(const void *pBuffer, const size_t nBytesToWrite);
/**
* @brief Flush a file to disk.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval STATUS_CODE_FAILURE
* @retval ...
*/
ACTIV_BASE_API virtual StatusCode Flush();
/**
* @brief Get the current position within the file.
*
* This might not include any unflushed data and must offset the return value
* with data in the ReadLine buffer.
*
* @param position the position within the file.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API StatusCode GetPosition(uint64_t &position) const;
/**
* @brief Get the decoded position.
*
* This might not include any unflushed data and must offset the return value
* with data in the ReadLine buffer.
*
* @param position the position within the codec.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API virtual StatusCode GetDecodedPosition(uint64_t &position) const;
/**
* @brief Set the current position within the file.
*
* The return value must handle the data in the ReadLine buffer.
*
* @param position the position within the file.
* @param seekMethod the seek method.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_BASE_API virtual StatusCode SetPosition(int64_t position, const SeekMethod seekMethod = SEEK_METHOD_BEGIN);
/**
* @brief Get the size of the file.
*
* If gzip compression is enabled, this does not include any unflushed data buffered inside the compressor
*
* @param size the size of the file.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval STATUS_CODE_FAILURE
* @retval ...
*/
ACTIV_BASE_API StatusCode GetSize(uint64_t &size) const;
/**
* @brief Set the size of the file.
*
* Not supported in Gzip compression mode.
*
* @param size the size of the file.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval STATUS_CODE_NOT_SUPPORTED
* @retval ...
*/
ACTIV_BASE_API StatusCode SetSize(uint64_t size);
/**
* @brief Get the last write date time of the file.
*
* @param tm reference to a tm structure to receive the UTC date / time.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API StatusCode GetLastWriteDateTime(std::tm &tm) const;
/**
* @brief Get the creation date time of the file.
*
* @param tm reference to a tm structure to receive the UTC date / time.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API StatusCode GetCreationDateTime(std::tm &tm) const;
/**
* @brief Get the last access date time of the file.
*
* @param tm reference to a tm structure to receive the UTC date / time.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API StatusCode GetLastAccessDateTime(std::tm &tm) const;
/**
* @brief Get the file name.
*
* @param fileName the file name.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
*/
ACTIV_BASE_API StatusCode GetFileName(String &fileName) const;
//! Get the underlying file handle
HANDLE GetHandle() const;
//! Is the file open?
bool IsOpen() const;
//! Get the file type
FileType GetFileType() const;
#ifndef ACTIV_LITE_FRAMEWORK
/**
* @brief Get the file type of the file.
*
* @param fileName the name of the file.
* @param fileType the file type.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API static StatusCode GetFileTypeFromFile(const String& fileName, FileType &fileType);
/**
* @brief Get the file type of the file.
*
* @param fileName the name of the file.
*
* @return the file type/
*
* @throws StatusCodeException
*/
ACTIV_BASE_API static FileType GetFileTypeFromFile(const String& fileName);
#endif
protected:
/**
* @brief Constructor.
*
* @param fileType the file type.
*/
ACTIV_BASE_API explicit IFile(const FileType fileType);
/**
* @brief Move constructor.
*
* @param rhs transfer ownership of the underlying file managed by @a rhs to this.
*/
IFile(ACTIV_BOOST_RV_REF(IFile) rhs) :
m_fileHandle(rhs.m_fileHandle),
m_fileType(rhs.m_fileType),
m_accessFlags(rhs.m_accessFlags),
m_readLineBuffer(CxxYZ::move(rhs.m_readLineBuffer)),
m_bufferOffset(rhs.m_bufferOffset),
m_bufferLength(rhs.m_bufferLength)
#if (defined ACTIV_PLATFORM_WINDOWS)
,m_shouldDeleteOnClose(false)
#endif // (defined ACTIV_PLATFORM_WINDOWS)
{
// Inline here for G++.
m_fileName.swap(rhs.m_fileName),
rhs.m_fileHandle = INVALID_HANDLE_VALUE;
rhs.m_bufferOffset = 0;
rhs.m_bufferLength = 0;
}
/**
* @brief Move assignment operator.
*
* Transfer ownership of a file from another IFile object to this.
*
* If this object has a file open, it is closed. The underlying file associated with rhs is transferred to this object,
* and no file is then associated with rhs.
*
* @param rhs the file to transfer to this object.
*
* @return *this
*/
IFile &operator=(ACTIV_BOOST_RV_REF(IFile) rhs)
{
// Inline here for G++.
if (this != &rhs)
{
(void) Close();
m_fileName.clear();
m_fileName.swap(rhs.m_fileName);
m_fileHandle = rhs.m_fileHandle;
m_fileType = rhs.m_fileType;
m_accessFlags = rhs.m_accessFlags;
m_readLineBuffer = CxxYZ::move(rhs.m_readLineBuffer);
m_bufferOffset = rhs.m_bufferOffset;
m_bufferLength = rhs.m_bufferLength;
rhs.m_fileHandle = INVALID_HANDLE_VALUE;
rhs.m_accessFlags = AccessFlags::None();
rhs.m_bufferOffset = 0;
rhs.m_bufferLength = 0;
// Not transferring m_shouldDeleteOnClose; it is specific to the IFile passed to the ScopedDelete object.
}
return *this;
}
/**
* @brief Duplicate the a file handle into a C runtime file descriptor.
*
* @param fileHandle the file handle to duplicate.
* @param accessFlags the current access flags.
* @param fileDescriptor the duplicated C runtime file descriptor.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
*/
ACTIV_BASE_API static StatusCode DuplicateFileHandle(const HANDLE fileHandle, const AccessFlags::Type accessFlags, int &fileDescriptor);
/**
* @brief Decode data and read to a buffer.
*
* @param pBuffer the buffer to read into.
* @param nBytesToRead the number of bytes to read.
* @param nBytesRead the number of bytes read.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API virtual StatusCode Decode(void *pBuffer, const size_t nBytesToRead, size_t &nBytesRead) = 0;
/**
* @brief Encode and write buffer.
*
* @param pBuffer the buffer to write from.
* @param nBytesToWrite the number of bytes to write.
* @param nBytesWritten the number of bytes written.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_OPEN
* @retval ...
*/
ACTIV_BASE_API virtual StatusCode Encode(const void *pBuffer, const size_t nBytesToWrite, size_t &nBytesWritten) = 0;
typedef Boost::container::vector<byte_t> DataBuffer; ///< The data buffer type definition.
String m_fileName;
HANDLE m_fileHandle;
FileType m_fileType;
AccessFlags::Type m_accessFlags;
DataBuffer m_readLineBuffer;
size_t m_bufferOffset;
size_t m_bufferLength;
#if (defined ACTIV_PLATFORM_WINDOWS)
bool m_shouldDeleteOnClose;
#endif // (defined ACTIV_PLATFORM_WINDOWS)
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline HANDLE IFile::GetHandle() const
{
return m_fileHandle;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool IFile::IsOpen() const
{
return (INVALID_HANDLE_VALUE != m_fileHandle);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline FileType IFile::GetFileType() const
{
return m_fileType;
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_IFILE_H)
@@ -1,71 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/IFileMappedMemory.h
*
* @brief Header file for the file mapped memory interface class.
*/
#if (!defined ACTIV_BASE_IFILE_MAPPED_MEMORY_H)
#define ACTIV_BASE_IFILE_MAPPED_MEMORY_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/IMappedMemory.h"
#include "ActivMiddleware/Misc/TypeSafeFlags.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Abstract base file mapped memory class.
*/
class IFileMappedMemory : public IMappedMemory
{
public:
static const size_t USE_CURRENT_FILE_SIZE = 0; ///< Used for creating a mapping of the current file size.
//! Flags.
class FileFlags : public TypeSafeFlags::Underlying<uint32_t>
{
public:
typedef TypeSafeFlags::Value<FileFlags, 0x00000000> None;
typedef TypeSafeFlags::Value<FileFlags, 0x00000001> CreateAlways; ///< Always create new file.
typedef TypeSafeFlags::Value<FileFlags, 0x00000002> OpenExisting; ///< Open existing file, fail if file doesn't exist.
typedef TypeSafeFlags::Value<FileFlags, 0x00000004> ReadOnly; ///< Open file in read only mode.
typedef TypeSafeFlags::Value<FileFlags, 0x00000008> DeleteAtClose; ///< Delete the file when the handle to it is closed.
typedef TypeSafeFlags::Type<FileFlags, None> Type;
};
//! Destructor.
virtual ~IFileMappedMemory() = 0;
/**
* @brief Resize a memory mapped file.
*
* @param size the new size of the memory mapped file.
*
* @return a pointer to the new mapped memory region.
*
* @throw Exception
*/
virtual void *Resize(const size_t size) = 0;
/**
* @brief Flush the memory mapped file to the disk.
*
* @param nBytesToFlush the number of bytes to flush, starting from the beginning of the file. Default flush all.
*
* @throw Exception
*/
virtual void Flush(const size_t nBytesToFlush = 0) const = 0;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline IFileMappedMemory::~IFileMappedMemory()
{
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_IFILE_MAPPED_MEMORY_H)
@@ -1,64 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/IMappedMemory.h
*
* @brief Header file for the mapped memory interface class.
*/
#if (!defined ACTIV_BASE_IMAPPED_MEMORY_H)
#define ACTIV_BASE_IMAPPED_MEMORY_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/Misc/TypeSafeFlags.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Abstract base mapped memory class.
*/
class IMappedMemory : private Boost::noncopyable
{
public:
//! Flags.
class MappingFlags : public TypeSafeFlags::Underlying<uint32_t>
{
public:
typedef TypeSafeFlags::Value<MappingFlags, 0x00000000> None;
typedef TypeSafeFlags::Value<MappingFlags, 0x00000001> ReadOnly; ///< Read only access to the mapped memory segment.
typedef TypeSafeFlags::Value<MappingFlags, 0x00000002> Unique; ///< A named segment cannot already exist when creating.
typedef TypeSafeFlags::Value<MappingFlags, 0x00000004> Locked; ///< Lock the mapped data in memory (Posix only).
typedef TypeSafeFlags::Value<MappingFlags, 0x00000008> OverrideIpcGroupId; ///< Use group id as set in environment variable as owner of the mapped memory file (Posix only).
typedef TypeSafeFlags::Value<MappingFlags, 0x00000010> TryHugePages; ///< Try to use huge pages with the mapped memory file (Posix only).
typedef TypeSafeFlags::Type<MappingFlags, None> Type;
};
/**
* @brief Destructor.
*/
virtual ~IMappedMemory() = 0;
/**
* @brief Get pointer to mapped memory.
*
* @return Pointer to mapped memory.
*/
virtual void *GetPointer() const = 0;
/**
* @brief Get size of mapped memory.
*
* @return Size.
*/
virtual size_t GetSize() const = 0;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline IMappedMemory::~IMappedMemory()
{
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_IMAPPED_MEMORY_H)
@@ -1,76 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/IMutex.h
*
* @brief Header file for the mutex interface class.
*/
#if (!defined ACTIV_BASE_IMUTEX_H)
#define ACTIV_BASE_IMUTEX_H
#include "ActivMiddleware/ActivBase/External.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Mutex interface class.
*/
class IMutex : private Boost::noncopyable
{
public:
/**
* @brief Destructor.
*/
virtual ~IMutex() = 0;
/**
* @brief Try to obtain the mutex lock.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
*/
virtual StatusCode Try() const = 0;
/**
* @brief Acquire the mutex lock.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_NOT_SUPPORTED
*/
virtual StatusCode Acquire() const = 0;
/**
* @brief Release the mutex lock.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
*/
virtual StatusCode Release() const = 0;
/**
* @brief Get approximate contention count for the mutex.
*
* The count is approximate as it doesn't use an atomic counter - if multiple threads attempt to lock
* the mutex at the "same" time and the mutex is already locked, the counter may not be incremented correctly.
*
* Note not all mutex implementations may provide this value, in which case this function will return 0. For
* mutexes that do, the value is incremented if Try() fails or Acquire() blocks.
*
* This is provided for informational purposes only.
*
* @return approximate contention count.
*/
virtual size_t GetContentionCount() const = 0;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline IMutex::~IMutex()
{
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_IMUTEX_H)
@@ -1,55 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/ISerializableMessage.h
*
* @brief Header file for serializable message interface class.
*/
#if (!defined ACTIV_BASE_ISERIALIZABLE_MESSAGE_H)
#define ACTIV_BASE_ISERIALIZABLE_MESSAGE_H
#include "ActivMiddleware/ActivBase/External.h"
//! Activ namespace.
namespace Activ
{
class MessageValidator;
class MessageBuilder;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Serializable message interface.
*/
class ISerializableMessage
{
public:
/**
* @brief Destructor.
*/
virtual ~ISerializableMessage() = 0;
/**
* @brief Serialize the message.
*
* @param messageBuilder message builder into which data will be placed.
*/
virtual StatusCode Serialize(MessageBuilder &messageBuilder) const = 0;
/**
* @brief Deserialize the message.
*
* @param messageValidator message validator from which the data will be extracted.
*/
virtual StatusCode Deserialize(MessageValidator &messageValidator) = 0;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline ISerializableMessage::~ISerializableMessage()
{
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_ISERIALIZABLE_MESSAGE_H)
File diff suppressed because it is too large. Load diff
@@ -1,109 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/IntervalTimer.h
*
* @brief Header file for the interval timer class.
*/
#if (!defined ACTIV_BASE_INTERVAL_TIMER_H)
#define ACTIV_BASE_INTERVAL_TIMER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/ActivBase.h"
//! Activ namespace.
namespace Activ
{
//! Interval timer class
class IntervalTimer
{
public:
//! Helper class to measure time whilst in scope.
class Scoped : private Boost::noncopyable
{
public:
/**
* @brief Constructor.
*
* "Starts" the timer.
*
* @param time reference to a double to receive the time this object is in scope, in seconds.
*/
Scoped(double &time);
/**
* @brief Destructor.
*
* "Stops" the timer and stores the time in the double provided to the constructor.
*/
~Scoped();
private:
double & m_time;
const uint64_t m_startTimeStamp;
};
//! Get the timer frequency.
ACTIV_BASE_API static uint64_t GetFrequency();
//! Scale a timestamp to a time in seconds.
ACTIV_BASE_API static double ScaleTimeStamp(const uint64_t time);
//! Get the current time stamp.
ACTIV_BASE_API static uint64_t GetTimeStamp();
//! Get the current time stamp in milliseconds.
ACTIV_BASE_API static uint64_t GetMillisecondTimeStamp();
//! Get the current time stamp in microseconds.
ACTIV_BASE_API static uint64_t GetMicrosecondTimeStamp();
//! Get the current time stamp in nanoseconds.
ACTIV_BASE_API static uint64_t GetNanosecondTimeStamp();
//! Get the number of milliseconds that have elapsed since the system was started.
ACTIV_BASE_API static uint32_t GetTickCount();
/**
* @brief Get the number of milliseconds that have elapsed since the system was started.
* This function will be emulated on Windows if a native GetTickCount64 is not
* available or if the native GetTickCount64 cannot provide the desired resolution.
* The emulated version keeps track of how many times the system tick count
* overflows a uint32_t and so must be called at least once every ~49 days.
*
* @return Time since system started, in ms.
*/
ACTIV_BASE_API static uint64_t GetTickCount64();
/**
* @brief Get the system clock resolution.
*
* On Windows, this returns the actual clock resolution if possible, or a default of 15600 if unable to determine.
*
* @return The clock resolution, in microseconds.
*/
ACTIV_BASE_API static size_t GetClockResolution();
private:
IntervalTimer();
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline IntervalTimer::Scoped::Scoped(double &time) :
m_time(time),
m_startTimeStamp(IntervalTimer::GetTimeStamp())
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline IntervalTimer::Scoped::~Scoped()
{
m_time = IntervalTimer::ScaleTimeStamp(IntervalTimer::GetTimeStamp() - m_startTimeStamp);
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_INTERVAL_TIMER_H)
@@ -1,863 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/IntrusiveSetHelper.h
*
* @brief Header file for intrusive set helper.
*/
#if (!defined ACTIV_BASE_INTRUSIVE_SET_HELPER_H)
#define ACTIV_BASE_INTRUSIVE_SET_HELPER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Detail/IntrusiveSetHelperDetail.h"
//! Activ namespace.
namespace Activ
{
namespace IntrusiveSetHelper
{
//! Set entries must be derived from a BaseHook or include a public MemberHook.
typedef Boost::intrusive::make_set_base_hook<Detail::DefaultLinkMode>::type SetBaseHook;
typedef Boost::intrusive::make_set_member_hook<Detail::DefaultLinkMode>::type SetMemberHook;
typedef Detail::UnorderedSetBaseHookHelper<false> UnorderedSetBaseHook;
typedef Detail::UnorderedSetBaseHookHelper<true> UnorderedSetBaseHookStoreHash;
typedef Boost::intrusive::make_unordered_set_member_hook<Detail::DefaultLinkMode>::type UnorderedSetMemberHook;
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Unordered set class.
* This set owns any objects placed in the container. They will be deleted when erased or the container cleared.
*
* @tparam T value type of the set.
* @tparam KEY key type of the set.
* @tparam DISPOSER disposer function object.
* @tparam HASH hash function object.
*/
template<typename T, typename KEY, typename DISPOSER = Detail::DeleteDisposer<T>, typename GET_KEY_FUNC = typename T::GetKey,
typename HASH = typename Detail::HashSelector<T, KEY, GET_KEY_FUNC>::type>
class UnorderedSet : private Boost::noncopyable
{
public:
typedef Boost::intrusive::unordered_set<
T,
Boost::intrusive::hash<HASH>,
Boost::intrusive::power_2_buckets<true>,
Boost::intrusive::compare_hash<T::StoreHash>,
Boost::intrusive::key_of_value<GET_KEY_FUNC>
> UnorderedSetType;
typedef typename UnorderedSetType::key_type key_type;
typedef typename UnorderedSetType::value_type value_type;
typedef typename UnorderedSetType::iterator iterator;
typedef typename UnorderedSetType::const_iterator const_iterator;
typedef DISPOSER Disposer;
/**
* @brief Constructor.
*
* @param initialNumberOfBuckets
* @param bucketGrowFillPercent
* @param bucketShrinkFillPercent
* @param disposer
*/
UnorderedSet(const size_t initialNumberOfBuckets = 65536, const uint16_t bucketGrowFillPercent = 80,
const uint16_t bucketShrinkFillPercent = 13, const Disposer &disposer = Disposer());
//! Destructor.
~UnorderedSet();
//! Get bucket count.
size_t GetBucketCount() const;
//! Set the bucket count, causes a rehash.
void SetBucketCount(const size_t bucketCount);
//! Get the bucket grow fill percent.
uint16_t GetBucketGrowFillPercent() const;
//! Set the bucket grow fill percent.
void SetBucketGrowFillPercent(const uint16_t bucketGrowFillPercent);
//! Get an iterator to the first element.
iterator begin();
//! Get an iterator to the first element.
const_iterator begin() const;
//! Get an iterator to one past the last element.
iterator end();
//! Get an iterator to one past the last element.
const_iterator end() const;
//! Empty.
bool empty() const;
//! Size.
size_t size() const;
/**
* @brief Insert check. Note, a call to insert_check and insert_commit must be done as a pair. It is invalid to call
* insert_check twice with different keys followed by an insert_commit of the first item.
*
* @param key check presence of element with this key.
*
* @return A pair of iterator and bool. If the key exists the iterator will point to it and the boolean will be false else the
* boolean will be true if an element can be inserted.
*/
std::pair<iterator, bool> insert_check(const key_type &key);
/**
* @brief Insert commit stable. Note, a call to insert_check and insert_commit must be done as a pair. It is invalid to call
* insert_check twice with different keys followed by an insert_commit of the first item.
* Does not perform a rehash hence iterators are still valid after calling. Container should be rehashed after.
*
* @param pEntry the new element.
*
* @return An iterator to the new element.
*/
iterator insert_commit_stable(value_type *pEntry);
/**
* @brief Insert commit unstable. Note, a call to insert_check and insert_commit must be done as a pair. It is invalid to call
* insert_check twice with different keys followed by an insert_commit of the first item.
* Potentially performs a rehash, all iterators (including end) are invalidated during a rehash.
*
* @param pEntry the new element.
*
* @return An iterator to the new element.
*/
iterator insert_commit_unstable(value_type *pEntry);
/**
* @brief Erase stable.
* Does not perform a rehash hence iterators are still valid after calling. Container should be rehashed after.
*
* @param iterator element to erase.
*/
void erase_stable(const_iterator iterator);
/**
* @brief Erase stable.
* Does not perform a rehash hence iterators are still valid after calling. Container should be rehashed after.
*
* @param key the key of the element to erase.
*
* @return the number of elements erased.
*/
size_t erase_stable(const key_type &key);
/**
* @brief Erase unstable.
* Potentially performs a rehash, all iterators (including end) are invalidated during a rehash.
*
* @param iterator element to erase.
*/
void erase_unstable(const_iterator iterator);
/**
* @brief Erase unstable.
* Potentially performs a rehash, all iterators (including end) are invalidated during a rehash.
*
* @param key the key of the element to erase.
*
* @return the number of elements erased.
*/
size_t erase_unstable(const key_type &key);
//! Clear.
void clear();
/**
* @brief Find.
*
* @param key the key of the element to find an iterator to.
*
* @return An iterator to the element or end().
*/
iterator find(const key_type &key);
/**
* @brief Find.
*
* @param key the key of the element to find an iterator to.
*
* @return An iterator to the element or end().
*/
const_iterator find(const key_type &key) const;
/**
* @brief Find.
*
* @param keyType the compatible key type to find an iterator to.
* @param hasher hasher functor for compatible key type.
* @param equalFunctor equality functor for compatible key type.
*
* @return An iterator to the element or end().
*/
template<class KeyType, class KeyHasher, class KeyEqual>
iterator find(const KeyType &keyType, KeyHasher hasher, KeyEqual equalFunctor);
/**
* @brief Find.
*
* @param keyType the compatible key type to find an iterator to.
* @param hasher hasher functor for compatible key type.
* @param equalFunctor equality functor for compatible key type.
*
* @return An iterator to the element or end().
*/
template<class KeyType, class KeyHasher, class KeyEqual>
const_iterator find(const KeyType &keyType, KeyHasher hasher, KeyEqual equalFunctor) const;
/**
* @brief Iterator to.
*
* @param value the value to get an iterator for (must exist in container).
*
* @return An iterator to value.
*/
iterator iterator_to(value_type &value);
/**
* @brief Iterator to.
*
* @param value the value to get an iterator for (must exist in container).
*
* @return An iterator to value.
*/
const_iterator iterator_to(const value_type &value) const;
//! Rehash. invalidates all iterators (including end).
void rehash();
private:
Detail::BucketManager<UnorderedSetType> m_bucketManager;
Disposer m_disposer;
UnorderedSetType m_unorderedSet;
typename UnorderedSetType::insert_commit_data m_commitData;
};
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::UnorderedSet(const size_t initialNumberOfBuckets,
const uint16_t bucketGrowFillPercent, const uint16_t bucketShrinkFillPercent, const Disposer &disposer) :
m_bucketManager(initialNumberOfBuckets, bucketGrowFillPercent, bucketShrinkFillPercent),
m_disposer(disposer),
m_unorderedSet(m_bucketManager.GetBucketTraits())
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::~UnorderedSet()
{
clear();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline size_t UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::GetBucketCount() const
{
return m_bucketManager.GetSize();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline void UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::SetBucketCount(const size_t bucketCount)
{
m_bucketManager.SetBucketCount(m_unorderedSet, bucketCount);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline uint16_t UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::GetBucketGrowFillPercent() const
{
return m_bucketManager.GetBucketGrowFillPercent();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline void UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::SetBucketGrowFillPercent(const uint16_t bucketGrowFillPercent)
{
m_bucketManager.SetBucketGrowFillPercent(bucketGrowFillPercent);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline typename UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::iterator
UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::begin()
{
return m_unorderedSet.begin();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline typename UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::const_iterator
UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::begin() const
{
return m_unorderedSet.cbegin();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline typename UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::iterator
UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::end()
{
return m_unorderedSet.end();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline typename UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::const_iterator
UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::end() const
{
return m_unorderedSet.cend();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline bool UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::empty() const
{
return m_unorderedSet.empty();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline size_t UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::size() const
{
return m_unorderedSet.size();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline std::pair<typename UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::iterator, bool>
UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::insert_check(const key_type &key)
{
return m_unorderedSet.insert_check(key, m_unorderedSet.hash_function(), m_unorderedSet.key_eq(), m_commitData);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline typename UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::iterator
UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::insert_commit_stable(value_type *pEntry)
{
return m_unorderedSet.insert_commit(*pEntry, m_commitData);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline typename UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::iterator
UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::insert_commit_unstable(value_type *pEntry)
{
// Workaround for bug in boost 1.80.0 and 1.81.0, m_commitData is broken after a rehash, do another insert_check.
//
// Opened issue - https://github.com/boostorg/intrusive/issues/81
//
// TODO: remove when boost bug is fixed.
if (ACTIV_UNLIKELY(m_bucketManager.CheckRehashOnInsert(m_unorderedSet)))
(void) insert_check(GET_KEY_FUNC()(*pEntry));
return m_unorderedSet.insert_commit(*pEntry, m_commitData);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline void UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::erase_stable(const_iterator iterator)
{
m_unorderedSet.erase_and_dispose(iterator, m_disposer);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline size_t UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::erase_stable(const key_type &key)
{
return m_unorderedSet.erase_and_dispose(key, m_unorderedSet.hash_function(), m_unorderedSet.key_eq(), m_disposer);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline void UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::erase_unstable(const_iterator iterator)
{
m_bucketManager.CheckRehashOnErase(m_unorderedSet);
m_unorderedSet.erase_and_dispose(iterator, m_disposer);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline size_t UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::erase_unstable(const key_type &key)
{
m_bucketManager.CheckRehashOnErase(m_unorderedSet);
return m_unorderedSet.erase_and_dispose(key, m_unorderedSet.hash_function(), m_unorderedSet.key_eq(), m_disposer);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline void UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::clear()
{
return m_unorderedSet.clear_and_dispose(m_disposer);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline typename UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::iterator
UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::find(const key_type &key)
{
return m_unorderedSet.find(key, m_unorderedSet.hash_function(), m_unorderedSet.key_eq());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline typename UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::const_iterator
UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::find(const key_type &key) const
{
return m_unorderedSet.find(key, m_unorderedSet.hash_function(), m_unorderedSet.key_eq());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
template<class KeyType, class KeyHasher, class KeyEqual>
inline typename UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::iterator
UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::find(const KeyType &keyType, KeyHasher hasher, KeyEqual equalFunctor)
{
return m_unorderedSet.find(keyType, hasher, equalFunctor);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
template<class KeyType, class KeyHasher, class KeyEqual>
inline typename UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::const_iterator
UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::find(const KeyType &keyType, KeyHasher hasher, KeyEqual equalFunctor) const
{
return m_unorderedSet.find(keyType, hasher, equalFunctor);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline typename UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::iterator
UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::iterator_to(value_type &value)
{
return m_unorderedSet.iterator_to(value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline typename UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::const_iterator
UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::iterator_to(const value_type &value) const
{
return m_unorderedSet.iterator_to(value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC, typename HASH>
inline void UnorderedSet<T, KEY, DISPOSER, GET_KEY_FUNC, HASH>::rehash()
{
(void) m_bucketManager.CheckRehashOnInsert(m_unorderedSet);
m_bucketManager.CheckRehashOnErase(m_unorderedSet);
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set class.
* This set owns any objects placed in the container. They will be deleted when erased or the container cleared.
*
* @tparam T value type of the set.
* @tparam KEY key type of the set.
* @tparam DISPOSER disposer function object.
* @tparam GET_KEY_FUNC function object return the key of T.
*/
template<typename T, typename KEY, typename DISPOSER = Detail::DeleteDisposer<T>, typename GET_KEY_FUNC = typename T::GetKey>
class Set : private Boost::noncopyable
{
public:
typedef Boost::intrusive::set<
T,
Boost::intrusive::key_of_value<GET_KEY_FUNC>
> SetType;
typedef typename SetType::key_type key_type;
typedef typename SetType::value_type value_type;
typedef typename SetType::iterator iterator;
typedef typename SetType::const_iterator const_iterator;
typedef DISPOSER Disposer;
//! Default Constructor.
Set();
//! Destructor.
~Set();
//! Get an iterator to the first element.
iterator begin();
//! Get an iterator to the first element.
const_iterator begin() const;
//! Get an iterator to one past the last element.
iterator end();
//! Get an iterator to one past the last element.
const_iterator end() const;
//! Empty.
bool empty() const;
//! Size.
size_t size() const;
/**
* @brief Insert check. Note, a call to insert_check and insert_commit must be done as a pair. It is invalid to call
* insert_check twice with different keys followed by an insert_commit of the first item.
*
* @param key check presence of element with this key.
*
* @return A pair of iterator and bool. If the key exists the iterator will point to it and the boolean will be false else the
* boolean will be true if an element can be inserted.
*/
std::pair<iterator, bool> insert_check(const key_type &key);
/**
* @brief Insert check. Note, a call to insert_check and insert_commit must be done as a pair. It is invalid to call
* insert_check twice with different keys followed by an insert_commit of the first item.
*
* @param hint insertion point hint.
* @param key check presence of element with this key.
*
* @return A pair of iterator and bool. If the key exists the iterator will point to it and the boolean will be false else the
* boolean will be true if an element can be inserted.
*/
std::pair<iterator, bool> insert_check(const_iterator hint, const key_type &key);
/**
* @brief Insert commit. Note, a call to insert_check and insert_commit must be done as a pair. It is invalid to call
* insert_check twice with different keys followed by an insert_commit of the first item.
*
* @param pEntry the new element.
*
* @return An iterator to the new element.
*/
iterator insert_commit(value_type *pEntry);
/**
* @brief Erase.
*
* @param iterator element to erase.
*/
void erase(const_iterator iterator);
/**
* @brief Erase.
*
* @param key the key of the element to erase.
*
* @return the number of elements erased.
*/
size_t erase(const key_type &key);
//! Clear.
void clear();
/**
* @brief Lower bound.
*
* @param key the key to find the lower bound of.
*
* @return An iterator to the first element is not less than key or end().
*/
iterator lower_bound(const key_type &key);
/**
* @brief Lower bound.
*
* @param key the key to find the lower bound of.
*
* @return An iterator to the first element is not less than key or end().
*/
const_iterator lower_bound(const key_type &key) const;
/**
* @brief Upper bound.
*
* @param key the key to find the upper bound of.
*
* @return An iterator to the first element greater than key or end().
*/
iterator upper_bound(const key_type &key);
/**
* @brief Upper bound.
*
* @param key the key to find the upper bound of.
*
* @return An iterator to the first element greater than key or end().
*/
const_iterator upper_bound(const key_type &key) const;
/**
* @brief Find.
*
* @param key the key of the element to find an iterator to.
*
* @return An iterator to the element or end().
*/
iterator find(const key_type &key);
/**
* @brief Find.
*
* @param key the key of the element to find an iterator to.
*
* @return An iterator to the element or end().
*/
const_iterator find(const key_type &key) const;
/**
* @brief Iterator to.
*
* @param value the value to get an iterator for (must exist in container).
*
* @return An iterator to value.
*/
iterator iterator_to(value_type &value);
/**
* @brief Iterator to.
*
* @param value the value to get an iterator for (must exist in container).
*
* @return An iterator to value.
*/
const_iterator iterator_to(const value_type &value) const;
private:
Disposer m_disposer;
SetType m_set;
typename SetType::insert_commit_data m_commitData;
};
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline Set<T, KEY, DISPOSER, GET_KEY_FUNC>::Set()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline Set<T, KEY, DISPOSER, GET_KEY_FUNC>::~Set()
{
clear();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::iterator Set<T, KEY, DISPOSER, GET_KEY_FUNC>::begin()
{
return m_set.begin();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::const_iterator
Set<T, KEY, DISPOSER, GET_KEY_FUNC>::begin() const
{
return m_set.cbegin();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::iterator Set<T, KEY, DISPOSER, GET_KEY_FUNC>::end()
{
return m_set.end();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::const_iterator
Set<T, KEY, DISPOSER, GET_KEY_FUNC>::end() const
{
return m_set.cend();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline bool Set<T, KEY, DISPOSER, GET_KEY_FUNC>::empty() const
{
return m_set.empty();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline size_t Set<T, KEY, DISPOSER, GET_KEY_FUNC>::size() const
{
return m_set.size();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline std::pair<typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::iterator, bool>
Set<T, KEY, DISPOSER, GET_KEY_FUNC>::insert_check(const key_type &key)
{
return m_set.insert_check(key, m_set.value_comp(), m_commitData);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline std::pair<typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::iterator, bool>
Set<T, KEY, DISPOSER, GET_KEY_FUNC>::insert_check(const_iterator hint, const key_type &key)
{
return m_set.insert_check(hint, key, m_set.value_comp(), m_commitData);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::iterator
Set<T, KEY, DISPOSER, GET_KEY_FUNC>::insert_commit(value_type *pEntry)
{
return m_set.insert_commit(*pEntry, m_commitData);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline void Set<T, KEY, DISPOSER, GET_KEY_FUNC>::erase(const_iterator iterator)
{
m_set.erase_and_dispose(iterator, m_disposer);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline size_t Set<T, KEY, DISPOSER, GET_KEY_FUNC>::erase(const key_type &key)
{
return m_set.erase_and_dispose(key, m_set.value_comp(), m_disposer);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline void Set<T, KEY, DISPOSER, GET_KEY_FUNC>::clear()
{
return m_set.clear_and_dispose(m_disposer);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::iterator
Set<T, KEY, DISPOSER, GET_KEY_FUNC>::lower_bound(const key_type &key)
{
return m_set.lower_bound(key, m_set.value_comp());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::const_iterator
Set<T, KEY, DISPOSER, GET_KEY_FUNC>::lower_bound(const key_type &key) const
{
return m_set.lower_bound(key, m_set.value_comp());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::iterator
Set<T, KEY, DISPOSER, GET_KEY_FUNC>::upper_bound(const key_type &key)
{
return m_set.upper_bound(key, m_set.value_comp());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::const_iterator
Set<T, KEY, DISPOSER, GET_KEY_FUNC>::upper_bound(const key_type &key) const
{
return m_set.upper_bound(key, m_set.value_comp());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::iterator
Set<T, KEY, DISPOSER, GET_KEY_FUNC>::find(const key_type &key)
{
return m_set.find(key, m_set.value_comp());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::const_iterator
Set<T, KEY, DISPOSER, GET_KEY_FUNC>::find(const key_type &key) const
{
return m_set.find(key, m_set.value_comp());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::iterator
Set<T, KEY, DISPOSER, GET_KEY_FUNC>::iterator_to(value_type &value)
{
return m_set.iterator_to(value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T, typename KEY, typename DISPOSER, typename GET_KEY_FUNC>
inline typename Set<T, KEY, DISPOSER, GET_KEY_FUNC>::const_iterator
Set<T, KEY, DISPOSER, GET_KEY_FUNC>::iterator_to(const value_type &value) const
{
return m_set.iterator_to(value);
}
} // namespace IntrusiveSetHelper
} // namespace Activ
#endif // (!defined ACTIV_BASE_INTRUSIVE_SET_HELPER_H)
@@ -1,62 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Ip/INetworkAffinityHelper.h
*
* @brief Header file for the INetworkAffinityHelper interface class.
*/
#if (!defined ACTIV_BASE_I_NETWORK_AFFINITY_HELPER_H)
#define ACTIV_BASE_I_NETWORK_AFFINITY_HELPER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/CxxYZ/memory.h"
//! Activ namespace.
namespace Activ
{
// Forward declarations.
class NetworkAffinityFilter;
//! INetworkAffinityHelper interface class.
class INetworkAffinityHelper : private Boost::noncopyable
{
public:
//! Destructor.
ACTIV_BASE_API virtual ~INetworkAffinityHelper() = 0;
/**
* @brief Create network affinity helper.
*
* @return The created network affinity helper.
*/
ACTIV_BASE_API static CxxYZ::unique_ptr<INetworkAffinityHelper> Create();
/**
* @brief Is supported.
*
* @retval true if supported, false otherwise.
*/
ACTIV_BASE_API static bool IsSupported();
/**
* @brief Add filter.
*
* @param networkAffinityFilter
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API virtual StatusCode AddFilter(const NetworkAffinityFilter &networkAffinityFilter) = 0;
/**
* @brief Remove filter.
*
* @param networkAffinityFilter
*/
ACTIV_BASE_API virtual void RemoveFilter(const NetworkAffinityFilter &networkAffinityFilter) = 0;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_I_NETWORK_AFFINITY_HELPER_H)
@@ -1,515 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Ip/IpAddress.h
*
* @brief Header file for ip address class.
*/
#if (!defined ACTIV_BASE_IP_IP_ADDRESS_H)
#define ACTIV_BASE_IP_IP_ADDRESS_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/MessageValidator.h"
#include "ActivMiddleware/ActivBase/MessageBuilder.h"
#include <vector>
#include <cstring>
#if (defined ACTIV_PLATFORM_POSIX)
#include <sys/socket.h>
#endif
//! Activ namespace.
namespace Activ
{
class IpAddressMask;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Ip address information.
*
* Currently supports ipv4 and ipv6 addresses.
*/
class IpAddress
{
public:
/**
* @brief Address union.
*/
union AddressUnion
{
sockaddr Address;
sockaddr_in AddressIn; ///< Ipv4 address.
sockaddr_in6 AddressIn6; ///< Ipv6 address.
};
/**
* @brief Constructor.
*
* The socket type and protocol are initialized to 0.
*
* @param family the address family.
*/
IpAddress(const int family = AF_UNSPEC);
/**
* @brief Constructor.
*
* @param socketType the socket type.
* @param protocol the socket protocol.
* @param family the address family.
*/
IpAddress(const int socketType, const int protocol, const int family = AF_UNSPEC);
/**
* @brief Compare two IpAddress objects.
*
* Port number is included in the comparison.
*
* @param rhs reference to an IpAddress object to compare.
*
* @retval -ve if this is less than rhs.
* @retval 0 if this equal to rhs.
* @retval +ve if this is greater than rhs.
*/
int Compare(const IpAddress &rhs) const;
/**
* @brief Equality operator.
*
* Port number is included in the comparison.
*
* @param rhs reference to an IpAddress object to compare.
*
* @retval true if this is equal to rhs.
* @retval false if this is not equal to rhs.
*/
bool operator==(const IpAddress &rhs) const;
/**
* @brief Inequality operator.
*
* Port number is included in the comparison.
*
* @param rhs reference to an IpAddress object to compare.
*
* @retval true if this is not equal to rhs.
* @retval false if this is equal to rhs.
*/
bool operator!=(const IpAddress &rhs) const;
/**
* @brief Less than operator.
*
* Port number is included in the comparison.
*
* @param rhs reference to an IpAddress object to compare.
*
* @retval true if this is less than rhs.
* @retval false if this is greater than or equal to rhs.
*/
bool operator<(const IpAddress &rhs) const;
/**
* @brief Convert address to a string.
*
* @param shouldShowPort whether to include the port number in the string.
*
* @return The string form of the address, or an empty string is returned if the address cannot be converted.
*/
ACTIV_BASE_API String ToString(const bool shouldShowPort = true) const;
/**
* @brief Get the socket family.
*
* @return The socket family.
*/
sa_family_t GetFamily() const;
/**
* @brief Set the socket family.
*
* @param family
*/
void SetFamily(const sa_family_t family);
/**
* @brief Get the socket address length.
*
* @return The socket address length.
*/
socklen_t GetLength() const;
/**
* @brief Set the socket address length.
*
* @param length
*/
void SetLength(const socklen_t length);
/**
* @brief Get reference to the Address union.
*
* @return Address reference.
*/
AddressUnion &GetAddress();
/**
* @brief Get const reference to the Address union.
*
* @return Address reference.
*/
const AddressUnion &GetAddress() const;
/**
* @brief Get the socket type.
*
* @return The socket type.
*/
int GetType() const;
/**
* @brief Set the socket type.
*
* @param type
*/
void SetType(const int type);
/**
* @brief Get the socket protocol.
*
* @return The socket protocol.
*/
int GetProtocol() const;
/**
* @brief Set the socket protocol.
*
* @param protocol
*/
void SetProtocol(const int protocol);
/**
* @brief Clear the socket address.
*
* All bytes of the Address union are set to 0.
*/
void Clear();
/**
* @brief Get the port number, in local endian.
*
* @return Port number.
*
* @throw Exception if the address isn't an ipv4 or ipv6 address.
*/
ACTIV_BASE_API uint16_t GetPort() const;
/**
* @brief Set the port number.
*
* @param port Port number in local endian.
*
* @throw Exception if the address isn't an ipv4 or ipv6 address.
*/
ACTIV_BASE_API void SetPort(const uint16_t port);
#if (!defined ACTIV_LITE_FRAMEWORK)
/**
* @brief Get the interface index of a local ipv6 address.
*
* @throw Exception.
*/
ACTIV_BASE_API uint32_t GetInterfaceIndex() const;
/**
* @brief Is this a loopback address?
*
* @return Whether this is a loopback address.
*
* @throw Exception if the address isn't an ipv4 or ipv6 address.
*/
ACTIV_BASE_API bool IsLoopback() const;
/**
* @brief Is this a local address on the machine?
*
* The current implementation of this function is not optimized and should be used sparingly.
*
* @return Whether this is a local address.
*/
ACTIV_BASE_API bool IsLocal() const;
#endif // (!defined ACTIV_LITE_FRAMEWORK)
/**
* @brief Is this a link-local address?
*
* @return Whether this is a link-local address.
*/
ACTIV_BASE_API bool IsLinkLocal() const;
/**
* @brief Is this an unspecified address (aka an 'any' address)?
*
* @return Whether this is an unspecified address.
*
* @throw Exception if the address isn't an ipv4 or ipv6 address.
*/
ACTIV_BASE_API bool IsUnspecified() const;
/**
* @brief Is this a multicast address?
*
* @return Whether this is a multicast address.
*
* @throw Exception if the address isn't an ipv4 or ipv6 address.
*/
ACTIV_BASE_API bool IsMulticast() const;
/**
* @brief Is this address on the same network as the provided address and mask?
*
* @param network
*
* @return Boolean
*/
ACTIV_BASE_API bool IsOnNetwork(const IpAddressMask &network) const;
/**
* @brief Serialize.
*
* @param messageBuilder
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode Serialize(MessageBuilder &messageBuilder) const;
/**
* @brief Deserialize.
*
* @param messageValidator
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode Deserialize(MessageValidator &messageValidator);
private:
AddressUnion m_address; ///< Union of ipv4 and ipv6 addresses; use as appropriate based on Address.sa_family.
byte_t m_addressLength; ///< Size of useful info in m_address.
byte_t m_type; ///< Socket type.
byte_t m_protocol; ///< Protocol specific to address family.
};
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Type of list of ip addresses.
*/
typedef std::vector<IpAddress> IpAddressList;
// ---------------------------------------------------------------------------------------------------------------------------------
inline IpAddress::IpAddress(const int family) :
m_addressLength(0),
m_type(0),
m_protocol(0)
{
std::memset(&m_address, 0, sizeof(m_address));
m_address.Address.sa_family = family;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline IpAddress::IpAddress(const int socketType, const int protocol, const int family) :
m_addressLength(0),
m_type(static_cast<byte_t>(socketType)),
m_protocol(static_cast<byte_t>(protocol))
{
std::memset(&m_address, 0, sizeof(m_address));
m_address.Address.sa_family = family;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline int IpAddress::Compare(const IpAddress &rhs) const
{
if (m_addressLength != rhs.m_addressLength)
{
const byte_t compareLength = GetMinimum<byte_t>(m_addressLength, rhs.m_addressLength);
const int compareValue = std::memcmp(&m_address, &rhs.m_address, compareLength);
if (0 == compareValue)
return (m_addressLength == compareLength) ? -1 : 1;
else
return compareValue;
}
else
{
return std::memcmp(&m_address, &rhs.m_address, m_addressLength);
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool IpAddress::operator==(const IpAddress &rhs) const
{
return 0 == Compare(rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool IpAddress::operator!=(const IpAddress &rhs) const
{
return 0 != Compare(rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool IpAddress::operator<(const IpAddress &rhs) const
{
return Compare(rhs) < 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline sa_family_t IpAddress::GetFamily() const
{
return m_address.Address.sa_family;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IpAddress::SetFamily(const sa_family_t family)
{
m_address.Address.sa_family = family;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline socklen_t IpAddress::GetLength() const
{
return m_addressLength;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IpAddress::SetLength(const socklen_t length)
{
m_addressLength = static_cast<byte_t>(length);
#if (defined ACTIV_PLATFORM_OSX)
m_address.Address.sa_len = length;
#elif (defined ACTIV_PLATFORM_BSD)
m_address.Address.sin_len = length;
#endif
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline IpAddress::AddressUnion &IpAddress::GetAddress()
{
return m_address;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const IpAddress::AddressUnion &IpAddress::GetAddress() const
{
return m_address;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline int IpAddress::GetType() const
{
return m_type;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IpAddress::SetType(const int type)
{
m_type = static_cast<byte_t>(type);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline int IpAddress::GetProtocol() const
{
return m_protocol;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IpAddress::SetProtocol(const int protocol)
{
m_protocol = static_cast<byte_t>(protocol);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IpAddress::Clear()
{
std::memset(&m_address, 0, sizeof(m_address));
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Extension of IpAddress with netmask length.
*/
class IpAddressMask : public IpAddress
{
public:
/**
* @brief Constructor.
*
* The socket type, protocol and netmask length are initialized to 0.
*
* @param family the address family.
*/
IpAddressMask(const int family = AF_UNSPEC);
/**
* @brief Constructor.
*
* @param ipAddress
* @param netMaskLength
*/
IpAddressMask(const IpAddress &ipAddress, const size_t netMaskLength);
size_t m_netMaskLength; ///< Length of the network mask, in bits.
};
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Type of list of ip address masks.
*/
typedef std::vector<IpAddressMask> IpAddressMaskList;
// ---------------------------------------------------------------------------------------------------------------------------------
inline IpAddressMask::IpAddressMask(const int family) :
IpAddress(family),
m_netMaskLength(0)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline IpAddressMask::IpAddressMask(const IpAddress &ipAddress, const size_t netMaskLength) :
IpAddress(ipAddress),
m_netMaskLength(netMaskLength)
{
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_IP_ADDRESS_H)
@@ -1,71 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Ip/IpException.h
*
* @brief Header file for the Ip exception class.
*/
#if (!defined ACTIV_BASE_IP_IP_EXCEPTION_H)
#define ACTIV_BASE_IP_IP_EXCEPTION_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Exception.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief The list of possible errors and their strings.
*
* Note this list is converted to an enum using the ACTIV_DECLARE_ELEMENT_1 macro in ActivMiddleware.h,
* and the strings are unpicked using ACTIV_DECLARE_ELEMENT_2.
*/
#define ACTIV_BASE_IP_EXCEPTION_LIST(d) \
d(ERROR_UNACCEPTABLE_WINSOCK_VERSION, "unacceptable winsock version") \
d(ERROR_INVALID_FUNCTION_POINTER_LENGTH, "invalid function pointer length") \
d(ERROR_MULTIPLE_CLOSES_PERFORMED, "multiple closes performed on socket") \
d(ERROR_ALREADY_LISTENING, "already listening") \
d(ERROR_NOT_LISTENING, "not listening") \
d(ERROR_RX_BUFFER_SIZE_NOT_SET, "rx buffer size not set correctly") \
d(ERROR_TX_BUFFER_SIZE_NOT_SET, "tx buffer size not set correctly") \
d(ERROR_MANAGED_OBJECTS_STILL_EXIST, "managed objects still exist") \
d(ERROR_ADDRESS_FAMILIES_DO_NOT_MATCH, "address families do not match") \
d(ERROR_INVALID_ADDRESS_FAMILY, "invalid address family") \
d(ERROR_INTERFACE_INDEX_MISMATCH, "interface index mismatch") \
d(ERROR_FAILED_TO_POST_READ, "failed to post read")
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Ip exception class.
*/
class IpException : public Exception
{
public:
/**
* @brief Enumeration of all IpException errors.
*/
enum
{
ACTIV_BASE_IP_EXCEPTION_LIST(ACTIV_DECLARE_ELEMENT_1_WITH_COMMA)
NUM_ERRORS
};
/**
* @brief Default constructor.
*
* @param file the file which raised the exception.
* @param function the function which raised the exception.
* @param line the line number which raised the exception.
* @param errorCode the exception specific error code.
* @param message the exception message.
*/
ACTIV_BASE_API IpException(const char *file, const char *function, const uint_fast32_t line, const uint_fast32_t errorCode,
const String &message = "");
ACTIV_BASE_API virtual String ToString() const ACTIV_OVERRIDE;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_IP_EXCEPTION_H)
@@ -1,31 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Ip/IpManager.h
*
* @brief Header file for base ip manager class.
*/
#if (!defined ACTIV_BASE_IP_IP_MANAGER_H)
#define ACTIV_BASE_IP_IP_MANAGER_H
#include "ActivMiddleware/ActivBase/External.h"
#if (defined ACTIV_PLATFORM_WINDOWS)
#include "../Windows/Ip/IpManager.h"
#elif (defined ACTIV_PLATFORM_POSIX)
#include "../Posix/Ip/IpManager.h"
#else
#error No IpManager.h for this platform yet.
#endif
//! Activ namespace.
namespace Activ
{
inline const IpManager::Settings &IpManager::GetSettings() const
{
return m_settings;
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_IP_MANAGER_H)
@@ -1,133 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Ip/IpSocket.h
*
* @brief Header file for ip socket class.
*/
#if (!defined ACTIV_BASE_IP_IP_SOCKET_H)
#define ACTIV_BASE_IP_IP_SOCKET_H
#include "ActivMiddleware/ActivBase/External.h"
#if (defined ACTIV_PLATFORM_WINDOWS)
#include "../Windows/Ip/IpSocket.h"
#elif (defined ACTIV_PLATFORM_POSIX)
#include "../Posix/Ip/IpSocket.h"
#else
#error No IpSocket.h for this platform yet.
#endif
//! Activ namespace.
namespace Activ
{
inline void IpSocket::AppendRxBuffer(void *pData, const size_t dataLength)
{
return m_rxBuffers.Append(pData, dataLength);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline IpBufferHelper &IpSocket::GetRxBuffers()
{
return m_rxBuffers;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const IpBufferHelper &IpSocket::GetRxBuffers() const
{
return m_rxBuffers;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IpSocket::EnableCustomRx()
{
m_isCustomRx = true;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IpSocket::AppendTxBuffer(const void *pData, const size_t dataLength)
{
return m_txBuffers.Append(const_cast<void *>(pData), dataLength);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline IpBufferHelper &IpSocket::GetTxBuffers()
{
return m_txBuffers;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const IpBufferHelper &IpSocket::GetTxBuffers() const
{
return m_txBuffers;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IpSocket::EnableCustomTx()
{
m_isCustomTx = true;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline IpManager &IpSocket::GetIpManager() const
{
return m_ipManager;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool IpSocket::IsInCallback() const
{
return (0 != m_inCallbackCount);
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline IpSocket::ScopedIsInCallback::ScopedIsInCallback(IpSocket &ipSocket) :
m_ipSocket(ipSocket)
{
++m_ipSocket.m_inCallbackCount;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline IpSocket::ScopedIsInCallback::~ScopedIsInCallback()
{
--m_ipSocket.m_inCallbackCount;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename SOCKET_TYPE>
typename SOCKET_TYPE::Stats IpSocket::Stats::Get(const SOCKET_TYPE &socket)
{
const IpSocket &ipSocket = socket;
ScopedMutexLocker scopedMutexLocker(ipSocket.m_pMutex);
return typename SOCKET_TYPE::Stats(socket);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename SOCKET_TYPE>
typename SOCKET_TYPE::Stats *IpSocket::Stats::Create(const SOCKET_TYPE &socket)
{
const IpSocket &ipSocket = socket;
ScopedMutexLocker scopedMutexLocker(ipSocket.m_pMutex);
return new typename SOCKET_TYPE::Stats(socket);
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_IP_SOCKET_H)
@@ -1,171 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Ip/NetworkAffinityFilter.h
*
* @brief Header file for network affinity filter class.
*/
#if (!defined ACTIV_BASE_IP_NETWORK_AFFINITY_FILTER_H)
#define ACTIV_BASE_IP_NETWORK_AFFINITY_FILTER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/SInt.h"
#include "ActivMiddleware/ActivBase/IniFileParser.h"
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
//! Activ namespace.
namespace Activ
{
//! Network affinity filter.
class NetworkAffinityFilter
{
public:
//! Settings class.
class Settings
{
public:
//! Default constructor.
ACTIV_BASE_API Settings();
/**
* @brief Read settings from an ini file section.
*
* @param sectionIterator iterator to an ini file section.
*
* @throw Exception
*/
ACTIV_BASE_API void Read(const IniFileParser::ConstSectionIterator &sectionIterator);
//! Is initialized.
ACTIV_BASE_API bool IsInitialized() const;
//! To string.
ACTIV_BASE_API String ToString() const;
SInt m_cpu; ///< Default: [NotInitialized]. The cpu core to bind the filter to. -1 will result in using the core this thread is currently running on.
SInt m_receiveQueue; ///< Default: [NotInitialized]. The NIC receive queue to bind the filter to.
};
//! Default Constructor.
ACTIV_BASE_API NetworkAffinityFilter();
/**
* @brief Constructor.
*
* @param settings
*/
ACTIV_BASE_API NetworkAffinityFilter(const Settings &settings);
/**
* @brief Constructor.
*
* @param settings
* @param interfaceIpAddress
* @param localIpAddress
* @param remoteIpAddress
*/
ACTIV_BASE_API NetworkAffinityFilter(const Settings &settings, const IpAddress &interfaceIpAddress,
const IpAddress &localIpAddress, const IpAddress &remoteIpAddress = IpAddress());
/**
* @brief Less than operator.
*
* Only addresses are included in the comparison.
*
* @param rhs reference to a Filter object to compare.
*
* @retval true if this is less than rhs.
* @retval false if this is greater than or equal to rhs.
*/
ACTIV_BASE_API bool operator<(const NetworkAffinityFilter &rhs) const;
/**
* @brief Serialize.
*
* @param messageBuilder
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode Serialize(MessageBuilder &messageBuilder) const;
/**
* @brief Deserialize.
*
* @param messageValidator
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode Deserialize(MessageValidator &messageValidator);
//! Get protocol.
ACTIV_BASE_API int GetProtocol() const;
//! Get cpu affinity.
ACTIV_BASE_API int32_t GetCpuAffinity() const;
//! Get receive queue affinity.
ACTIV_BASE_API int32_t GetReceiveQueueAffinity() const;
/**
* @brief Set interface IpAddress.
*
* @param interfaceIpAddress
*/
ACTIV_BASE_API void SetInterfaceIpAddress(const IpAddress &interfaceIpAddress);
//! Get interface address.
ACTIV_BASE_API const IpAddress &GetInterfaceIpAddress() const;
/**
* @brief Set local IpAddress.
*
* @param localIpAddress
*/
ACTIV_BASE_API void SetLocalIpAddress(const IpAddress &localIpAddress);
//! Get local address.
ACTIV_BASE_API const IpAddress &GetLocalIpAddress() const;
/**
* @brief Set remote IpAddress.
*
* @param remoteIpAddress
*/
ACTIV_BASE_API void SetRemoteIpAddress(const IpAddress &remoteIpAddress);
//! Get remote address.
ACTIV_BASE_API const IpAddress &GetRemoteIpAddress() const;
//! Is initialized.
ACTIV_BASE_API bool IsInitialized() const;
/**
* @brief Convert to a string for display purposes.
*
* @return String.
*/
ACTIV_BASE_API const String ToString() const;
/**
* @brief Convert to a short string for display purposes.
*
* @return String.
*/
ACTIV_BASE_API const String ToShortString() const;
private:
bool m_isInitialized;
int32_t m_cpu; ///< The cpu core to bind the filter to.
int32_t m_receiveQueue; ///< The NIC receive queue to bind the filter to.
IpAddress m_interfaceIpAddress; ///< The interface to add the filter to.
IpAddress m_localIpAddress; ///< Local address to add the filter for (possibly a multicast destination).
IpAddress m_remoteIpAddress; ///< The remote address to add the filter for.
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_NETWORK_AFFINITY_FILTER_H)
@@ -1,447 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Ip/SocketHelper.h
*
* @brief Header file for socket helper functions.
*/
#if (!defined ACTIV_BASE_IP_SOCKET_HELPER_H)
#define ACTIV_BASE_IP_SOCKET_HELPER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/OsException.h"
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
#include "ActivMiddleware/ActivBase/Ip/IpException.h"
#include "ActivMiddleware/ActivBase/Ip/IpManager.h"
#include <fcntl.h>
//! Activ namespace.
namespace Activ
{
//! SocketHelper namespace.
namespace SocketHelper
{
/**
* @brief Create a bound non-block, no clone socket.
*
* @param localAddress address to use for socket create (will be updated with used port if binding to 0).
* @param shouldSetReUseAddrSocketOption whether the SO_REUSEADDR socket option be set.
*
* @return the socket handle.
*
* @throw OsException
*/
ACTIV_BASE_API SOCKET CreateBoundSocket(IpAddress &localAddress, const bool shouldSetReUseAddrSocketOption = true);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set socket option.
*
* @param socket
* @param optionName
* @param pOptionValue
* @param optionLength
* @param level
*
* @throw OsException
*/
ACTIV_BASE_API void SetSocketOption(const SOCKET socket, const int optionName, const char *pOptionValue,
const socklen_t optionLength, const int level);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get socket option.
*
* @param socket
* @param optionName
* @param pOptionValue
* @param pOptionLength
* @param level
*
* @throw OsException
*/
ACTIV_BASE_API void GetSocketOption(const SOCKET socket, const int optionName, char *pOptionValue, socklen_t *pOptionLength,
const int level);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get rx buffer size.
*
* @param socket socket handle to get the rx buffer size of.
* @param size rx buffer size.
*
* @throw OsException
*/
ACTIV_BASE_API void GetRxBufferSize(const SOCKET socket, int &size);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set rx buffer size.
*
* @param socket socket handle to modify the rx buffer size of.
* @param size new rx buffer size.
*
* @throw OsException
* @throw LogMessageException
*/
ACTIV_BASE_API void SetRxBufferSize(const SOCKET socket, const int size);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get tx buffer size.
*
* @param socket socket handle to get the tx buffer size of.
* @param size tx buffer size.
*
* @throw OsException
*/
ACTIV_BASE_API void GetTxBufferSize(const SOCKET socket, int &size);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set tx buffer size.
*
* @param socket socket handle to modify the tx buffer size of.
* @param size new tx buffer size.
*
* @throw OsException
* @throw LogMessageException
*/
ACTIV_BASE_API void SetTxBufferSize(const SOCKET socket, const int size);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get type of service.
*
* @param socket socket handle to get the type of service for.modify the multicast ttl of.
* @param typeOfService the sockets current type of service.
*
* @throw OsException
*/
ACTIV_BASE_API void GetTypeOfService(const SOCKET socket, byte_t &typeOfService);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set type of service.
*
* @param socket socket handle to set the type of service for.
* @param typeOfService the type of service to set.
*
* @throw OsException
*/
ACTIV_BASE_API void SetTypeOfService(const SOCKET socket, const byte_t typeOfService);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set non-blocking.
*
* @param socket socket handle to set to non-blocking for.
*
* @throw OsException
*/
ACTIV_BASE_API void SetNonBlocking(const SOCKET socket);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Disable clone on exec.
*
* @param socket socket handle to disable cloning for.
*
* @throw OsException
*/
ACTIV_BASE_API void DisableCloneOnExec(const SOCKET socket);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Duplicate a socket.
*
* @param socket
*
* @return The duplicated socket or INVALID_SOCKET.
*/
ACTIV_BASE_API SOCKET DuplicateSocket(const SOCKET socket);
// ---------------------------------------------------------------------------------------------------------------------------------
//! Udp namespace.
namespace Udp
{
/**
* @brief Create socket.
*
* @param localAddress address to use for socket create (will be updated with used port if binding to 0).
* @param shouldSetReUseAddrSocketOption whether the SO_REUSEADDR socket option be set.
*
* @return the socket handle.
*
* @throw OsException
*/
ACTIV_BASE_API SOCKET CreateSocket(IpAddress &localAddress, const bool shouldSetReUseAddrSocketOption = true);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Connect.
*
* @param socket socket handle to connect.
* @param remoteAddress the remote address to connect to.
*
* @throw OsException
*/
ACTIV_BASE_API void Connect(const SOCKET socket, const IpAddress &remoteAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Disconnect.
*
* @param socket socket handle to disconnect.
*
* @throw OsException
*/
ACTIV_BASE_API void Disconnect(const SOCKET socket);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Join multicast group.
*
* @param socket socket handle to add the multicast group membership to.
* @param multicastAddress multicast group address.
* @param interfaceAddress interface address.
*
* @throw OsException
*/
ACTIV_BASE_API void JoinMulticastGroup(const SOCKET socket, const IpAddress &multicastAddress, const IpAddress &interfaceAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Join multicast group with source specific multicast filtering.
*
* @param socket socket handle to add the multicast group membership to.
* @param multicastAddress multicast group address.
* @param interfaceAddress interface address.
* @param sourceAddress source address. If !sourceAddress.IsUnspecified(), a source specific multicast join is attempted.
*
* @throw OsException
*/
ACTIV_BASE_API void JoinMulticastGroup(const SOCKET socket, const IpAddress &multicastAddress, const IpAddress &interfaceAddress,
const IpAddress &sourceAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Leave multicast group.
*
* @param socket socket handle to add the multicast group membership to.
* @param multicastAddress multicast group address.
* @param interfaceAddress interface address.
*
* @throw OsException
*/
ACTIV_BASE_API void LeaveMulticastGroup(const SOCKET socket, const IpAddress &multicastAddress, const IpAddress &interfaceAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Leave multicast group with source specific multicast filtering.
*
* @param socket socket handle to add the multicast group membership to.
* @param multicastAddress multicast group address.
* @param interfaceAddress interface address.
* @param sourceAddress source address. If !sourceAddress.IsUnspecified(), a source specific multicast leave is attempted.
*
* @throw OsException
*/
ACTIV_BASE_API void LeaveMulticastGroup(const SOCKET socket, const IpAddress &multicastAddress, const IpAddress &interfaceAddress,
const IpAddress &sourceAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set multicast TX interface.
*
* @param socket socket handle to modify the multicast tx interface of.
* @param interfaceAddressString string representation of the interface address to use.
*
* @throw OsException
*/
ACTIV_BASE_API void SetMulticastTxInterface(const SOCKET socket, const String &interfaceAddressString);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set multicast ttl.
*
* @param socket socket handle to modify the multicast ttl of.
* @param localAddress to determine family.
* @param ttl new multicast ttl.
*
* @throw OsException
*/
ACTIV_BASE_API void SetMulticastTtl(const SOCKET socket, IpAddress localAddress, const int ttl);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set unicast ttl.
*
* @param socket socket handle to modify the multicast ttl of.
* @param localAddress to determine family.
* @param ttl new unicast ttl.
*
* @throw OsException
*/
ACTIV_BASE_API void SetUnicastTtl(const SOCKET socket, IpAddress localAddress, const int ttl);
} // namespace Udp
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! Tcp namespace.
namespace Tcp
{
/**
* @brief Connect.
*
* @param socket socket handle to connect.
* @param remoteAddress the remote address to connect to.
*
* @throw OsException
*/
ACTIV_BASE_API void Connect(const SOCKET socket, const IpAddress &remoteAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Async connect.
*
* @param socket socket handle to connect.
* @param remoteAddress the remote address to connect to.
*
* @throw OsException
*/
ACTIV_BASE_API void AsyncConnect(const SOCKET socket, const IpAddress &remoteAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Enable Nagle.
*
* @param socket socket handle to disable Nagle for.
*
* @throw OsException
*/
ACTIV_BASE_API void EnableNagle(const SOCKET socket);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Disable Nagle.
*
* @param socket socket handle to disable Nagle for.
*
* @throw OsException
*/
ACTIV_BASE_API void DisableNagle(const SOCKET socket);
} // namespace Tcp
} // namespace SocketHelper
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Scoped addrinfo helper class.
*
* This takes a pointer to freeaddrinfo() to cope with dynamic loading of the library providing it.
*/
class ScopedAddrInfo : private Boost::noncopyable
{
public:
#if (defined ACTIV_PLATFORM_WINDOWS)
typedef void (WINAPI *FreeAddrInfoPtr)(addrinfo FAR *);
#else
typedef void (*FreeAddrInfoPtr)(addrinfo *);
#endif
/**
* @brief Constructor.
*
* @param pFreeAddrInfo pointer to freeaddrinfo() function.
*/
ScopedAddrInfo(FreeAddrInfoPtr pFreeAddrInfo) :
m_pAddrInfo(0),
m_pFreeAddrInfo(pFreeAddrInfo)
{
}
/**
* @brief Constructor.
*
* @param pAddrInfo addrinfo pointer to manage.
* @param pFreeAddrInfo pointer to freeaddrinfo() function.
*/
ScopedAddrInfo(addrinfo *pAddrInfo, FreeAddrInfoPtr pFreeAddrInfo) :
m_pAddrInfo(pAddrInfo),
m_pFreeAddrInfo(pFreeAddrInfo)
{
}
//! Destructor. Calls freeaddrinfo() on a non-NULL managed pointer.
~ScopedAddrInfo()
{
if ((0 != m_pAddrInfo) && (0 != m_pFreeAddrInfo))
m_pFreeAddrInfo(m_pAddrInfo);
}
//! Accessor for managed pointer.
operator addrinfo*()
{
return m_pAddrInfo;
}
//! Const accessor for managed pointer.
operator const addrinfo*() const
{
return m_pAddrInfo;
}
//! Accessor for managed pointer.
addrinfo *operator->()
{
return m_pAddrInfo;
}
//! Address of operator.
addrinfo **operator&()
{
return &m_pAddrInfo;
}
private:
addrinfo * m_pAddrInfo;
FreeAddrInfoPtr m_pFreeAddrInfo;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_SOCKET_HELPER_H)
@@ -1,201 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Ip/SocketWrapper.h
*
* @brief Header file for socket wrapper class.
*/
#if (!defined ACTIV_BASE_IP_SOCKET_WRAPPER_H)
#define ACTIV_BASE_IP_SOCKET_WRAPPER_H
#include "ActivMiddleware/ActivBase/External.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Socket wrapper class.
*
* Allows cleaning up of a socket if an exception is thrown.
*/
class SocketWrapper
{
public:
/**
* @brief Default constructor.
*/
SocketWrapper();
/**
* @brief Constructor.
*
* @param socket SOCKET handle to wrap.
*/
SocketWrapper(const SOCKET socket);
/**
* @brief Copy constructor.
*
* If rhs has an attached socket, ownership is transferred to this.
*
* @param rhs SocketWrapper to copy from.
*/
SocketWrapper(SocketWrapper &rhs);
/**
* @brief Destructor.
*
* The destructor will close the underlying socket if it is still attached to this.
*/
~SocketWrapper();
/**
* @brief Assignment operator. Any current attached socket is closed.
*
* @param socket SOCKET handle to wrap.
*/
SocketWrapper &operator=(const SOCKET socket);
/**
* @brief Assignment operator. Any current attached socket is closed.
*
* If rhs has an attached socket, ownership is transferred to this.
*
* @param rhs SocketWrapper to copy from.
*/
SocketWrapper &operator=(SocketWrapper &rhs);
/**
* @brief Cast operator to SOCKET.
*
* @return Underlying socket.
*/
operator SOCKET() const;
#if (defined ACTIV_PLATFORM_WINDOWS)
/**
* @brief Cast operator to HANDLE.
*
* @return Underlying socket.
*/
operator HANDLE() const;
#endif
/**
* @brief Test if socket attached is valid.
*
* @return true if attached to a valid socket handle.
*/
bool IsValid() const;
/**
* @brief Close the underlying socket handle.
*/
void Close();
private:
/**
* @brief Attach a socket.
*/
void Attach(const SOCKET socket);
SOCKET m_socket; ///< socket handle.
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline SocketWrapper::SocketWrapper() :
m_socket(INVALID_SOCKET)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline SocketWrapper::SocketWrapper(const SOCKET socket) :
m_socket(socket)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline SocketWrapper::SocketWrapper(SocketWrapper &rhs) :
m_socket(INVALID_SOCKET)
{
*this = rhs;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline SocketWrapper::~SocketWrapper()
{
Attach(INVALID_SOCKET);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline SocketWrapper &SocketWrapper::operator=(SocketWrapper &rhs)
{
if (this == &rhs)
return *this;
*this = rhs.m_socket;
rhs.m_socket = INVALID_SOCKET;
return *this;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline SocketWrapper &SocketWrapper::operator=(const SOCKET socket)
{
Attach(socket);
return *this;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline SocketWrapper::operator SOCKET() const
{
return m_socket;
}
// ---------------------------------------------------------------------------------------------------------------------------------
#if (defined ACTIV_PLATFORM_WINDOWS)
inline SocketWrapper::operator HANDLE() const
{
return reinterpret_cast<HANDLE>(m_socket);
}
#endif
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool SocketWrapper::IsValid() const
{
return (INVALID_SOCKET != m_socket);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void SocketWrapper::Close()
{
if (IsValid())
(void) closesocket(m_socket);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void SocketWrapper::Attach(const SOCKET socket)
{
Close();
m_socket = socket;
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_SOCKET_WRAPPER_H)
@@ -1,20 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Ip/TcpListener.h
*
* @brief Header file for tcp listener class.
*/
#if (!defined ACTIV_BASE_IP_TCP_LISTENER_H)
#define ACTIV_BASE_IP_TCP_LISTENER_H
#include "ActivMiddleware/ActivBase/External.h"
#if (defined ACTIV_PLATFORM_WINDOWS)
#include "../Windows/Ip/TcpListener.h"
#elif (defined ACTIV_PLATFORM_POSIX)
#include "../Posix/Ip/TcpListener.h"
#else
#error No TcpListener.h for this platform yet.
#endif
#endif // (!defined ACTIV_BASE_IP_TCP_LISTENER_H)
@@ -1,38 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Ip/TcpSocket.h
*
* @brief Header file for tcp socket class.
*/
#if (!defined ACTIV_BASE_IP_TCP_SOCKET_H)
#define ACTIV_BASE_IP_TCP_SOCKET_H
#include "ActivMiddleware/ActivBase/External.h"
#if (defined ACTIV_PLATFORM_WINDOWS)
#include "../Windows/Ip/TcpSocket.h"
#elif (defined ACTIV_PLATFORM_POSIX)
#include "../Posix/Ip/TcpSocket.h"
#else
#error No TcpSocket.h for this platform yet.
#endif
//! Activ namespace.
namespace Activ
{
inline TcpSocket::State TcpSocket::GetState() const
{
return m_state;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void TcpSocket::PreLockedEnableShutdown(const bool isEnabled)
{
m_isShutdownEnabled = isEnabled;
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_TCP_SOCKET_H)
@@ -1,56 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Ip/UdpDatagramInfo.h
*
* @brief Header file for udp datagram info class.
*/
#if (!defined ACTIV_BASE_IP_UDP_DATAGRAM_INFO_H)
#define ACTIV_BASE_IP_UDP_DATAGRAM_INFO_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#include "ActivMiddleware/Misc/CrtHelper.h"
//! Activ namespace.
namespace Activ
{
//! UdpDatagramInfo class.
class UdpDatagramInfo
{
public:
const void * m_pData; ///< Pointer to the start of the data.
size_t m_dataLength; ///< The length of the data.
const timespec * m_pTimestamp; ///< Pointer to the optional recieve timestamp for the data. Only set if receive timestamping is enabled.
IpAddress m_sourceIpAddress; ///< The ip address that is the source of the data.
const uint8_t * m_pSourceMacAddress; ///< Pointer to the optional source MAC address. Will only be set if received by kernel bypass.
//! Constructor.
UdpDatagramInfo();
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline UdpDatagramInfo::UdpDatagramInfo() :
m_pData(ACTIV_NULLPTR),
m_dataLength(0),
m_pTimestamp(ACTIV_NULLPTR),
m_pSourceMacAddress(ACTIV_NULLPTR)
{
m_sourceIpAddress.SetFamily(AF_INET);
m_sourceIpAddress.SetLength(sizeof(m_sourceIpAddress.GetAddress().AddressIn));
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! Receive callback function type definition.
typedef CxxYZ::function<void (const UdpDatagramInfo &udpDatagramInfo)> UdpDatagramCallbackFunction;
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_UDP_DATAGRAM_INFO_H)
@@ -1,364 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Ip/UdpPacketBuilder.h
*
* @brief Header for the UdpPacketBuilder class.
*/
#if (!defined ACTIV_BASE_IP_UDP_PACKET_BUILDER_H)
#define ACTIV_BASE_IP_UDP_PACKET_BUILDER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/MessageBuilder.h"
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
#include "ActivMiddleware/Misc/MacAddress.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief UdpPacketBuilder class.
*
* This class can be used to build udp packets. The AppendMessage() functions provided will build the message by appending a
* uint16_t with the length of the message, followed by the message itself. To send a more generic message the MessageBuilder can
* be used directly with GetMessageBuilder() and GetUdpPayloadOffset().
*/
class UdpPacketBuilder
{
public:
//! Default constructor.
ACTIV_BASE_API UdpPacketBuilder();
/**
* @brief Set the destination MacAddress.
*
* @param macAddress the MacAddress.
*
* @throws Exception
*/
void SetDestinationMacAddress(const MacAddress &macAddress);
/**
* @brief Set the source MacAddress.
*
* @param macAddress the MacAddress.
*
* @throws Exception
*/
void SetSourceMacAddress(const MacAddress &macAddress);
/**
* @brief Set the vlan id.
*
* @param vlanId the vlan id.
*
* @throws Exception
*/
ACTIV_BASE_API void SetVlanId(const uint16_t vlanId);
/**
* @brief Set the TTL.
*
* @param ttl the TTL.
*
* @throws Exception
*/
void SetTtl(const uint8_t ttl);
/**
* @brief Set the source IpAddress.
*
* @param ipAddress the IpAddress.
*
* @throws Exception
*/
void SetSourceIpAddress(const IpAddress &ipAddress);
/**
* @brief Set the destination IpAddress.
*
* @param ipAddress the IpAddress.
*
* @throws Exception
*/
void SetDestinationIpAddress(const IpAddress &ipAddress);
/**
* @brief Set the source port.
*
* @param port the port.
*
* @throws Exception
*/
void SetSourcePort(const uint16_t port);
/**
* @brief Set the destination port.
*
* @param port the port.
*
* @throws Exception
*/
void SetDestinationPort(const uint16_t port);
/**
* @brief Get the message builder.
*
* Use the message builder to write the udp payload into.
*
* When the packet is finalized use the message builder to access the full Ethernet packet.
*/
MessageBuilder &GetMessageBuilder();
/**
* @brief Get the const message builder.
*
* When the packet is finalized use the message builder to access the full Ethernet packet.
*/
const MessageBuilder &GetMessageBuilder() const;
//! Get udp payload offset.
size_t GetUdpPayloadOffset() const;
/**
* @brief Finalize the packet, ready to send.
*
* Writes the length fields in the ip and udp headers.
*
* @throws Exception
*/
void Finalize();
/**
* @brief Finalize the packet, to the specified length.
*
* Writes the length fields in the ip and udp headers.
*
* @param length
*
* @throws Exception
*/
void Finalize(const size_t length);
/**
* @brief Reset the packet.
*
* The udp payload will be lost. The Ethernet and IP headers will be retained.
*
* @throws Exception
*/
void Reset();
/**
* @brief Append a message.
*
* @param function function taking a MessageBuilder, that will write the message.
*
* @throws Exception
*/
template <typename F>
void AppendMessage(const F &function);
/**
* @brief Append a message.
*
* @param pMessage
* @param length
*
* @throws Exception
*/
void AppendMessage(const void * const pMessage, const size_t length);
private:
// Ethernet offset constants.
static const size_t ETHERNET_DST_MAC_ADDRESS_OFFSET = 0;
static const size_t ETHERNET_SRC_MAC_ADDRESS_OFFSET = ETHERNET_DST_MAC_ADDRESS_OFFSET + MacAddress::SIZE;
static const size_t ETHERNET_VLAN_TAG_OFFSET = ETHERNET_SRC_MAC_ADDRESS_OFFSET + MacAddress::SIZE;
static const size_t ETHERNET_VLAN_ID_OFFSET = ETHERNET_VLAN_TAG_OFFSET + sizeof(uint16_t);
// IP header constants with offsets from m_ipHeaderOffset.
static const size_t IP_V4_ADDRESS_LENGTH = 4;
static const size_t IP_LENGTH_OFFSET = 2;
static const size_t IP_TTL_OFFSET = 8;
static const size_t IP_SRC_IP_OFFSET = 12;
static const size_t IP_DST_IP_OFFSET = IP_SRC_IP_OFFSET + IP_V4_ADDRESS_LENGTH;
// UDP header constants with offsets from m_ipHeaderOffset.
static const size_t UDP_HEADER_LENGTH = 8;
static const size_t UDP_HEADER_START_OFFSET = IP_DST_IP_OFFSET + IP_V4_ADDRESS_LENGTH;
static const size_t UDP_SRC_PORT_OFFSET = UDP_HEADER_START_OFFSET;
static const size_t UDP_DST_PORT_OFFSET = UDP_SRC_PORT_OFFSET + sizeof(uint16_t);
static const size_t UDP_LENGTH_OFFSET = UDP_DST_PORT_OFFSET + sizeof(uint16_t);
size_t m_ipHeaderOffset;
size_t m_udpPayloadOffset;
MessageBuilder m_messageBuilder;
bool m_hasVlanTag;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline void UdpPacketBuilder::SetDestinationMacAddress(const MacAddress &macAddress)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, m_messageBuilder.OverwriteBuffer(ETHERNET_DST_MAC_ADDRESS_OFFSET,
macAddress.Get(), MacAddress::SIZE));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void UdpPacketBuilder::SetSourceMacAddress(const MacAddress &macAddress)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
m_messageBuilder.OverwriteBuffer(ETHERNET_SRC_MAC_ADDRESS_OFFSET, macAddress.Get(), MacAddress::SIZE));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void UdpPacketBuilder::SetTtl(const uint8_t ttl)
{
const size_t offset = m_ipHeaderOffset + IP_TTL_OFFSET;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
(m_messageBuilder.Overwrite<MessageHandler::ENDIAN_BIG, sizeof(uint8_t)>(offset, ttl)));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void UdpPacketBuilder::SetSourceIpAddress(const IpAddress &ipAddress)
{
const size_t offset = m_ipHeaderOffset + IP_SRC_IP_OFFSET;
const size_t value = ipAddress.GetAddress().AddressIn.sin_addr.s_addr;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
(m_messageBuilder.Overwrite<MessageHandler::ENDIAN_LOCAL, IP_V4_ADDRESS_LENGTH>(offset, value)));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void UdpPacketBuilder::SetDestinationIpAddress(const IpAddress &ipAddress)
{
const size_t offset = m_ipHeaderOffset + IP_DST_IP_OFFSET;
const size_t value = ipAddress.GetAddress().AddressIn.sin_addr.s_addr;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
(m_messageBuilder.Overwrite<MessageHandler::ENDIAN_LOCAL, IP_V4_ADDRESS_LENGTH>(offset, value)));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void UdpPacketBuilder::SetSourcePort(const uint16_t port)
{
const size_t offset = m_ipHeaderOffset + UDP_SRC_PORT_OFFSET;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
(m_messageBuilder.Overwrite<MessageHandler::ENDIAN_BIG, sizeof(uint16_t)>(offset, port)));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void UdpPacketBuilder::SetDestinationPort(const uint16_t port)
{
const size_t offset = m_ipHeaderOffset + UDP_DST_PORT_OFFSET;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
(m_messageBuilder.Overwrite<MessageHandler::ENDIAN_BIG, sizeof(uint16_t)>(offset, port)));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageBuilder &UdpPacketBuilder::GetMessageBuilder()
{
return m_messageBuilder;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const MessageBuilder &UdpPacketBuilder::GetMessageBuilder() const
{
return m_messageBuilder;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t UdpPacketBuilder::GetUdpPayloadOffset() const
{
return m_udpPayloadOffset;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void UdpPacketBuilder::Finalize()
{
Finalize(m_messageBuilder.GetLength());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void UdpPacketBuilder::Finalize(const size_t length)
{
if (ACTIV_UNLIKELY(length < m_udpPayloadOffset))
ACTIV_THROW(StatusCodeException, STATUS_CODE_INVALID_LENGTH);
// Write ip length.
size_t offset = m_ipHeaderOffset + IP_LENGTH_OFFSET;
size_t value = length - m_ipHeaderOffset;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
(m_messageBuilder.Overwrite<MessageHandler::ENDIAN_BIG, sizeof(uint16_t)>(offset, value)));
// Write udp length.
offset = m_ipHeaderOffset + UDP_LENGTH_OFFSET;
value = length - (m_ipHeaderOffset + UDP_HEADER_START_OFFSET);
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
(m_messageBuilder.Overwrite<MessageHandler::ENDIAN_BIG, sizeof(uint16_t)>(offset, value)));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void UdpPacketBuilder::Reset()
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, m_messageBuilder.SetLength(m_udpPayloadOffset));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename F>
inline void UdpPacketBuilder::AppendMessage(const F &function)
{
const size_t lengthOffset = m_messageBuilder.GetLength();
try
{
// Append zero length. Overwrite later.
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
m_messageBuilder.Append<MessageBuilder::ENDIAN_LITTLE>(uint16_t(0)));
function(m_messageBuilder);
const uint16_t messageLength =
static_cast<uint16_t>((m_messageBuilder.GetLength() - (lengthOffset + sizeof(uint16_t))));
assert ((m_messageBuilder.GetLength() - lengthOffset) <= std::numeric_limits<uint16_t>::max());
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
m_messageBuilder.Overwrite<MessageBuilder::ENDIAN_LITTLE>(lengthOffset, messageLength));
}
ACTIV_CATCH_ALL()
{
m_messageBuilder.SetLength(lengthOffset);
throw;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void UdpPacketBuilder::AppendMessage(const void * const pMessage, const size_t length)
{
assert (length <= std::numeric_limits<uint16_t>::max());
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
m_messageBuilder.Append<MessageBuilder::ENDIAN_LITTLE>(static_cast<uint16_t>(length)));
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=,
m_messageBuilder.AppendBuffer(pMessage, length));
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_UDP_PACKET_BUILDER_H)
@@ -1,20 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Ip/UdpSocket.h
*
* @brief Header file for udp socket class.
*/
#if (!defined ACTIV_BASE_IP_UDP_SOCKET_H)
#define ACTIV_BASE_IP_UDP_SOCKET_H
#include "ActivMiddleware/ActivBase/External.h"
#if (defined ACTIV_PLATFORM_WINDOWS)
#include "../Windows/Ip/UdpSocket.h"
#elif (defined ACTIV_PLATFORM_POSIX)
#include "../Posix/Ip/UdpSocket.h"
#else
#error No UdpSocket.h for this platform yet.
#endif
#endif // (!defined ACTIV_BASE_IP_UDP_SOCKET_H)
@@ -1,183 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Linux/OnloadHelper.h
*
* @brief Header file for the OnloadHelper class.
*/
#if (!defined ACTIV_BASE_LINUX_ONLOAD_HELPER_H)
#define ACTIV_BASE_LINUX_ONLOAD_HELPER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/Misc/DynamicLibraryLoader.h"
struct onload_stat;
namespace Activ
{
//! Forward declarations.
class ProcessorAffinity;
//! Onload helper class.
class OnloadHelper
{
public:
//! Default constructor.
ACTIV_BASE_API OnloadHelper();
//! Is onload available.
ACTIV_BASE_API bool IsAvailable() const;
//! Is this process onloaded.
ACTIV_BASE_API static bool IsProcessOnloaded();
/**
* @brief Does the interface refer to a device that supports onload?
*
* @param interfaceName
*
* @retval true if supported, false otherwise.
*/
ACTIV_BASE_API static bool IsSfcInterface(const String &interfaceName);
//! Get version.
const String &GetVersion() const;
/**
* @brief Disable for this process.
*
* @throw std::exception
*/
ACTIV_BASE_API static void DisableForThisProcess();
/**
* @brief Disable spinning for this thread.
*
* @throw std::exception
*/
ACTIV_BASE_API static void DisableSpinningForThisThread();
/**
* @brief Set thread stack name (enables onload for this thread).
*
* @param stackName
*
* @throw std::exception
*/
ACTIV_BASE_API void SetThreadStackName(const String &stackName) const;
/**
* @brief Configure ideal receive channel.
*
* @param processorAffinity
*
* @throw std::exception
*/
ACTIV_BASE_API void ConfigureIdealReceiveChannel(const ProcessorAffinity &processorAffinity) const;
/**
* @brief Configure receive channel.
*
* @param receiveChannel
*
* @throw std::exception
*/
ACTIV_BASE_API void ConfigureReceiveChannel(const uint16_t receiveChannel) const;
/**
* @brief Set option.
*
* @param optionName
* @param value
*
* @throw std::exception
*/
ACTIV_BASE_API void SetOption(const String &optionName, const uint64_t value) const;
/**
* @brief Is socket onloaded.
*
* @param socket
*
* @return true if the socket is onload accelerated, false otherwise.
*/
ACTIV_BASE_API bool IsSocketOnloaded(SOCKET socket) const;
/**
* @brief Get socket stack name.
*
* @param socket
*
* @return The name of the stack the socket belongs to. Empty if not accelerated.
*/
ACTIV_BASE_API const String GetSocketStackName(SOCKET socket) const;
/**
* @brief Move socket to current onload stack.
*
* @param socket
*/
ACTIV_BASE_API void MoveSocketToCurrentStack(SOCKET socket) const;
/**
* @brief Move socket to new onload stack.
*
* @param socket
* @param stackName
* @param receiveChannnel
*/
ACTIV_BASE_API void MoveSocketToStack(SOCKET socket, const String &stackName, const uint64_t receiveChannnel) const;
/**
* @brief Get the ideal receive channel for this ProcessorAffinity.
*
* @param processAffinity
*
* @return the ideal receive channel for this ProcessorAffinity.
*
* @throw StringException.
*/
ACTIV_BASE_API static uint16_t GetIdealReceiveChannel(const ProcessorAffinity &processAffinity);
private:
typedef int (onload_set_stacknameF)(int, int, const char* );
typedef int (onload_stack_opt_set_intF)(const char*, int64_t);
typedef int (onload_thread_set_spinF)(int, int);
typedef int (onload_fd_statF)(int, onload_stat *);
typedef int (onload_stackname_saveF)();
typedef int (onload_stackname_restoreF)();
typedef int (onload_move_fdF)(int);
ACTIV_DECLARE_DLL_FUNCTION(onload_set_stackname, onload_set_stacknameF, false);
ACTIV_DECLARE_DLL_FUNCTION(onload_stack_opt_set_int, onload_stack_opt_set_intF, false);
ACTIV_DECLARE_DLL_FUNCTION(onload_thread_set_spin, onload_thread_set_spinF, false);
ACTIV_DECLARE_DLL_FUNCTION(onload_fd_stat, onload_fd_statF, false);
ACTIV_DECLARE_DLL_FUNCTION(onload_stackname_save, onload_stackname_saveF, false);
ACTIV_DECLARE_DLL_FUNCTION(onload_stackname_restore, onload_stackname_restoreF, false);
ACTIV_DECLARE_DLL_FUNCTION(onload_move_fd, onload_move_fdF, false);
typedef DynamicLibraryLoader<Boost::mpl::vector<
onload_set_stackname,
onload_stack_opt_set_int,
onload_thread_set_spin,
onload_fd_stat,
onload_stackname_save,
onload_stackname_restore,
onload_move_fd>
> OnloadLoader;
const OnloadLoader m_onloadLoader;
const String m_onloadVersion;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &OnloadHelper::GetVersion() const
{
return m_onloadVersion;
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_LINUX_ONLOAD_HELPER_H)
@@ -1,57 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/LogMessageException.h
*
* @brief Header file for the LogMessageException class.
*/
#if (!defined ACTIV_BASE_LOG_MESSAGE_EXCEPTION_H)
#define ACTIV_BASE_LOG_MESSAGE_EXCEPTION_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/ActivBase.h"
#include ACTIV_BOOST_INCLUDE(exception/all.hpp)
//! Activ namespace.
namespace Activ
{
/**
* @brief LogMessage exception class.
*
* Calls LogMessage() with the provided string. Useful to both log and throw an error.
*/
class LogMessageException : public virtual Boost::exception, public virtual std::exception
{
public:
/**
* @brief Constructor.
*
* @param logType
* @param pMessage string to log.
*/
ACTIV_BASE_API LogMessageException(const LogType logType, const char * const pMessage);
/**
* @brief Constructor.
*
* @param logType
* @param message string to log.
*/
ACTIV_BASE_API LogMessageException(const LogType logType, const String &message);
/**
* @brief Destructor.
*/
ACTIV_BASE_API ~LogMessageException() throw();
// std::exception overrides.
ACTIV_BASE_API virtual const char *what() const throw() ACTIV_OVERRIDE;
private:
const String m_message;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_LOG_MESSAGE_EXCEPTION_H)
File diff suppressed because it is too large. Load diff
@@ -1,161 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/MessageHandler.h
*
* @brief Header file for the base message handler class.
*/
#if (!defined ACTIV_BASE_MESSAGE_HANDLER_H)
#define ACTIV_BASE_MESSAGE_HANDLER_H
#include "ActivMiddleware/ActivBase/External.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Base class for validator and builder.
*/
class MessageHandler
{
public:
typedef uint16_t DefaultStringLength; ///< Definition of the default string length type.
typedef uint8_t MessageVersion; ///< Definition of the version type.
static const byte_t MIN_PRINTABLE_ASCII = 0x20; ///< The minimum printable ascii character.
static const byte_t MAX_PRINTABLE_ASCII = 0x7e; ///< The maximum printable ascii character.
static const MessageVersion MESSAGE_VERSION_UNDEFINED = ~0; ///< Undefined version value.
/**
* @brief Endian enumeration.
*/
enum Endian
{
ENDIAN_LITTLE, ///< Little endian
ENDIAN_BIG, ///< Big endian
#if (defined ACTIV_LITTLE_ENDIAN)
ENDIAN_LOCAL = ENDIAN_LITTLE, ///< Local endian
ENDIAN_ALIEN = ENDIAN_BIG
#else
ENDIAN_LOCAL = ENDIAN_BIG, ///< Local endian
ENDIAN_ALIEN = ENDIAN_LITTLE
#endif
};
/**
* @brief Helper class to scope changes to message version.
*/
class ScopedVersion : private Boost::noncopyable
{
public:
/**
* @brief Constructor.
*
* Caches the current message version to restore when this object is destructed.
*
* @param messageHandler MessageHandler to set version of.
*/
ScopedVersion(MessageHandler &messageHandler);
/**
* @brief Constructor.
*
* Caches the current message version to restore when this object is destructed and
* sets the current version to a new value.
*
* @param messageHandler MessageHandler to set version of.
* @param newVersion version to set.
*/
ScopedVersion(MessageHandler &messageHandler, const MessageVersion newVersion);
/**
* @brief Destructor.
*
* The original message version is restored.
*/
~ScopedVersion();
private:
MessageHandler & m_messageHandler;
const MessageVersion m_oldVersion;
};
/**
* @brief Constructor.
*
* @param messageVersion optional version.
*/
MessageHandler(const MessageVersion messageVersion = MESSAGE_VERSION_UNDEFINED);
/**
* @brief Get the version.
*
* @return The version.
*/
MessageVersion GetMessageVersion() const;
/**
* @brief Set the version.
*
* @param messageVersion the new version to set.
*
* @return The previous version.
*/
MessageVersion SetMessageVersion(const MessageVersion messageVersion);
private:
MessageVersion m_messageVersion;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageHandler::MessageHandler(const MessageVersion messageVersion)
{
SetMessageVersion(messageVersion);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageHandler::MessageVersion MessageHandler::GetMessageVersion() const
{
return m_messageVersion;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageHandler::MessageVersion MessageHandler::SetMessageVersion(const MessageVersion messageVersion)
{
const MessageVersion oldMessageVersion = m_messageVersion;
m_messageVersion = messageVersion;
return oldMessageVersion;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageHandler::ScopedVersion::ScopedVersion(MessageHandler &messageHandler) :
m_messageHandler(messageHandler),
m_oldVersion(m_messageHandler.GetMessageVersion())
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageHandler::ScopedVersion::ScopedVersion(MessageHandler &messageHandler, const MessageVersion newVersion) :
m_messageHandler(messageHandler),
m_oldVersion(m_messageHandler.SetMessageVersion(newVersion))
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageHandler::ScopedVersion::~ScopedVersion()
{
(void) m_messageHandler.SetMessageVersion(m_oldVersion);
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_MESSAGE_HANDLER_H)
@@ -1,156 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/MessageRateThrottler.h
*
* @brief Header file for the message rate throttler class.
*/
#if (!defined ACTIV_BASE_MESSAGE_RATE_THROTTLER_H)
#define ACTIV_BASE_MESSAGE_RATE_THROTTLER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/CompartmentalizedMessageRateThrottler.h"
#include ACTIV_BOOST_INCLUDE(scoped_ptr.hpp)
//! Activ namespace.
namespace Activ
{
class IMutex;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Message rate throttler class.
*
* This class should be used when wishing to throttle a message rate, and only sleep when it is not presently possible to send.
*/
class MessageRateThrottler
{
public:
/**
* @brief Class to temporarily set a new message rate and then revert to the old rate when it goes out of scope.
*/
class ScopedMessageRate
{
public:
/**
* @brief Constructor.
*
* Set the new message rate.
*
* @param messageRateThrottler.
* @param newMessageRate the new message rate per second.
*/
ScopedMessageRate(MessageRateThrottler &messageRateThrottler, const size_t newMessageRate);
/**
* @brief Destructor.
*
* Revert to the old message rate.
*/
~ScopedMessageRate();
private:
MessageRateThrottler & m_messageRateThrottler;
const size_t m_previousMessageRate;
const size_t m_previousPeriodLength;
};
/**
* @brief Constructor.
*
* @param messagesPerSecond the message rate per second, or 0 for no throttle.
* @param shouldCreateMutex indicates whether a mutex should be created.
*/
ACTIV_BASE_API MessageRateThrottler(const size_t messagesPerSecond = 0, const bool shouldCreateMutex = false);
/**
* @brief Constructor.
*
* @param messagesPerSecond the message rate per second, or 0 for no throttle.
* @param periodLength the period length (in milliseconds) to throttle over. Must be a factor of 1000.
* @param shouldCreateMutex indicates whether a mutex should be created.
*
* @throw StatusCodeException
*/
ACTIV_BASE_API MessageRateThrottler(const size_t messagesPerSecond, const size_t periodLength,
const bool shouldCreateMutex = false);
/**
* @brief Destructor.
*/
ACTIV_BASE_API ~MessageRateThrottler();
/**
* @brief Initialize.
*
* @param messagesPerSecond the message rate per second, or 0 for no throttle.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_BASE_API StatusCode Initialize(const size_t messagesPerSecond);
/**
* @brief Initialize.
*
* @param messagesPerSecond the message rate per second, or 0 for no throttle.
* @param periodLength the period length (in milliseconds) to throttle over. Must be a factor of 1000.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_BASE_API StatusCode Initialize(const size_t messagesPerSecond, const size_t periodLength);
/**
* @brief Get the message rate.
*
* @return The message rate in messages per second.
*/
ACTIV_BASE_API size_t GetMessageRate() const;
/**
* @brief Get the period length.
*
* @return The period length.
*/
ACTIV_BASE_API size_t GetPeriodLength() const;
/**
* @brief Reset.
*/
ACTIV_BASE_API void Reset();
/**
* @brief Run the throttler.
*
* May suspend the calling thread for a period of time in order to throttle.
*/
ACTIV_BASE_API void Suspend();
private:
Boost::scoped_ptr<IMutex> m_pMutex;
CompartmentalizedMessageRateThrottler m_compartmentalizedMessageRateThrottler;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageRateThrottler::ScopedMessageRate::ScopedMessageRate(MessageRateThrottler &messageRateThrottler,
const size_t newMessageRate) :
m_messageRateThrottler(messageRateThrottler),
m_previousMessageRate(messageRateThrottler.GetMessageRate()),
m_previousPeriodLength(messageRateThrottler.GetPeriodLength())
{
messageRateThrottler.Initialize(newMessageRate, m_previousPeriodLength);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageRateThrottler::ScopedMessageRate::~ScopedMessageRate()
{
m_messageRateThrottler.Initialize(m_previousMessageRate, m_previousPeriodLength);
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_MESSAGE_RATE_THROTTLER_H)
File diff suppressed because it is too large. Load diff
@@ -1,335 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/MutexHelper.h
*
* @brief Header file for the mutex helper classes.
*/
#if (!defined ACTIV_BASE_MUTEX_HELPER_H)
#define ACTIV_BASE_MUTEX_HELPER_H
#include "ActivMiddleware/ActivBase/IMutex.h"
#include ACTIV_BOOST_INCLUDE(utility/explicit_operator_bool.hpp)
#include <cassert>
//! Activ namespace.
namespace Activ
{
/**
* @brief Scoped mutex locking helper class.
*
* The ScopedMutexLocker class wraps up locking / unlocking a mutex.
*/
class ScopedMutexLocker : private Boost::noncopyable
{
public:
/**
* @brief Constructor which obtains the mutex lock.
*
* @param pMutex pointer to the mutex to be locked. It can be null, in which case this is a no-op (as is the dtor).
*/
ScopedMutexLocker(IMutex * const pMutex);
/**
* @brief Constructor which obtains the mutex lock.
*
* @param pMutex pointer to the mutex to be locked. It can be null, in which case this is a no-op (as is the dtor).
*/
ScopedMutexLocker(const IMutex * const pMutex);
/**
* @brief Constructor which obtains the mutex lock.
*
* @param pMutex smart pointer to the mutex to be locked. It can be null, in which case this is a no-op (as is the dtor).
*/
template<typename T>
ScopedMutexLocker(T &pMutex);
//! Destructor releases the mutex lock, if a non-null mutex pointer was provided to the constructor.
~ScopedMutexLocker();
private:
const IMutex * const m_pMutex; ///< The mutex object.
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline ScopedMutexLocker::ScopedMutexLocker(IMutex * const pMutex) :
m_pMutex(pMutex)
{
if (0 != m_pMutex)
(void) m_pMutex->Acquire();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline ScopedMutexLocker::ScopedMutexLocker(const IMutex * const pMutex) :
m_pMutex(pMutex)
{
if (0 != m_pMutex)
(void) m_pMutex->Acquire();
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline ScopedMutexLocker::ScopedMutexLocker(T &pMutex) :
m_pMutex(pMutex.get())
{
if (0 != m_pMutex)
(void) m_pMutex->Acquire();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline ScopedMutexLocker::~ScopedMutexLocker()
{
if (0 != m_pMutex)
(void) m_pMutex->Release();
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Try acquire mutex helper class.
*
* The ScopedMutexTryLocker class wraps up try-locking / unlocking a mutex.
*/
class ScopedMutexTryLocker : private Boost::noncopyable
{
public:
/**
* @brief Constructor. The constructor attempts to lock the mutex.
*
* @param pMutex pointer to the mutex to be locked. It can be null. If a null mutex is provided, it is
* treated as if it is "locked". I.e. operator bool() will return true.
*/
ScopedMutexTryLocker(IMutex * const pMutex);
/**
* @brief Constructor. The constructor attempts to lock the mutex.
*
* @param pMutex pointer to the mutex to be locked. It can be null. If a null mutex is provided, it is
* treated as if it is "locked". I.e. operator bool() will return true.
*/
ScopedMutexTryLocker(const IMutex * const pMutex);
/**
* @brief Constructor. The constructor attempts to lock the mutex.
*
* @param pMutex smart pointer to the mutex to be locked. It can be null. If a null mutex is provided, it is
* treated as if it is "locked". I.e. operator bool() will return true.
*/
template<typename T>
ScopedMutexTryLocker(T &pMutex);
//! Destructor releases the mutex lock, if the lock was acquired.
~ScopedMutexTryLocker();
/**
* @brief Acquire the mutex.
*
* If the constructor acquired the mutex, this is a no-op. Otherwise, it will block until the mutex is unlocked
* by another thread.
*/
void Acquire();
//! Is the mutex locked?
ACTIV_BOOST_EXPLICIT_OPERATOR_BOOL()
//! Is the mutex not locked?
bool operator!() const;
private:
const IMutex * const m_pMutex; ///< The mutex object.
bool m_isLocked;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline ScopedMutexTryLocker::ScopedMutexTryLocker(IMutex * const pMutex) :
m_pMutex(pMutex),
m_isLocked((0 != m_pMutex) ? (STATUS_CODE_SUCCESS == m_pMutex->Try()) : true)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline ScopedMutexTryLocker::ScopedMutexTryLocker(const IMutex * const pMutex) :
m_pMutex(pMutex),
m_isLocked((0 != m_pMutex) ? (STATUS_CODE_SUCCESS == m_pMutex->Try()) : true)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline ScopedMutexTryLocker::ScopedMutexTryLocker(T &pMutex) :
m_pMutex(pMutex.get()),
m_isLocked((0 != m_pMutex) ? (STATUS_CODE_SUCCESS == m_pMutex->Try()) : true)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline ScopedMutexTryLocker::~ScopedMutexTryLocker()
{
if ((0 != m_pMutex) && m_isLocked)
(void) m_pMutex->Release();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void ScopedMutexTryLocker::Acquire()
{
if ((0 != m_pMutex) && !m_isLocked)
{
(void) m_pMutex->Acquire();
m_isLocked = true;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool ScopedMutexTryLocker::operator!() const
{
return !m_isLocked;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Deferred acquire mutex helper class.
*
* This version does not attempt to acquire the mutex in the constructor, it is left
* to a later method call.
*/
class DeferredScopedMutexLocker : private Boost::noncopyable
{
public:
/**
* @brief Constructor.
*
* @param pMutex pointer to the mutex to be locked. If a null mutex is provided, Try() will always succeed.
*/
DeferredScopedMutexLocker(IMutex * const pMutex);
/**
* @brief Constructor.
*
* @param pMutex pointer to the mutex to be locked. If a null mutex is provided, Try() will always succeed.
*/
DeferredScopedMutexLocker(const IMutex * const pMutex);
/**
* @brief Constructor.
*
* @param pMutex smart pointer to the mutex to be locked. If a null mutex is provided, Try() will always succeed.
*/
template<typename T>
DeferredScopedMutexLocker(T &pMutex);
//! Destructor releases the mutex lock, if the lock was acquired.
~DeferredScopedMutexLocker();
//! Acquire the mutex.
void Acquire();
/**
* @brief Attempt to acquire the mutex.
*
* @return True if the mutex was already locked by this thread, or was successfully locked by this call.
*/
bool Try();
//! Is the mutex locked?
ACTIV_BOOST_EXPLICIT_OPERATOR_BOOL()
//! Is the mutex not locked?
bool operator!() const;
private:
const IMutex * const m_pMutex; ///< The mutex object.
bool m_isLocked;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline DeferredScopedMutexLocker::DeferredScopedMutexLocker(IMutex * const pMutex) :
m_pMutex(pMutex),
m_isLocked(false)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline DeferredScopedMutexLocker::DeferredScopedMutexLocker(const IMutex * const pMutex) :
m_pMutex(pMutex),
m_isLocked(false)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline DeferredScopedMutexLocker::DeferredScopedMutexLocker(T &pMutex) :
m_pMutex(pMutex.get()),
m_isLocked(false)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline DeferredScopedMutexLocker::~DeferredScopedMutexLocker()
{
if ((0 != m_pMutex) && m_isLocked)
(void) m_pMutex->Release();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void DeferredScopedMutexLocker::Acquire()
{
if (!m_isLocked)
{
if (0 != m_pMutex)
(void) m_pMutex->Acquire();
m_isLocked = true;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool DeferredScopedMutexLocker::Try()
{
if (!m_isLocked)
{
if (0 != m_pMutex)
{
if (STATUS_CODE_SUCCESS == m_pMutex->Try())
m_isLocked = true;
}
else
{
m_isLocked = true;
}
}
return m_isLocked;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool DeferredScopedMutexLocker::operator!() const
{
return !m_isLocked;
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_MUTEX_HELPER_H)
Loaded 100 of 10967 files, more files were not shown because too many files have changed in this diff. Show more