SharkEngine Documentation, generated with mkdoc

Last update 27/Jul/2008 by Mark Seuffert

1. Introduction

This is a documentation about the SharkeEngine library. SharkEngine is an object oriented platform abstraction layer, it allows to use the same code on different platforms. Shared libraries are available for C++ on Linux, BSD and Windows.
Feature highlights:
  • network, file, directory and thread support
  • parsing for files, memory and strings
  • completely asynchronous delight for single threaded applications
  • not binary dependent on a specific version of STL or Boost
SharkeEngine is included in the Pichat SDK, available at http://www.pichat.net

2.1. CAsyncNetwork

Description: Nonblocking network access, socket with DNS and timer
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class provides asynchronous network access, which means that any network operation is nonblocking and processed within one thread context. It comes with automatic DNS resolution, timer events and supports TCP/UDP/RAW sockets. Derive your own class from this and overload the virtual methods you need. Generally, if you overload a virtual method call the base class method first. Important, when you overload one of the methods OnClosing() or OnClose() you have to call Close() in your derived destructor, this is mandatory!
Limitations on Windows platform: A graceful close with EOF from other peers is never reported from Winsock. Instead connection is closed as soon as all pending data has been received, both when remote peer issues Disconnect() or Close().
These virtual methods exist:
  • OnListen() informs when a listening socket has been established or failed
  • OnAccept() informs when incoming socket is waiting at listening socket
  • OnConnecting() informs when socket is connecting
  • OnConnect() informs when socket has been connected or attempt failed
  • OnReceive() informs when (more) data can be received
  • OnSend() informs when (more) data can be send
  • OnResolveDns() informs when DNS lookup has been resolved or failed
  • OnTimer() called periodically if requested (once per second)
  • OnNotify() called once for each notification requested
  • OnClosing() informs when socket is closing
  • OnClose() informs when socket has been closed
Construction
Syntax:CAsyncNetwork();
Constants
network status:
NETWORK_CLOSEDsocket closed
NETWORK_CLOSED_RECONNECTsocket closed, waiting for reconnect (unused)
NETWORK_UNCONNECTEDsocket unconnected
NETWORK_CLOSINGsocket closing/disconnecting
NETWORK_CONNECTING_STARTsocket starting new connection (unused)
NETWORK_CONNECTING_LOOKUPsocket resolving hostname
NETWORK_CONNECTINGsocket connecting
NETWORK_CONNECTEDsocket connected to remote peer
NETWORK_CONNECTED_SESSION_STARTsocket connected, protocol specific (unused)
NETWORK_CONNECTED_SESSION_OKsocket connected, protocol specific (unused)
NETWORK_CONNECTED_SESSIONsocket connected, protocol specific (unused)
NETWORK_LISTENINGserver listening
NETWORK_TYPE_CUSTOMcustom types, free for use
 
DNS status:
DNS_NONEnothing done
DNS_RESOLVINGresolving in progress, try again
DNS_RESOLVED_HOSTNAMEhostname resolved, IP available
DNS_RESOLVED_ADDRESSaddress resolved, hostname available
DNS_HOSTNAME_NOT_FOUNDhostname can't be resolved, non-existent
DNS_ADDRESS_NOT_FOUNDaddress can't be resolved, non-existent
DNS_SYSFAILUREunderlying system failure, DNS unavailable
DNS_NO_BUFFERSnot enough lookup entries
DNS_POISONED_BUFFERnot enough lookup entries to hold results
DNS_MAX_PENDINGmaximum number of pending notifies reached
DNS_HOSTNAME_TIMEOUThostname can't be resolved, timeout
DNS_ADDRESS_TIMEOUTaddress can't be resolved, timeout
 
DNS_FLUSH_ADDRESS = 0, DNS_FLUSH_HOSTNAME = 1
EVENT_MASK_DEFAULT = FD_READ | FD_WRITE | FD_ACCEPT | FD_CONNECT | FD_CLOSE
LISTEN_BACKLOG_DEFAULT = 5
Open - Open socket
Syntax:bool Open(int nSocketPort = 0, int nSocketType = SOCK_STREAM, int nEventMask = EVENT_MASK_DEFAULT, const char* szSocketAddress = NULL);
Close - Close socket, force immediate close
Syntax:void Close(int nErrorCode = ERROR_ECLOSE);
CloseDown - Close down server socket, request friendly server close
Syntax:void CloseDown();
Disconnect - Disconnect socket, initiate graceful close of client connection
Notes: Remote peer will receive an EOF when all data has been transferred.
Syntax:void Disconnect();
Listen - Listen on incoming connections
Syntax:void Listen(int nConnectionBacklog = LISTEN_BACKLOG_DEFAULT);
Connect - Connect socket to remote server
Syntax:void Connect(const char* szHostAddress, int nHostPort);
void Connect(const SOCKADDR* pSockAddr, int nSockAddrLen);
Accept - Accept incoming connection
Notes: This method accepts an incoming connection and assigns it to a new socket, the new socket will inherit the event mask from the server socket. Do not call Open() on the new socket.
Syntax:bool Accept(CAsyncNetwork& socketNew);
Receive - Receive data
Notes: Returns the number of bytes received or SOCKET_ERROR.
Syntax:int Receive(void* pBuffer, int nBufferLen, bool bCheckEOF = true);
Send - Send data
Notes: Returns the number of bytes send or SOCKET_ERROR.
Syntax:int Send(const void* pBuffer, int nBufferLen);
ReceiveFrom - Receive data, for sockets of type SOCK_DGRAM
Notes: Returns the number of bytes received or SOCKET_ERROR.
Syntax:int ReceiveFrom(void* pBuffer, int nBufferLen, SOCKADDR* pSockAddr, int nSockAddrLen);
SendTo - Send data, for sockets of type SOCK_DGRAM
Notes: Returns the number of bytes send or SOCKET_ERROR.
Syntax:int SendTo(const void* pBuffer, int nBufferLen, const char* szHostAddress, int nHostPort);
int SendTo(const void* pBuffer, int nBufferLen, const SOCKADDR* pSockAddr, int nSockAddrLen);
AsyncSelect - Request socket events
Syntax:void AsyncSelect(int nEventMask = EVENT_MASK_DEFAULT);
AsyncTimer - Request timer events
Syntax:void AsyncTimer(bool bRequest = true);
AsyncNotify - Request an user event
Notes: This method is thread safe, you can call it from any thread.
Syntax:void AsyncNotify(int nStatusCode);
Attach - Attach a socket handle
Notes: This method can be used to manually attach a socket handle. Do not call Open() on the attached socket.
Syntax:bool Attach(HSOCKET hSocket, int nEventMask = EVENT_MASK_DEFAULT, int nStatus = NETWORK_CONNECTED);
Detach - Detach a socket handle
Notes: When detaching a socket handle you need to set the correct network status manually. A detached socket will NOT call OnClose() or OnClosing() any more.
Syntax:HSOCKET Detach();
GetStatus - Return network status
Syntax:int GetStatus() const;
bool GetStatus(int nStatus) const;
GetStartError - Return network start error during open/listen/connect
Syntax:int GetStartError() const;
GetSocketPort - Return port number of local socket
Notes: Returns the listening port of a server socket or the local port.
Syntax:int GetSocketPort() const;
GetRemoteAddr - Return address of remote peer
Notes: Returns the IP address of the remote peer in network order.
Syntax:unsigned long GetRemoteAddr() const;
GetPeerName - Return address of remote peer
Syntax:bool GetPeerName(CString8& sPeerAddress, int& nPeerPort) const;
bool GetPeerName(SOCKADDR* pSockAddr, int* pnSockAddrLen) const;
SetOpt - Set socket options
Syntax:bool SetOpt(int nOptionName, const void* pOptionValue, int nOptionLen);
GetOpt - Get socket options
Syntax:bool GetOpt(int nOptionName, void* pOptionValue, int* pnOptionLen) const;
IsOpen - Check if socket is open
Notes: This doesn't mean the socket is also listening or connected, use GetStatus() to check the exact network status.
Syntax:bool IsOpen() const;
ResolveDns - Resolve hostname or IP address, optionally with notification
Notes: The second version resolves hostnames only, third version resolves IP addresses only.
Syntax:bool ResolveDns(const char* szStringToResolve, CString8& sResult, bool bNotify = false);
bool ResolveDns(const char* szHostname, unsigned long* plAddr, bool bNotify = false);
bool ResolveDns(unsigned long lAddr, char* pHostnameBuffer, int nHostnameBufferLen, bool bNotify = false);
FlushDns - Flush old entries from DNS lookup buffer
Syntax:void FlushDns();
void FlushDns(int nAgeSeconds, int nFlushMode);
FlushEntryDns - Flush specific entry from DNS lookup buffer
Notes: The second version flushes hostnames only, third version flushed IP addresses only.
Syntax:void FlushEntryDns(const char* szStringToFlush, bool bAutoDetect);
void FlushEntryDns(const char* szHostname);
void FlushEntryDns(unsigned long lAddr);
GetStatusDns - Return DNS lookup status
Syntax:int GetStatusDns() const;
GetLastResolvedDns - Get last resolved hostname and IP address
Notes: These methods return result of current DNS notification, therefore they should be called in OnResolveDns() handler only.
Syntax:void GetLastResolvedDns(CString8& sHostname, CString8& sAddr) const;
void GetLastResolvedDns(CString8& sHostname, unsigned long& plAddr) const;
IsLastResolvedDnsBufferedEntry - Check if last result was a buffered entry
Notes: This method checks result of current DNS notification, therefore it should be called in OnResolveDns() handler only.
Syntax:bool IsLastResolvedDnsBufferedEntry() const;
SetPendingDnsNotifiesMax - Set maximum number of pending DNS notifies per socket
Syntax:void SetPendingDnsNotifiesMax(int nPendingDnsNotifiesMax = 1);
GetPendingDnsNotifiesMax - Return maximum number of pending DNS notifies
Syntax:int GetPendingDnsNotifiesMax() const;
SetOptDns - Set DNS options
Notes: DNS settings can NOT be changed while lookups are running! On success the lookup buffer will be flushed.
Syntax:bool SetOptDns(int nLookupEntriesMax = 64, int nLookupThreadsMax = 4, int nLookupTimeout = 60);
GetOptDns - Get DNS options
Syntax:void GetOptDns(int& nLookupEntriesMax, int& nLookupThreadsMax, int& nLookupTimeout) const;
GetLookupThreadsRunningDns - Return number of running DNS worker threads
Syntax:int GetLookupThreadsRunningDns() const;
GetLastError - Return last network error status
Syntax:static int GetLastError();
SetLastError - Set last network error status
Syntax:static void SetLastError(int nErrorCode);
IsBenignError - Check if error status is benign
Notes: Returns true for error codes that do not signal an error case, e.g. ERROR_SUCCESS, ERROR_EOF, ERROR_EDISCONNECT, ERROR_ECLOSE.
Syntax:static bool IsBenignError(int nErrorCode);

2.2. CAsyncNetworkClient

Description: Nonblocking network access, client socket with proxy support
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class provides buffered input for TCP sockets and connection via a HTTP proxy. Derive your own class from this and overload the virtual methods you need. To use line buffered input call ReceiveLine() in your OnReceive() method, alternatively to use binary buffered input call ReceiveBinary() in your OnReceive() method. Generally, if you overload a virtual method call the base class method first. Important, when you overload one of the methods OnClosing() or OnClose() you have to call Close() in your derived destructor, this is mandatory!
These virtual methods exist (also see base class CAsyncNetwork):
  • OnReceiveLine() informs when text line was received
  • OnReceiveBinary() informs when chunk of binary data was received
Construction
Syntax:CAsyncNetworkClient();
Constants
proxy status:
PROXY_UNCONNECTEDnot connected to proxy
PROXY_CONNECTING_LOOKUPresolving hostname
PROXY_CONNECTINGconnecting to proxy
PROXY_REQUESTINGproxy connected and requesting connection
PROXY_ESTABLISHEDproxy has established connection
 
EVENT_MASK_DEFAULT = FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE
NETWORK_LINE_BUFFER_SIZE = ENGINE_MAXLINE
NETWORK_BINARY_BUFFER_SIZE = ENGINE_BINARY_BUFFER_SIZE
Open - Open socket
Syntax:bool Open(int nSocketPort = 0, int nSocketType = SOCK_STREAM, int nEventMask = EVENT_MASK_DEFAULT, int nLineBufferSize = NETWORK_LINE_BUFFER_SIZE, int nBinaryBufferSize = NETWORK_BINARY_BUFFER_SIZE);
Connect - Connect socket to remote server, possibly via proxy
Syntax:void Connect(const char* szHostAddress, int nHostPort);
void Connect(const SOCKADDR* pSockAddr, int nSockAddrLen);
ReceiveLine - Collect data and split into text lines
Notes: Returns the number of bytes read, in case of an error this method returns 0 and never SOCKET_ERROR. This method splits newline terminated text lines (CRLF and LF).
Syntax:int ReceiveLine(int nBytesMax = INT_MAX);
ReceiveBinary - Collect data into binary buffer
Notes: Returns the number of bytes read, in case of an error this method returns 0 and never SOCKET_ERROR.
Syntax:int ReceiveBinary(int nBytesMax = INT_MAX);
PeekLineBuffer - Peek into collected data in line buffer
Syntax:const char* PeekLineBuffer(int nBytesMin) const;
TransferLineBuffer - Copy remaining data from line buffer to binary buffer
Syntax:void TransferLineBuffer();
SetProxy - Set proxy settings
Notes: Where available a connection is optionally done via a HTTP proxy.
Syntax:void SetProxy(const char* szProxyAddress, int nProxyPort, bool bUseProxy = true);
void SetProxyAdvanced(const char* szProxyBypassList, bool bProxyResolveDns);
GetProxy - Get proxy settings
Syntax:void GetProxy(CString8& sProxyAddress, int& nProxyPort, bool& bUseProxy) const;
void GetProxyAddress(CString8& sProxyAddress) const;
void GetProxyAdvanced(CString8& sProxyBypassList, bool& bProxyResolveDns) const;
FlushProxyDns - Flush cached proxy address
Syntax:void FlushProxyDns();
ResetProxy - Reset proxy settings
Syntax:void ResetProxy();
GetStatusProxy - Return proxy status
Syntax:int GetStatusProxy() const;
IsProxy - Check if proxy can be used
Syntax:bool IsProxy() const;
IsProxyActive - Check if proxy is used in current session
Syntax:bool IsProxyActive() const;
IsProxyConnect - Check if proxy has been connected
Notes: When connecting via proxy the OnConnect() handler is being called twice, once for the proxy and once for the remote peer. This method checks which one it is, it should be called in OnConnect() handler only.
Syntax:bool IsProxyConnect() const;
IsProxyConnectError - Check if proxy error has happened
Notes: This method should be called in OnConnect() handler only.
Syntax:bool IsProxyConnectError() const;
GetProxyConnectErrorFormated - Return human readable proxy error description
Notes: This method should be called in OnConnect() handler only.
Syntax:CString8 GetProxyConnectErrorFormated() const;

2.3. CAsyncResolverSimple

Description: Nonblocking DNS resolver
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: First, this is not a cache. The only purpose of this class is to perform nonblocking DNS lookups and to send events... nothing else. If you need a cache for hostnames and IP addresses, better do this LAN-wide with a local nscd/named. Generally work IP based when ever possible and keep lookup buffer size small. When the buffer becomes poisoned, consider storing resolved hostnames with socket objects and reuse them instead of resolving each time.
This class is quite low-level, for an alternative see class CAsyncNetwork.
Construction
Syntax:CAsyncResolverSimple(HHANDLER hNotifyHandler = 0, unsigned int nNotifyEvent = 0);
Constants
DNS status:
STATUS_NONEnothing done
STATUS_RESOLVINGresolving in progress, try again
STATUS_RESOLVED_HOSTNAMEhostname resolved, IP available
STATUS_RESOLVED_ADDRESSaddress resolved, hostname available
STATUS_HOSTNAME_NOT_FOUNDhostname can't be resolved, non-existent
STATUS_ADDRESS_NOT_FOUNDaddress can't be resolved, non-existent
STATUS_SYSFAILUREunderlying system failure, resolver unavailable
STATUS_NO_BUFFERSnot enough lookup entries
STATUS_POISONED_BUFFERnot enough lookup entries to hold results
STATUS_TYPE_CUSTOMcustom types, free for use
 
RESOLVE_REVERSE = 0, RESOLVE_NORMAL = 1
FLUSH_ADDRESS = 0, FLUSH_HOSTNAME = 1
BUFFERED_ENTRY_FLAG = 8, NORMAL_ENTRY_MASK = 1, INDEX_INADDR_NONE = 0xFFFF
HOSTNAME_LENGTH_MAX = 100
Create - Create resolver
Syntax:bool Create();
Destroy - Destroy resolver
Syntax:void Destroy();
Resolve - Resolve hostname into IP address
Notes: If not enough lookup entries are available, this method returns error STATUS_NO_BUFFERS and no notify event will be posted.
Syntax:int Resolve(const char* szHostname, unsigned long* plAddr, bool bNotify = false);
Reverse - Reverse resolve IP address into hostname
Notes: If not enough lookup entries are available, this method returns error STATUS_NO_BUFFERS and no notify event will be posted.
Syntax:int Reverse(unsigned long lAddr, char* pHostnameBuffer, int nHostnameBufferLen, bool bNotify = false);
Flush - Flush old entries from lookup buffer
Syntax:void Flush();
void Flush(int nAgeSeconds, int nFlushMode);
FlushEntry - Flush specific entry from lookup buffer
Notes: The second version flushes hostnames only, third version flushed IP addresses only.
Syntax:void FlushEntry(const char* szHostname, unsigned long lAddr, int nFlushMode);
void FlushEntry(const char* szHostname);
void FlushEntry(unsigned long lAddr);
SetOpt - Set number of lookup entries and worker threads
Notes: Settings can NOT be changed while lookups are running! It's recommended to change settings before starting any lookup. On success, lookup buffer will be flushed and threads (re)started.
Syntax:bool SetOpt(int nLookupEntriesMax = 64, int nLookupThreadsMax = 4);
GetLookupEntries - Return number of lookup entries
Syntax:int GetLookupEntries() const;
GetLookupThreadsMax - Return maximum number of worker threads
Syntax:int GetLookupThreadsMax() const;
GetLookupThreadsRunning - Return number of running worker threads
Syntax:int GetLookupThreadsRunning();
GetResolvedEntry - Get a resolved entry from lookup buffer
Syntax:int GetResolvedEntry(int nIndex, int nResolveMode, char* pHostnameBuffer, int nHostnameBufferLen, unsigned long* plAddr) const;
IsCreated - Check if resolver is created
Syntax:bool IsCreated() const;
AsyncEvent - Request event notification
Syntax:bool AsyncEvent(HHANDLER hNotifyHandler, unsigned int nNotifyEvent);
InitResolvers - Initialise and quit resolver system
Syntax:static void InitResolvers();
static void QuitResolvers();
IsHostname - Check if string is hostname or IP address
Syntax:static bool IsHostname(const char* szString);

2.4. CAsyncSocketSimple

Description: Nonblocking socket
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class provides simple asynchronous socket events. To prevent flooding an event queue with too many events a socket event will be send only once. The corresponding socket methods refresh further notification of that socket event. Calling Receive() or ReceiveFrom() reenables FD_READ notification, Send() or SendTo() reenables FD_WRITE notification, Accept() reenables FD_ACCEPT notification.
Limitations on Windows platform: A graceful close with EOF from other peers is never reported from Winsock. Instead connection is closed as soon as all pending data has been received, both when remote peer issues Disconnect() or Close().
This class is quite low-level, for an alternative see class CAsyncNetwork.
The following socket events exist:
  • FD_READ informs when (more) data can be received or EOF was signaled
  • FD_WRITE informs when (more) data can be send
  • FD_ACCEPT informs when incoming socket is waiting at listening socket
  • FD_CONNECT informs when socket has been connected or attempt failed
  • FD_CLOSE informs when socket has been closed
Construction
Syntax:CAsyncSocketSimple(HHANDLER hNotifyHandler = 0, unsigned int nNotifyEvent = 0);
Constants
shutdown modes:
SHUTDOWN_RECEIVEshut down receiving side
SHUTDOWN_SENDshut down sending side
SHUTDOWN_BOTHshut down both receiving and sending
Open - Open socket
Syntax:bool Open(int nSocketPort, int nSocketType, int nEventMask, const char* szSocketAddress);
Close - Close socket, force immediate close
Syntax:void Close();
Listen - Listen on incoming connections
Notes: Returns true if socket is listening.
Syntax:bool Listen(int nConnectionBacklog);
Connect - Connect socket to remote server
Notes: Returns true if socket is connecting.
Syntax:bool Connect(const SOCKADDR* pSockAddr, int nSockAddrLen);
Accept - Accept incoming connection
Syntax:bool Accept(HSOCKET& hSocketNew);
Receive - Receive data
Notes: Returns the number of bytes received or SOCKET_ERROR.
Syntax:int Receive(void* pBuffer, int nBufferLen, int nFlags = 0);
Send - Send data
Notes: Returns the number of bytes send or SOCKET_ERROR.
Syntax:int Send(const void* pBuffer, int nBufferLen, int nFlags = 0);
ReceiveFrom - Receive data, for sockets of type SOCK_DGRAM
Notes: Returns the number of bytes received or SOCKET_ERROR.
Syntax:int ReceiveFrom(void* pBuffer, int nBufferLen, SOCKADDR* pSockAddr, int* pnSockAddrLen, int nFlags = 0);
SendTo - Send data, for sockets of type SOCK_DGRAM
Notes: Returns the number of bytes send or SOCKET_ERROR.
Syntax:int SendTo(const void* pBuffer, int nBufferLen, const SOCKADDR* pSockAddr, int nSockAddrLen, int nFlags = 0);
ShutDown - Shut down socket
Syntax:bool ShutDown(int nShutdownMode = SHUTDOWN_SEND);
IsOpen - Check if socket is open
Syntax:bool IsOpen() const;
AsyncEvent - Request event notification
Syntax:bool AsyncEvent(HHANDLER hNotifyHandler, unsigned int nNotifyEvent);
AsyncSelect - Request socket events
Syntax:bool AsyncSelect(int nEventMask);
Attach - Attach a socket handle
Syntax:bool Attach(HSOCKET hSocket, int nEventMask);
void AttachAccepted(HSOCKET hSocket, int nEventMask);
Detach - Detach a socket handle
Syntax:HSOCKET Detach();
GetHandle - Return socket handle
Syntax:HSOCKET GetHandle() const;
GetEventMask - Return event notification mask
Syntax:int GetEventMask() const;
GetSockName - Return address of local socket
Syntax:bool GetSockName(SOCKADDR* pSockAddr, int* pnSockAddrLen) const;
GetPeerName - Return address of connected peer
Syntax:bool GetPeerName(SOCKADDR* pSockAddr, int* pnSockAddrLen) const;
SetOpt - Set socket options
Syntax:bool SetOpt(int nOptionName, const void* pOptionValue, int nOptionLen);
GetOpt - Get socket options
Syntax:bool GetOpt(int nOptionName, void* pOptionValue, int* pnOptionLen) const;
InitSockets - Initialise and quit socket system
Syntax:static void InitSockets();
static void QuitSockets();
GetLastError - Return last socket error status
Syntax:static int GetLastError();
SetLastError - Set last socket error status
Syntax:static void SetLastError(int nErrorCode);
InetMask - Return network mask in network byte order
Syntax:static unsigned long InetMask(int nMaskBits);

2.5. CAsyncTimer

Description: Nonblocking timer, called once per second
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class provides asynchronous timer events. Derive your own class from this and overload the following virtual method:
  • OnTimer() called periodically if requested (once per second)
Construction
Syntax:CAsyncTimer();
AsyncTimer - Request timer events
Syntax:void AsyncTimer(bool bRequest = true);
IsValid - Check if timer is ready, construction may fail on some platforms
Syntax:bool IsValid() const;

2.6. CAsyncTimerSimple

Description: Nonblocking timer
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class provides simple asynchronous timer events. To prevent flooding an event queue with too many events a recurring timer has to be refreshed before more events will be send.
This class is quite low-level, for an alternative see class CAsyncTimer.
Construction
Syntax:CAsyncTimerSimple(HHANDLER hNotifyHandler = 0, unsigned int nNotifyEvent = 0);
Create - Create timer
Syntax:bool Create(DWORD dwMilliseconds, bool bRecurring = false);
Destroy - Destroy timer
Syntax:void Destroy();
IsCreated - Check if timer is created
Syntax:bool IsCreated() const;
AsyncEvent - Request event notification
Syntax:bool AsyncEvent(HHANDLER hNotifyHandler, unsigned int nNotifyEvent);
InitTimers - Initialise and quit timer system
Syntax:static void InitTimers();
static void QuitTimers();
RefreshTimer - Refresh a recurring timer
Syntax:static bool RefreshTimer(int nIndex, bool bRefresh = true);

2.7. CDataBuffer

Description: Buffer class, allows direct manipulation
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class provides multi purpose buffer handling. It is a replacement for std::vector<BYTE> (STL) that offers dynamic memory allocation and direct buffer manipulation.
Construction
Syntax:CDataBuffer();
CDataBuffer(const CDataBuffer& buffer);
CDataBuffer(const MEMBLOCK memory);
Constants
NOT_FOUND = -1data not found
MAX_POS = -1largest position in data buffer
Clear - Clear buffer and release memory
Syntax:void Clear();
Reserve - Reserve space in buffer
Notes: Call this method to reserve (more) space in a buffer, you have to call it at least once before accessing the buffer memory. The internally allocated memory may be bigger than requested and will be reallocated if necessary.
Syntax:void Reserve(int nLen);
Find - Find data
Notes: Returns position of given data in buffer or NOT_FOUND if not found.
Syntax:int Find(const void* pBuffer, int nBufferLen, int nPos = 0) const;
int Find(BYTE byData, int nPos = 0) const;
FindReverse - Find data reverse
Notes: Returns position of given data in buffer or NOT_FOUND if not found.
Syntax:int FindReverse(const void* pBuffer, int nBufferLen, int nPos = MAX_POS) const;
int FindReverse(BYTE byData, int nPos = MAX_POS) const;
GetBuffer - Return pointer to buffer, allows direct buffer manipulation
Syntax:BYTE* GetBuffer();
GetBufferConst - Return pointer to non-modifiable buffer
Syntax:const BYTE* GetBufferConst() const;
SetPos - Set data position in buffer
Notes: Call this method if you want to store an optional data position.
Syntax:void SetPos(int nPos);
ChangePos - Change data position in buffer
Notes: Call this method if you want to change an optional data position.
Syntax:void ChangePos(int nPosDiff);
GetPos - Return data position in buffer
Syntax:int GetPos() const;
SetSize - Set size of data in buffer
Syntax:void SetSize(int nSize);
ChangeSize - Change size of data in buffer
Syntax:void ChangeSize(int nSizeDiff);
GetSize - Return size of data in buffer, NOT internally allocated memory
Syntax:int GetSize() const;
GetCapacity - Return size of internally allocated memory
Syntax:int GetCapacity() const;
IsEmpty - Check if buffer is empty
Syntax:bool IsEmpty() const;
IsValid - Check if buffer is available
Syntax:bool IsValid() const;
SetAllocator - Set custom memory allocator
Notes: This allows to use an specialised allocator for this class, e.g. to exchange objects over library boundaries. Also see IAllocatorInterface.
Syntax:static void SetAllocator(IAllocatorInterface* pAllocator);

2.8. CDataCompression

Description: Data compression and decompression
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class provides memory compression and decompression. Arbitrary buffer sizes can be used for input and output. If buffers are big enough compression/decompression can happen at once. In any other case you need to loop Compress() or Decompress() method until all input data was processed and all output data was created.
Construction
Syntax:CDataCompression();
Constants
compression modes:
DATA_ZLIB_COMPRESScompress data, 'zlib' format
DATA_ZLIB_DECOMPRESSdecompress data
DATA_GZIP_COMPRESScompress data, 'gzip' format
DATA_GZIP_DECOMPRESSdecompress data
 
compression levels:
LEVEL_MINfastest compression
LEVEL_DEFAULTdefault compression
LEVEL_MAXbest compression
 
flush modes:
FLUSH_NONEno flush required
FLUSH_SYNCoutput is flushed
FLUSH_FULLoutput is flushed and compression state is reset
FLUSH_FINISHoutput is flushed and compression finishes
 
COMPRESSION_BUFFER_SIZE = ENGINE_COMPRESSION_BUFFER_SIZE
Open - Open compression/decompression
Syntax:bool Open(int nCompressionMode, int nCompressionLevel = LEVEL_DEFAULT, int nOutputBufferSize = COMPRESSION_BUFFER_SIZE);
Close - Close compression/decompression
Syntax:void Close();
Compress - Compress data
Notes: Call repeatedly with more data until all output was produced from given input. Errors do not happen, return value can be ignored.
Syntax:bool Compress(int nFlushMode = FLUSH_NONE);
Decompress - Decompress data
Notes: Call repeatedly with more data until all output was produced from given input. Errors may happen, calling application needs to catch them.
Syntax:bool Decompress(int nFlushMode = FLUSH_NONE);
SetInput - Give more input to compression/decompression
Syntax:void SetInput(const void* pInput, int nInputLen);
GetOutput - Return pointer to data in output buffer
Syntax:BYTE* GetOutput();
GetOutputSize - Return size of available data in output buffer
Syntax:int GetOutputSize() const;
GetBufferSize - Return size of output buffer
Syntax:int GetBufferSize() const;
ResetOutput - Reset output buffer, make space for more output
Notes: The second version reserves additional space for meta data at start and end of output buffer, buffer will be overwritten after reserved header. The method GetOutputSize() will return length of produced data plus length of header and trailer.
Syntax:void ResetOutput();
void ResetOutput(int nOutputReservedHeader, int nOutputReservedTrailer);
GetInputTotal - Get total number of processed input bytes
Syntax:unsigned int GetInputTotal() const;
GetOutputTotal - Get total number of created output bytes
Syntax:unsigned int GetOutputTotal() const;
IsOpen - Check if compression/decompression is open
Syntax:bool IsOpen() const;
IsError - Check if error has happened while decompressing
Syntax:bool IsError() const;
IsInputProcessed - Check if input is processed
Syntax:bool IsInputProcessed() const;
IsOutputAvailable - Check if output is available
Syntax:bool IsOutputAvailable() const;
IsOutputFull - Check if output buffer is full
Syntax:bool IsOutputFull() const;
IsOutputFinished - Check if all data is processed and output is finished
Syntax:bool IsOutputFinished() const;
Crc32 - Calculate CRC32 for given buffer
Syntax:static DWORD Crc32(const void* pBuffer, int nBufferLen);
GetLibraryVersion - Return compression library version
Syntax:static const char* GetLibraryVersion();

2.9. CDataEncryption

Description: Data encryption and hash
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This is pretty much a place holder for what comes later.
Construction
Syntax:CDataEncryption();
Constants
SHA256_HASH_SIZE = 32
BeginSha256 - Calculate SHA256 hash for given buffer, can be looped if necesary
Notes: The output buffer needs to be at least SHA256_HASH_SIZE bytes long.
Syntax:void BeginSha256();
void LoopSha256(const void* pBuffer, int nBufferLen);
void EndSha256(void* pOutput, int nOutputLen);
Sha256Hash - Calculate SHA256 hash for given buffer
Notes: The output buffer needs to be at least SHA256_HASH_SIZE bytes long.
Syntax:static void Sha256Hash(const void* pBuffer, int nBufferLen, void* pOutput, int nOutputLen);

2.10. CEventHandler

Description: Event handler, thread safe event distribution
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class deals with inter thread communication for asynchronous operations. Events can be posted between threads, the event itself will be processed in the thread context of the receiving event handler and all events will be handled in the order they are received. A thread can either place an event into a queue by using PostEvent() or wait blocking until the event was processed by using SendEvent(). Each thread has an own event queue and can have multiple event handlers. One event handler of a thread has to run the event pump to ensure that queued events will be processed. However, threads only posting or sending events to others (not receiving themselves) don't need an event pump at all.
Avoid SendEvent() if you do not absolutely have to use it. Using it in a thread with own event handler has a dead lock possibility because two threads could end up waiting for each other. Also SendEvent() can never send an event to the same thread, because it would block the event pump. The method PostEvent() on the other side is always safe and hazzle free.
Limitations on Windows platform: The method SendEvent() violates event order and is processed immediately, plausibility checking is weak and allows misuse.
Construction
Syntax:CEventHandler();
Constants
event limitations:
EVENT_USER_MINlowest possible event number
EVENT_LEFTPARAM_LIMITbiggest left parameter
EVENT_RIGHTPARAM_LIMITbiggest right parameter
Create - Create event handler
Syntax:bool Create(const char* szHandlerName = NULL, bool bEventPump = true);
Destroy - Destroy event handler
Syntax:void Destroy();
Post - Post event
Syntax:bool Post(unsigned int nEvent, DWORD dwLeftParam, DWORD dwRightParam);
static bool PostEvent(HHANDLER hHandler, unsigned int nEvent, DWORD dwLeftParam, DWORD dwRightParam);
Send - Send event
Syntax:bool Send(unsigned int nEvent, DWORD dwLeftParam, DWORD dwRightParam);
static bool SendEvent(HHANDLER hHandler, unsigned int nEvent, DWORD dwLeftParam, DWORD dwRightParam);
PumpEvent - Pump event
Notes: The event pump shall be called periodically to ensure that all events get processed. This method blocks when no events are waiting in the queue, it returns false when the event handler has stopped.
Syntax:bool PumpEvent();
SetEventSlot - Add or remove an event slot
Notes: Events can trigger callbacks, the event handler calls registered callback functions when events are processed. There can be one callback function per event only, NULL removes a callback.
Syntax:bool SetEventSlot(unsigned int nEvent, EventSlotFunction pSlotFunc);
StopEventHandler - Stop event handler
Syntax:void StopEventHandler();
IsCreated - Check if event handler is created
Syntax:bool IsCreated() const;
IsPump - Check if event handler has an event pump
Syntax:bool IsPump() const;
GetHandle - Return handle
Syntax:HHANDLER GetHandle() const;
IsEventHandler - Check if handle is an event handler
Syntax:static bool IsEventHandler(HHANDLER hHandler);

2.11. CFileDirectory

Description: File directory access
Header file: SharkEngine_Classes.h, namespace SharkEngine
Construction
Syntax:CFileDirectory();
Constants
directory entry types:
DIRECTORY_TYPE_ANYany entry, sub directories and files
DIRECTORY_TYPE_SUBDIRECTORYlimited to sub directory entries
DIRECTORY_TYPE_FILElimited to file entries
Open - Open directory
Syntax:bool Open(const char* szPath, int nEntryType = DIRECTORY_TYPE_ANY);
Close - Close directory
Syntax:void Close();
GetNextEntry - Return next directory entry
Syntax:bool GetNextEntry();
GetEntryName - Return current entry name
Syntax:CString8 GetEntryName() const;
GetEntrySize - Return current entry size
Syntax:unsigned int GetEntrySize() const;
GetEntryModificationTime - Get modification time of current entry (GMT)
Syntax:time_t GetEntryModificationTime() const;
IsEntryDirectory - Check if current entry is a directory
Syntax:bool IsEntryDirectory() const;
IsOpen - Check if directory is open
Syntax:bool IsOpen() const;
IsAccessDenied - Check if not enough access rights
Syntax:bool IsAccessDenied() const;
IsExisting - Check if path exists, file or directory
Syntax:static bool IsExisting(const char* szPath);
IsFile - Check if path is a file
Syntax:static bool IsFile(const char* szPath);
IsDirectory - Check if path is a directory
Syntax:static bool IsDirectory(const char* szPath);
ExpandHomeDir - Expand home directory
Syntax:static CString8 ExpandHomeDir(const char* szPath);
MakeDirectory - Create new directory
Syntax:static bool MakeDirectory(const char* szPath);
RenameDirectory - Rename or move directory
Syntax:static bool RenameDirectory(const char* szOldPath, const char* szNewPath);
RemoveDirectory - Remove an empty directory
Syntax:static bool RemoveDirectory(const char* szPath);

2.12. CFilePreferences

Description: File preferences with command line support
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class provides reading, writing and updating file preferences. A preferences file may have multiple sections to store text and numerical settings. It is possible to read optional runtime settings from a command line. Command line arguments will override file settings with the same name, but will not be written to disk automatically. Detected are common arguments such as "-key=value" or "/key=value", a key without value will be set to 1 (treated as boolean value).
Construction
Syntax:CFilePreferences();
CFilePreferences(const CFilePreferences& pref);
Constants
flush modes:
FLUSH_SECTION_NORMALupdate section, add or replace given entries
FLUSH_SECTION_CLEANUPupdate section, add new and deactivate old entries
FLUSH_SECTION_REPLACEreplace section with given entries
 
PREFERENCES_BUFFER_MAXLINE = ENGINE_MAXLINE
Create - Create preferences
Syntax:bool Create(const char* szFileName, const char* szSectionName = NULL, int argc = 0, char** argv = NULL);
Destroy - Destroy preferences
Syntax:void Destroy();
Flush - Flush any pending file changes
Notes: Preferences will be automatically flushed when you change between sections or the preferences file will be closed.
Syntax:void Flush(int nFlushMode = FLUSH_SECTION_NORMAL);
ReleaseFile - Release open file and used resources
Syntax:void ReleaseFile();
GetNextLine - Get next line
Notes: Returns next text line in current section or empty string. This method can be used to iterate through all text lines in a section. To start at the beginning of a section call SetSection(), any write access invalidates the current position. Text lines are not altered by optional command line settings.
Syntax:CString8 GetNextLine();
bool GetNextLine(char* pBuffer, int nBufferLen);
GetString - Get string
Notes: Returns string from current section or command line.
Syntax:CString8 GetString(const char* szKeyName, bool bQuoted = false);
bool GetString(const char* szKeyName, char* pBuffer, int nBufferLen, bool bQuoted = false);
GetValue - Get numerical value
Notes: Returns value from current section or command line.
Syntax:int GetValue(const char* szKeyName);
WriteString - Store string
Syntax:bool WriteString(const char* szKeyName, const char* szString, bool bQuoted = false);
WriteValue - Store numerical value
Syntax:bool WriteValue(const char* szKeyName, int nValue);
IsExisting - Check if key exists
Syntax:bool IsExisting(const char* szKeyName);
SetCommandLine - Set command line
Syntax:void SetCommandLine(int argc, char** argv);
SetSection - Set current section
Syntax:void SetSection(const char* szSectionName);
ResetSection - Reset section, no section will be selected
Syntax:void ResetSection();
GetFileName - Return name of file
Syntax:CString8 GetFileName() const;
GetSectionName - Return name of current section
Syntax:CString8 GetSectionName() const;
GetNextSectionName - Return name of next section, also make it current section
Syntax:CString8 GetNextSectionName();
CreateSections - Create new sections in preferences file
Notes: Comma separated list of section names, new sections will be created in given order.
Syntax:bool CreateSections(const char* szSectionNames);
WriteSection - Write a section to preferences file
Notes: Section will be replaced with given entries or added if not found.
Syntax:bool WriteSection(const char* szSectionName, const char* szTextBlock);
RenameSection - Rename a section in preferences file
Syntax:bool RenameSection(const char* szSectionName, const char* szSectionNameNew);
ClearSection - Clear a section in preferences file
Notes: All entries will be removed, no new section will be created.
Syntax:bool ClearSection(const char* szSectionName);
IsSectionExisting - Check if section exists
Syntax:bool IsSectionExisting(const char* szSectionName);
IsFileExisting - Check if file exists
Syntax:bool IsFileExisting();
IsCreated - Check if preferences are created
Syntax:bool IsCreated() const;
IsError - Check if error has happened while reading/writing preferences
Syntax:bool IsError() const;
ExtractCommandLineString - Extract string from command line
Syntax:static CString8 ExtractCommandLineString(const char* szKeyName, int argc, char** argv);

2.13. CFileStream

Description: File and memory access
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class provides reading and writing of files and memory. Once a stream is opened it makes no difference for the calling code if the stream operates with file or memory. This makes it easy to access files and resources or to keep temporary data in memory instead of writing it to the file system.
Construction
Syntax:CFileStream();
Constants
stream open modes:
STREAM_READopen for reading only, file/memory must exist
STREAM_READWRITEopen for reading and writing, file/memory must exist
STREAM_WRITEopen for writing only, stream is positioned to end
STREAM_WRITENEWopen for writing only, existing data is overwritten
 
stream seek modes:
STREAM_SEEK_BEGINposition from beginning of stream
STREAM_SEEK_CURRENTposition from current position in stream
STREAM_SEEK_ENDposition from end of stream
 
FILE_BUFFER_SIZE = ENGINE_FILE_BUFFER_SIZE
Open - Open stream
Notes: File streams are buffered for faster access times, use a buffer size of 0 bytes for unbuffered access. Memory streams create a buffer memory (a copy of the original memory) only if write access is requested.
Syntax:bool Open(const char* szFileName, int nStreamMode, int nBufferSize = FILE_BUFFER_SIZE);
bool Open(const MEMBLOCK memory, int nStreamMode);
bool Open(int nReserveMemory, int nStreamMode);
Close - Close stream
Syntax:void Close();
Seek - Set position in stream
Syntax:bool Seek(int nOffset, int nSeekMode = STREAM_SEEK_BEGIN);
Read - Read data from stream
Notes: Returns number of bytes read from stream.
Syntax:int Read(void* pBuffer, int nBufferLen);
ReadLine - Read text line from stream into buffer
Notes: Returns number of bytes read from stream (NOT resulting string length). Buffer will hold a Null terminated text without newline.
Syntax:int ReadLine(void* pBuffer, int nBufferLen);
Write - Write data to stream
Syntax:bool Write(const void* pBuffer, int nBufferLen);
WriteLine - Write text line to stream
Notes: Newline is appended if necessary. Any newline in text will be converted to platform specific newline format (CRLF or LF).
Syntax:bool WriteLine(const void* pBuffer, int nBufferLen = -1);
Flush - Flush any pending stream changes
Notes: File stream will be automatically flushed when you close it.
Syntax:void Flush();
Lock - Lock stream, file streams only
Syntax:bool Lock();
Unlock - Unlock stream, file streams only
Syntax:void Unlock();
GetPosition - Return current position in stream
Syntax:int GetPosition() const;
GetSize - Return size of stream
Syntax:int GetSize() const;
GetBuffer - Return pointer to buffer, memory streams only
Notes: Returns NULL if stream was opened for read-only access.
Syntax:BYTE* GetBuffer();
GetBufferConst - Return pointer to non-modifiable buffer, memory streams only
Syntax:const BYTE* GetBufferConst() const;
GetModificationTime - Get modification time of stream (GMT)
Syntax:time_t GetModificationTime() const;
IsOpen - Check if stream is open
Syntax:bool IsOpen() const;
IsAccessDenied - Check if not enough access rights to open stream
Syntax:bool IsAccessDenied() const;
IsNormalType - Check if normal stream type
Notes: Returns true for a normal file or memory stream, otherwise it's something else like a device, pipe or symbolic link.
Syntax:bool IsNormalType() const;
IsFileStream - Check if stream is a file stream
Syntax:bool IsFileStream() const;
IsMemoryStream - Check if stream is a memory stream
Syntax:bool IsMemoryStream() const;
IsError - Check if error has happened after opening stream
Syntax:bool IsError() const;
IsEOF - Check if end of stream was reached
Syntax:bool IsEOF() const;
GetDirectoryName - Extract directory name from path
Syntax:static CString8 GetDirectoryName(const char* szPath);
GetBaseName - Extract file name from path
Syntax:static CString8 GetBaseName(const char* szPath);
GetFileExtension - Extract file extension
Syntax:static CString8 GetFileExtension(const char* szFileName);
IsAbsolute - Check if absolute or relative path
Syntax:static bool IsAbsolute(const char* szPath);
RenameFile - Rename or move file
Syntax:static bool RenameFile(const char* szOldFileName, const char* szNewFileName);
RemoveFile - Remove file
Syntax:static bool RemoveFile(const char* szFileName);
ReplaceFiles - Replace files
Notes: The temporary file will be deleted if files can not be replaced.
Syntax:static bool ReplaceFiles(const char* szFileName, const char* szFileNameTemp);
SetModificationTime - Set modification time of file (GMT)
Syntax:static bool SetModificationTime(const char* szFileName, time_t tModificationTime);

2.14. CFileStreamParser

Description: File and memory parser
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class provides reading and writing configuration data from file or memory. A file stream may have multiple sections to store text and numerical settings.
Construction
Syntax:CFileStreamParser();
Constants
PARSE_BUFFER_MAXLINE = ENGINE_MAXLINE
Open - Open stream
Notes: File streams are buffered for faster access times, file must exist. Memory streams create a buffer memory (a copy of the original memory) only if write access is requested.
Syntax:bool Open(const char* szFileName, const char* szSectionName = NULL, bool bReadWrite = false);
bool Open(const MEMBLOCK memory, const char* szSectionName = NULL, bool bReadWrite = false);
Close - Close stream
Syntax:void Close();
GetNextLine - Get next line
Notes: Returns next text line in current section or empty string. This method can be used to iterate through all text lines in a section. To start at the beginning of a section call SetSection(), any write access invalidates the current position.
Syntax:CString8 GetNextLine();
bool GetNextLine(char* pBuffer, int nBufferLen);
UpdateLine - Update or add line
Notes: Updates text line in current section or adds it to the end of the section if not found. A partial match compares only the line beginning, is case insensitive and ignores any whitespace.
Syntax:bool UpdateLine(const char* szTextOld, const char* szTextNew, bool bPartialMatch = false);
RemoveLine - Remove line
Notes: Removes text line from current section. A partial match compares only the line beginning, is case insensitive and ignores any whitespace.
Syntax:bool RemoveLine(const char* szText, bool bPartialMatch = false);
GetString - Get string
Notes: Extracts string from a text line of format key=string or key:string.
Syntax:CString8 GetString(const char* szKeyName, bool bQuoted = false);
bool GetString(const char* szKeyName, char* pBuffer, int nBufferLen, bool bQuoted = false);
GetValue - Get numerical value
Notes: Extracts value from a text line of format key=value or key:value.
Syntax:int GetValue(const char* szKeyName);
IsExisting - Check if key exists
Syntax:bool IsExisting(const char* szKeyName);
SetSection - Set current section
Syntax:void SetSection(const char* szSectionName);
ResetSection - Reset section, no section will be selected
Syntax:void ResetSection();
GetFileName - Return name of file
Syntax:CString8 GetFileName() const;
GetSectionName - Return name of current section
Syntax:CString8 GetSectionName() const;
GetNextSectionName - Return name of next section, also make it current section
Syntax:CString8 GetNextSectionName();
ClearSection - Clear a section and remove all text lines
Syntax:bool ClearSection(const char* szSectionName, bool bRemoveComments = true);
IsSectionExisting - Check if section exists
Syntax:bool IsSectionExisting(const char* szSectionName);
IsOpen - Check if stream is open
Syntax:bool IsOpen() const;
IsError - Check if error has happened after opening stream
Syntax:bool IsError() const;
IsValidFileName - Check if file name is valid
Syntax:static bool IsValidFileName(const char* szFileName);
IsValidSectionName - Check if section name is valid
Syntax:static bool IsValidSectionName(const char* szSectionName);
IsValidKeyName - Check if key name is valid
Syntax:static bool IsValidKeyName(const char* szKeyName);
IsSectionName - Check if text matches with section name
Syntax:static bool IsSectionName(const char* szText, const char* szSectionName, int nSectionNameLen);
FilterSectionName - Filter section name Notes: Returns pointer on first difference or empty string if beginning of strings do not match.
Syntax:static const char* FilterSectionName(const char* szText, const char* szSectionFilter, int nSectionFilterLen);
GetKeyValue - Extract value of a key
Notes: Returns pointer on string or NULL if key was not found at beginning of string. Given text should be in format key=string or key:string.
Syntax:static const char* GetKeyValue(const char* szText, const char* szKeyName, int nKeyNameLen);

2.15. CNonCopyable

Description: Base class for non-copyable classes
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This is a base class to prevent copying of class instances. A class that handles memory/resources usually needs a copy constructor and an assignment operator. If you don't want to suppy this derive your class from CNonCopyAble.

2.16. CPtrOwned

Description: Smart pointer template, strong ownership
Header file: SharkEngine_Classes.h, namespace SharkEngine
Construction
Syntax:CPtrOwned();
CPtrOwned(T* ptr);
Create - Create owned pointer
Notes: The given object must have been allocated with a C++ new operator. The object will be automatically destroyed when the owned pointer is destoyed or gets out of scope.
Syntax:bool Create(T* ptr);
Destroy - Destroy owned pointer
Syntax:void Destroy();
GetPtr - Return pointer to object
Syntax:T* GetPtr() const;
IsCreated - Check if owned pointer is created
Syntax:bool IsCreated() const;

2.17. CPtrShared

Description: Smart pointer template, shared ownership
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This smart pointer can be used in STL containers.
Construction
Syntax:CPtrShared();
CPtrShared(T* ptr);
CPtrShared(const CPtrShared& r);
Create - Create shared pointer
Notes: The given object must have been allocated with a C++ new operator. The object will be automatically destroyed when the last copy of the shared pointer is destroyed or gets out of scope.
Syntax:bool Create(T* ptr);
Destroy - Destroy shared pointer
Syntax:void Destroy();
GetPtr - Return pointer to object
Syntax:T* GetPtr() const;
IsCreated - Check if shared pointer is created
Syntax:bool IsCreated() const;
IsUnique - Check if only one instance of the shared pointer exists
Syntax:bool IsUnique() const;

2.18. CResourceHandler

Description: Resource handler
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class provides reading resources. Instead of shipping additional files with an application you can link them into one executable or shared library. Resources can be compressed to save space. Each resource has meta data for file name, size and modification time.
Construction
Syntax:CResourceHandler();
CResourceHandler(HMODULE hResourceModule, int nResourceID, const char* szResourceType = ENGINE_RESOURCE_TYPE);
Constants
RESOURCE_ID_NONE = -1
Open - Open resource
Syntax:bool Open(HMODULE hResourceModule, int nResourceID, const char* szResourceType = ENGINE_RESOURCE_TYPE);
Close - Close resource
Syntax:void Close();
GetFileName - Get file name of resource
Syntax:CString8 GetFileName() const;
GetModificationTime - Get modification time of resource (GMT)
Syntax:time_t GetModificationTime() const;
GetData - Get resource data
Notes: Call ReleaseData() when data is not used any more. Actually, access to resource data is reference counted, for each time calling GetData() you have to call ReleaseData() one time.
Syntax:const MEMBLOCK GetData();
ReleaseData - Release resource data
Syntax:void ReleaseData();
IsOpen - Check if resource is open
Syntax:bool IsOpen() const;
IsCompressed - Check if resource data is compressed
Notes: Compressed resources are stored in 'gzip' format.
Syntax:bool IsCompressed() const;
FindResourceID - Find resource from file name
Syntax:static int FindResourceID(HMODULE hResourceModule, const char* szFileName, const char* szResourceType = ENGINE_RESOURCE_TYPE, int nRangeStartID = 0, int nRangeStopID = 0);
SetStringResource - Set default resource for strings
Syntax:static void SetStringResource(HMODULE hResourceModule, int nResourceID, const char* szResourceType = ENGINE_RESOURCE_TYPE, int nStringBaseID = 0);
ResetStringResource - Reset default resource for strings
Syntax:static void ResetStringResource();
GetString - Get string from default resource
Syntax:static bool GetString(int nStringID, CString8& sString);
static bool GetString(int nStringID, char* pBuffer, int nBufferLen);

2.19. CString8

Description: String class
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class provides comfortable string handling. It is a replacement for std::string (STL) with additional methods for formatting and comparing strings.
Construction
Syntax:CString8();
CString8(const CString8& sString);
CString8(const CString8& sString, int nPos, int nLen);
CString8(const MEMBLOCK memory);
CString8(const char* szText, int nTextLen);
CString8(const char* szText);
CString8(char c, int nRepeat = 1);
Constants
NOT_FOUND = -1string or character not found
MAX_POS = -1largest position in string
Clear - Clear string and release memory
Syntax:void Clear();
Reserve - Reserve space for string
Notes: Call this method if you want to reserve more space for a string, this is useful for handling large strings. The internally allocated memory may be bigger than requested and will be reallocated if necessary.
Syntax:void Reserve(int nLen);
Assign - Assign string
Syntax:void Assign(const CString8& sString);
void Assign(const CString8& sString, int nPos, int nLen);
void Assign(const char* szText, int nTextLen);
void Assign(const char* szText);
void Assign(char c, int nRepeat = 1);
Append - Append string
Syntax:void Append(const CString8& sString);
void Append(const CString8& sString, int nPos, int nLen);
void Append(const char* szText, int nTextLen);
void Append(const char* szText);
void Append(char c, int nRepeat = 1);
Compare - Compare strings
Syntax:int Compare(const CString8& sString) const;
int Compare(const char* szText) const;
CompareNoCase - Compare strings case-insensitive
Syntax:int CompareNoCase(const char* szText) const;
CompareEnd - Compare end of strings
Syntax:int CompareEnd(const char* szText, int nTextLen) const;
Erase - Remove text from string
Syntax:void Erase(int nPos, int nLen = MAX_POS);
Find - Find text
Notes: Returns position of given text in string or NOT_FOUND if not found.
Syntax:int Find(const char* szText, int nPos = 0) const;
int Find(char c, int nPos = 0) const;
FindFirstOf - Find first of different characters
Notes: Returns position in string or NOT_FOUND if not found.
Syntax:int FindFirstOf(const char* szCharSet, int nPos = 0) const;
int FindFirstNotOf(const char* szCharSet, int nPos = 0) const;
FindLastOf - Find last of different characters
Notes: Returns position in string or NOT_FOUND if not found.
Syntax:int FindLastOf(const char* szCharSet, int nPos = MAX_POS) const;
int FindLastNotOf(const char* szCharSet, int nPos = MAX_POS) const;
FindReverse - Find text reverse
Notes: Returns position of given text in string or NOT_FOUND if not found.
Syntax:int FindReverse(const char* szText, int nPos = MAX_POS) const;
int FindReverse(char c, int nPos = MAX_POS) const;
Format - Format string, sprintf style
Syntax:void Format(const char* szFormat, ...);
void FormatV(const char* szFormat, va_list ap);
MakeUpper - Convert string to upper case
Syntax:void MakeUpper();
MakeLower - Convert string to lower case
Syntax:void MakeLower();
Replace - Replace text in string
Notes: To replace text until end of string use MAX_POS as length argument.
Syntax:void Replace(int nPos, int nLen, const char* szText);
ReplaceAll - Replace all characters or texts in string
Syntax:void ReplaceAll(char cOld, char cNew);
void ReplaceAll(const char* szTextOld, const char* szTextNew);
RemoveAll - Remove all characters from string
Syntax:void RemoveAll(const char* szCharSet);
TrimLeft - Trim string by removing unwanted characters at beginning
Syntax:void TrimLeft(const char* szTarget = " \t\r\n");
TrimRight - Trim string by removing unwanted characters at end
Syntax:void TrimRight(const char* szTarget = " \t\r\n");
TrimAll - Trim string by removing unwanted characters at beginning and end
Syntax:void TrimAll(const char* szTarget = " \t\r\n");
TrimCut - Trim string by cutting off at first unwanted character
Syntax:void TrimCut(const char* szTarget);
SubStr - Return sub string
Syntax:CString8 SubStr(int nPos, int nLen = MAX_POS) const;
CStr - Return pointer to Null terminated string, non-modifiable
Syntax:const char* CStr() const;
GetLength - Return length of string
Syntax:int GetLength() const;
GetCapacity - Return size of internally allocated memory
Syntax:int GetCapacity() const;
IsEmpty - Check if string is empty
Syntax:bool IsEmpty() const;
SetAllocator - Set custom memory allocator
Notes: This allows to use an specialised allocator for this class, e.g. to exchange objects over library boundaries. Also see IAllocatorInterface.
Syntax:static void SetAllocator(IAllocatorInterface* pAllocator);

2.20. CStringBuffer8

Description: String buffer, supports direct manipulation
Header file: SharkEngine_Classes.h, namespace SharkEngine
Construction
Syntax:CStringBuffer8();
CStringBuffer8(const CStringBuffer8& sBuffer);
CStringBuffer8(const CString8& sString);
CStringBuffer8(const CString8& sString, int nPos, int nLen);
CStringBuffer8(const MEMBLOCK memory);
CStringBuffer8(const char* szText, int nTextLen);
CStringBuffer8(const char* szText);
CStringBuffer8(char c, int nRepeat = 1);
Constants
MAX_POS = -1largest position in string buffer
Clear - Clear string buffer and release memory
Syntax:void Clear();
GetBuffer - Return pointer to Null terminated string buffer
Notes: The returned pointer allows direct string manipulation. The string buffer includes space for one more optional Null terminator (buffer is one character longer than string length). Do not store the pointer, it is only temporary.
Syntax:char* GetBuffer(int nMinLen = 0);
UpdateBuffer - Update size of string buffer
Notes: Call this method if you want to adjust string length (e.g. after direct buffer manipulation). If the buffer is Null terminated you can obmit length argument. However, the internally allocated memory does NOT shrink or grow.
Syntax:void UpdateBuffer(int nNewLen = MAX_POS);
Reserve - Reserve space in string buffer
Notes: Call this method if you want to reserve a bigger string buffer, this is useful for handling large buffers. The internally allocated memory may be bigger than requested and will be reallocated if necessary.
Syntax:void Reserve(int nLen);
Assign - Assign string buffer
Syntax:void Assign(const CStringBuffer8& sBuffer);
void Assign(const CString8& sString);
void Assign(const CString8& sString, int nPos, int nLen);
void Assign(const char* szText, int nTextLen);
void Assign(const char* szText);
void Assign(char c, int nRepeat = 1);
CStr - Return pointer to Null terminated string buffer, non-modifiable
Syntax:const char* CStr() const;
GetLength - Return length of string buffer, NOT internally allocated memory
Syntax:int GetLength() const;
IsEmpty - Check if string buffer is empty
Syntax:bool IsEmpty() const;
SetAllocator - Set custom memory allocator
Notes: This allows to use an specialised allocator for this class, e.g. to exchange objects over library boundaries. Also see IAllocatorInterface.
Syntax:static void SetAllocator(IAllocatorInterface* pAllocator);

2.21. CStringParser

Description: String parser
Header file: SharkEngine_Classes.h, namespace SharkEngine
Comments: This class offers a parser to split strings into smaller sub strings
(tokens). It is also possible to use it as a command parser. A command parser will not split all tokens at once, but split only the first token and then the remaining arguments can be parsed as needed.
Construction
Syntax:CStringParser(int nArgumentsMax = PARSER_ARGUMENTS_MAX);
Constants
PARSER_ARGUMENTS_MAX = 16
Parse - Split text into sub strings
Notes: Initialises requested number of arguments, the last argument may remain as connected text if there are more arguments than requested.
Syntax:void Parse(char* szText, char cSeparator = ' ');
ParseCommand - Split text into command and argument string
Notes: Initialises command string with first sub string.
Syntax:void ParseCommand(char* szText, char cSeparator = ' ');
ParseArguments - Split argument string
Notes: Initialises requested number of arguments, the last argument may remain as connected text if there are more arguments than requested. Returns true if the requested number of arguments where found.
Syntax:bool ParseArguments(int nArguments, char cSeparator);
SetArguments - Assign new argument string
Notes: Call this method to assign an argument string, then call ParseArguments() to parse it.
Syntax:void SetArguments(char* szArguments);
IdentifyCommand - Identify command
Syntax:bool IdentifyCommand(const char* szCommand) const;
bool IdentifyCommand(const char* szCommand, const char* szCommandAlternative) const;
bool IdentifyCommand(const char* szCommand, const char* szCommandAlternative1, const char* szCommandAlternative2) const;
IdentifyArgument - Identify argument
Syntax:bool IdentifyArgument(const char* szArgument, int nIndex) const;
bool IdentifyArgument(const char* szArgument, const char* szArgumentAlternative, int nIndex) const;