CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
cmlabs::utils Namespace Reference

Classes

struct  DrumBeatInfo
 Bookkeeping record for one periodic "drum beat" timer. More...
class  Mutex
 Recursive mutual-exclusion lock, optionally named for cross-process use. More...
class  Semaphore
 Counting semaphore, optionally named for cross-process use. More...
class  Event
 Auto-reset notification event (condition variable style), optionally named for cross-process use. More...
struct  TimerSchedule
 One scheduled entry inside a Timer: id, active window and platform timer handle. More...
struct  TimerTrigger
 A single timer expiry: which timer fired and when. More...
class  Timer
 Multiplexing timer: schedule many periodic timers and consume their expiries from one queue. More...
class  WaitQueue
 Thread-safe FIFO queue with blocking waits, the workhorse producer/consumer channel in CMSDK. More...
class  WaitQueuePointer
 WaitQueue specialization for owned heap pointers: clear()/destructor delete remaining entries. More...
struct  TimeQueueEntry
 One (time, entry) pair inside a TimeQueue. More...
class  TimeQueue
 Thread-safe queue of entries ordered by due time; entries become retrievable once their timestamp passes. More...
class  TimeQueuePointer
 TimeQueue specialization for owned heap pointers: clear()/destructor delete remaining entries. More...
class  CommandLineInfo
 Singleton snapshot of the parsed process command line (set via SetCommandLine()). More...
class  Library
 Thin RAII wrapper around a dynamically loaded library (LoadLibrary / dlopen). More...
struct  NetworkInterfaces
 Description of one local network interface (IPv4 address, MAC and names). More...
struct  FileDetails
 Existence, type, permission and timestamp information for one file, as returned by GetFileDetails(). More...

Typedefs

typedef std::pair< std::string, Mutex * > SharedMemoryMutexMapPair
typedef std::pair< std::string, Semaphore * > SharedMemorySemaphoreMapPair
typedef std::pair< std::string, Event * > SharedMemoryEventMapPair

Functions

bool CalcTimeout (struct timespec &timeout, uint32 ms)
uint64 GetTime ()
static void DrumBeatCallback (union sigval p)
bool WaitForNextEvent (const char *name, uint32 ms, bool autocreate)
uint64 hton64 (const uint64 *input)
int32 ReadRegistryDWORD (const char *key)
int64 ReadRegistryQWORD (const char *key)
std::string ReadRegistryString (const char *key)
bool WriteRegistryDWORD (const char *key, int32 value)
bool WriteRegistryQWORD (const char *key, int64 value)
bool WriteRegistryString (const char *key, const char *value)
bool DeleteRegistryTree (const char *key)
bool RenameRegistryTree (const char *entry, const char *newName)
C-string helpers

Low-level, allocation-free operations on raw char buffers.

bool UtilsTest ()
 Run the built-in self test of the utils module.
void PrintBinary (void *p, uint32 size, bool asInt, const char *title)
 Hex/decimal dump a memory region to stdout for debugging.
const char * stristr (const char *str, const char *substr, uint32 len=0)
 Case-insensitive strstr.
bool GetNextLineEnd (const char *str, uint32 size, uint32 &len, uint32 &crSize)
 Find the end of the current line.
uint32 TextReplaceCharsInPlace (char *str, uint32 size, char find, char replace)
 Replace every occurrence of a character, in place.
bool TextEndsWith (const char *str, const char *end, bool caseSensitive=true)
 Test whether str ends with end.
bool TextStartsWith (const char *str, const char *start, bool caseSensitive=true)
 Test whether str starts with start.
uint32 strcpyavail (char *dst, const char *src, uint32 maxlen, bool copyAvailable)
 Bounded strcpy that always NUL-terminates.
const char * laststrstr (const char *str1, const char *str2)
 Find the last occurrence of str2 in str1.
const char * laststristr (const char *str1, const char *str2)
 Case-insensitive laststrstr().
Timers and queues
static void TimerCallback (int sig, siginfo_t *siginfo, void *context)
 POSIX signal-based timer callback trampoline (SIGEV_SIGNAL); routes the expiry into the owning Timer's trigger queue.
bool UnitTest_Timer ()
 Self test for the Timer class.
bool UnitTest_Utils ()
 Aggregate self test for miscellaneous utils functionality.
Shared memory

Named segments are implemented with CreateFileMapping on Windows and shm_open/mmap on POSIX; names are prefixed with the shared system instance so independent CMSDK deployments do not collide.

char * CreateSharedMemorySegment (const char *name, uint64 size, bool force=false)
 Create a named shared memory segment and map it into this process.
char * OpenSharedMemorySegment (const char *name, uint64 size)
 Open and map an existing named shared memory segment.
bool CloseSharedMemorySegment (char *data, uint64 size)
 Unmap a segment previously created/opened here.
Bit field operations

Helpers for compact allocation bitmaps (used e.g.

by the shared-memory block allocators). Bit 0 is the least significant bit of the first byte.

uint64 ntoh64 (const uint64 *input)
 Convert a 64-bit value from network to host byte order.
uint64 hton64 (const uint64_t *input)
 Convert a 64-bit value from host to network byte order.
uint32 Calc32BitFieldSize (uint32 bitsize)
 Compute the byte size needed for a bitfield of bitsize bits, rounded up to a 32-bit boundary.
bool Reset32BitField (char *bitfield, uint32 bytesize)
 Zero the whole bitfield, marking every bit as free.
bool GetFirstFreeBitLoc (const char *bitfield, uint32 bytesize, uint32 &loc)
 Find the first 0 (free) bit.
bool GetFirstFreeBitLocN (const char *bitfield, uint32 bytesize, uint32 num, uint32 &loc)
 Find the first run of num consecutive 0 bits.
bool SetBit (uint32 loc, bit value, char *bitfield, uint32 bytesize)
 Set bit loc to value.
bool SetBitN (uint32 loc, uint32 num, bit value, char *bitfield, uint32 bytesize)
 Set num consecutive bits starting at loc to value.
bool GetBit (uint32 loc, const char *bitfield, uint32 bytesize, bit &val)
 Read bit loc.
bool GetLastOccupiedBitLoc (const char *bitfield, uint32 bytesize, uint32 &loc)
 Find the highest set (occupied) bit.
std::string GetBitFieldAsString (const char *bitfield, uint32 bytesize, uint32 size)
 Render the first size bits as a '0'/'1' string, for debugging.
std::string PrintBitFieldString (const char *bitfield, uint32 bytesize, uint32 size, const char *title)
 Like GetBitFieldAsString() but prefixed with title and formatted for printing.
Threading and CPU statistics
std::string PrintProgramTrace (uint32 startLine=0, uint32 endLine=0)
 Format the current call stack as printable text.
std::list< std::string > GetProgramTrace ()
 Capture the current call stack.
int32 AtomicIncrement32 (int32 volatile &v)
 Atomically increment a 32-bit value.
int64 AtomicIncrement64 (int64 volatile &v)
 Atomically increment a 64-bit value.
int32 AtomicDecrement32 (int32 volatile &v)
 Atomically decrement a 32-bit value.
int64 AtomicDecrement64 (int64 volatile &v)
 Atomically decrement a 64-bit value.
bool Sleep (uint32 ms)
 Suspend the calling thread.
bool CreateThread (THREAD_FUNCTION func, void *args, ThreadHandle &thread, uint32 &osID)
 Start a new OS thread.
bool WaitForThreadToFinish (ThreadHandle hThread, uint32 timeoutMS=0)
 Join a thread.
bool CheckForThreadFinished (ThreadHandle hThread)
 Non-blocking check whether a thread has terminated.
bool TerminateThread (ThreadHandle hThread)
 Forcibly kill a thread.
bool PauseThread (ThreadHandle hThread)
 Suspend a thread's execution.
bool ContinueThread (ThreadHandle hThread)
 Resume a thread paused with PauseThread().
bool GetCurrentThreadUniqueID (uint32 &tid)
 Get a process-unique id for the calling thread.
bool GetCurrentThreadOSID (uint32 &tid)
 Get the OS-level id of the calling thread (gettid / GetCurrentThreadId).
bool GetCurrentThread (ThreadHandle &thread)
 Get the handle of the calling thread.
bool IsThreadRunning (ThreadHandle hThread)
 Check whether a thread is still alive.
uint32 GetThreadStatColAbility ()
 Report this platform's capability for per-thread CPU statistics collection.
bool GetCPUTicks (ThreadHandle hThread, uint64 &ticks)
 Get accumulated CPU time of a specific thread.
bool GetCPUTicks (uint64 &ticks)
 Get accumulated CPU time of the calling thread.
bool GetProcessCPUTicks (uint64 &ticks)
 Get accumulated CPU time of the current process.
bool GetProcessCPUTicks (uint32 osProcID, uint64 &ticks)
 Get accumulated CPU time of another process.
bool GetProcAndOSCPUUsage (double &procPercentUse, double &osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks)
 Sample CPU usage of this process and of the whole OS since the previous call.
bool GetProcAndOSCPUUsage (uint32 osProcID, double &procPercentUse, double &osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks)
 As GetProcAndOSCPUUsage() above, but for an arbitrary process.
bool GetOSCPUUsage (double &percentUse)
 Get the instantaneous total OS CPU usage.
bool GetThreadPriority (ThreadHandle hThread, uint16 priority)
 Query a thread's scheduling priority.
bool SetThreadPriority (ThreadHandle hThread, uint16 priority)
 Set a thread's scheduling priority.
int ToOSPriority (int pri)
 Map a CMSDK priority value to the platform's native priority scale.
int FromOSPriority (int pri)
 Map a native OS priority back to the CMSDK priority scale.
bool SignalThread (ThreadHandle hThread, int32 signal)
 Send a signal to a thread (POSIX pthread_kill; limited emulation on Windows).
Desktop and console
bool GetDesktopSize (uint32 &width, uint32 &height)
 Get the primary desktop resolution.
bool RenameConsoleWindow (const char *name, bool prepend=false)
 Set the console window title.
bool MoveConsoleWindow (int32 x=-1, int32 y=-1, int32 w=-1, int32 h=-1)
 Move/resize the console window.
Process management
int RunOSCommand (const char *cmdline, const char *initdir, uint32 timeout, std::string &stdoutString, std::string &stderrString)
 Run a command synchronously and capture its output.
uint32 NewProcess (const char *cmdline, const char *initdir=NULL, const char *title=NULL, int16 x=-1, int16 y=-1, int16 w=-1, int16 h=-1)
 Launch a detached child process.
uint8 GetProcessStatus (uint32 proc, int &returncode)
 Poll a child started with NewProcess().
bool EndProcess (uint32 proc)
 Forcibly terminate a child process.
uint8 WaitForProcess (uint32 proc, uint32 timeout, int &returncode)
 Wait for a child to exit.
uint32 GetLocalProcessID ()
 Get the OS process id of the current process.
OS and hardware information
const char * GetComputerName ()
 Get this machine's hostname.
uint64 GetProcessMemoryUsage ()
 Current resident memory usage of this process.
uint64 GetPeakProcessMemoryUsage ()
 Peak resident memory usage of this process.
uint16 GetCPUCount ()
 Number of logical CPU cores.
uint16 GetCPUArchitecture ()
 CPU architecture id.
uint64 GetCPUSpeed ()
 Nominal CPU clock speed.
uint64 GetSystemMemorySize ()
 Total physical RAM installed.
bool GetSystemMemoryUsage (uint64 &totalRAM, uint64 &freeRAM)
 Query total and free physical memory.
const char * GetSystemArchitecture ()
 Architecture name string, e.g.
const char * GetSystemOSName ()
 OS name string, e.g.
bool GetSystemOSVersion (uint16 &major, uint16 &minor, uint16 &build, char *text, uint16 textSize)
 Detailed OS version.
Sockets and networking

Thin portability layer over BSD sockets / Winsock.

On non-Windows builds SOCKET is a plain int and closesocket() maps to close(); CHECKNETWORKINIT expands to a Winsock WSAStartup guard on Windows and to nothing elsewhere.

bool GetSocketError (int wsaError, char *errorString, uint16 errorStringMaxSize, bool *isRecoverable)
 Translate a socket error code into text and classify it.
int GetLastOSErrorNumber ()
 Get the last OS error number (errno / GetLastError()).
std::string GetLastOSErrorMessage ()
 Get the last OS error as human-readable text.
bool WaitForSocketReadability (SOCKET s, int32 timeout)
 Wait until a socket has data to read.
bool WaitForSocketWriteability (SOCKET s, int32 timeout)
 Wait until a socket can be written without blocking.
bool SetSocketNonBlockingMode (SOCKET s)
 Put a socket into non-blocking mode.
bool SetSocketBlockingMode (SOCKET s)
 Put a socket into blocking mode.
bool LookupIPAddress (const char *name, uint32 &address)
 Resolve a hostname to an IPv4 address.
bool LookupHostname (uint32 address, char *name, uint32 maxSize)
 Reverse-resolve an IPv4 address to a hostname.
std::string GetLocalHostnameString ()
 Local hostname as std::string.
bool GetLocalHostname (char *name, uint32 maxSize)
 Local hostname into a caller buffer.
bool IsLocalIPAddress (const char *addr)
 Test whether a textual address refers to this machine (loopback or a local interface).
bool IsLocalIPAddress (uint32 &address)
 Test whether a numeric IPv4 address is local.
bool GetLocalIPAddress (uint32 &address)
 Get the primary local IPv4 address.
uint32 * GetLocalIPAddresses (uint32 &count)
 List all local IPv4 addresses.
bool GetLocalMACAddress (uint64 &address)
 Get the primary local MAC address.
uint64 * GetLocalMACAddresses (uint32 &count)
 List all local MAC addresses.
NetworkInterfacesGetLocalInterfaces (uint32 &count)
 Enumerate local network interfaces with address, MAC and names.
bool GetNextAvailableLocalPort (uint16 lastPort, uint16 &nextPort)
 Find the next free TCP port above lastPort.
Registry access (Windows; no-ops/defaults elsewhere)

Keys are given as full paths, e.g.

"HKEY_LOCAL_MACHINE\\Software\\...". On non-Windows platforms these functions return failure/empty values.

uint32 ReadRegistryDWORD (const char *key, const char *entry)
 Read a 32-bit registry value.
uint64 ReadRegistryQWORD (const char *key, const char *entry)
 Read a 64-bit registry value.
std::string ReadRegistryString (const char *key, const char *entry)
 Read a string registry value.
bool WriteRegistryDWORD (const char *key, const char *entry, uint32 value)
 Write a 32-bit registry value (creates the key when needed).
bool WriteRegistryQWORD (const char *key, const char *entry, uint64 value)
 Write a 64-bit registry value.
bool WriteRegistryString (const char *key, const char *entry, const char *value)
 Write a string registry value.
bool DeleteRegistryEntry (const char *key, const char *entry)
 Delete a single value from a key.
bool DeleteRegistryKey (const char *key)
 Delete a (leaf) registry key.
bool DeleteRegistryTree (const char *root, const char *key)
 Recursively delete a key and all subkeys.
bool CopyRegistryTree (const char *entry, const char *newName)
 Recursively copy a registry subtree.
String replacement and templating
uint32 StringSingleReplace (std::string &text, std::string key, std::string value, bool onlyFirst)
 Replace occurrences of key with value in text.
uint32 StringMultiReplace (std::string &text, std::map< std::string, std::string > &map, bool onlyFirst)
 Apply many key→value replacements in one pass.
uint32 StringScriptReplace (std::string &text, std::string name, std::list< std::map< std::string, std::string > > &list)
 Expand a named repeating template block in text once per map in list, substituting each map's keys inside the block.
Text case, trimming, splitting and joining

All functions return new std::string values and leave inputs untouched.

NULL inputs are treated as empty strings unless noted.

std::string TextCapitalise (const char *text)
 Capitalise the first letter of text.
std::string TextUppercase (const char *text)
 Convert to upper case (ASCII/current locale).
std::string TextLowercase (const char *text)
 Convert to lower case (ASCII/current locale).
std::string TextIndent (const char *text, const char *indent)
 Prefix every line of text with indent.
std::string TextUnindent (const char *text)
 Remove one level of leading indentation from every line.
std::string TextTrimQuotes (const char *text)
 Strip a single pair of surrounding quotes if present.
std::string TextTrim (const char *text)
 Strip leading and trailing whitespace.
std::multimap< std::string, std::string > TextMultiMapSplit (const char *text, const char *outersplit, const char *innersplit)
 Split "k=v<sep>k=v..." text into a multimap (duplicate keys preserved).
std::map< std::string, std::string > TextMapSplit (const char *text, const char *outersplit, const char *innersplit)
 Split "k=v<sep>k=v..." text into a map (later duplicates overwrite earlier ones).
std::string TextJoin (std::vector< std::string > &list, const char *split, uint32 start=0, uint32 count=0)
 Join vector elements with split.
std::string TextJoin (std::list< std::string > &list, const char *split, uint32 start=0, uint32 count=0)
 Join list elements with split.
std::string TextJoin (std::map< std::string, std::string > &map, const char *innersplit, const char *outersplit, bool keyquotes, bool valquotes)
 Join a map as "key<innersplit>value<outersplit>..." with optional quoting.
std::string TextJoinJSON (std::map< std::string, std::string > &map)
 Serialize a map as a JSON object (keys/values escaped).
std::string TextJoinXML (std::map< std::string, std::string > &map, const char *innernodeName, const char *outernodeName)
 Serialize a map as XML, one innernodeName element per pair inside an outernodeName element.
std::vector< std::string > TextListSplit (const char *text, const char *split, bool keepEmpty=true, bool autoTrim=false)
 Split text on a separator.
std::vector< std::string > TextListSplitLines (const char *text, bool keepEmpty=true, bool autoTrim=false)
 Split text into lines, handling both \n and \r\n.
std::vector< std::string > TextListBreakLines (const char *text, uint32 maxLineLength=80)
 Word-wrap text into lines no longer than maxLineLength.
std::string TextListBreakLines (const char *text, uint32 maxLineLength, const char *breakstr)
 Word-wrap text, joining the wrapped lines with breakstr.
std::string TextVectorConcat (std::vector< std::string >, const char *sep, bool allowEmpty=true)
 Concatenate vector entries with sep.
std::vector< std::string > TextCommandlineSplit (const char *cmdline)
 Split a command line into arguments, honouring quoting rules.
char ** SplitCommandline (const char *cmdline, int &argc)
 Split a command line into a malloc'ed argv array.
wchar_t ** SplitCommandlineW (const char *cmdline, int &argc)
 Wide-character variant of SplitCommandline() (for Windows APIs).
bool DeleteCommandline (char **argv, int argc)
 Free an argv array produced by SplitCommandline().
printf-style string formatting
std::string StringFormat (const char *format,...)
 printf into a std::string.
char * StringFormat (uint32 &size, const char *format,...)
 printf into a freshly allocated buffer.
bool StringFormatInto (char *dst, uint32 maxsize, const char *format,...)
 printf into a caller-supplied buffer with truncation.
char * StringFormatVA (uint32 &size, const char *format, va_list args)
 va_list core used by the other StringFormat overloads.
Numeric conversion and checksums
unsigned char Hex2Char (const char *str)
 Parse two hex digits into a byte.
unsigned char Dec2Char (const char *str)
 Parse up to three decimal digits into a byte.
int CRC32 (const char *addr, uint32 length, int32 crc=0)
 Compute (or continue) a CRC-32 checksum.
int8 CompareFloats (float64 a, float64 b)
 Compare two doubles with epsilon tolerance.
File system

Paths accept the platform's native separator; most functions also tolerate '/' on Windows.

Directory listing uses dirent (via direntwin.h on Windows).

std::string ReadAFileString (std::string filename)
 Read an entire file into a std::string.
char * ReadAFile (const char *filename, uint32 &length, bool binary=false)
 Read an entire file into a new buffer.
char * ReadAFile (const char *dir, const char *filename, uint32 &length, bool binary=false)
 Read dir/filename into a new buffer; see ReadAFile().
bool WriteAFile (const char *filename, const char *data, uint32 length, bool binary=false)
 Write (create/overwrite) a file.
bool WriteAFile (const char *dir, const char *filename, const char *data, uint32 length, bool binary=false)
 Write dir/filename; see WriteAFile().
bool AppendToAFile (const char *filename, const char *data, uint32 length, bool binary=false)
 Append to a file, creating it if missing.
bool AppendToAFile (const char *dir, const char *filename, const char *data, uint32 length, bool binary=false)
 Append to dir/filename; see AppendToAFile().
char * GetFileList (const char *dirname, const char *ext, uint32 &count, bool fullpath, uint32 maxNameLen=256)
 List files in a directory matching an extension.
FileDetails GetFileDetails (const char *filename)
 Stat a file.
std::string GetFilePath (const char *filename)
 Directory portion of a path.
const char * GetFileBasename (const char *filename)
 Filename portion of a path.
std::string GetCurrentDir ()
 Current working directory.
bool DeleteAFile (const char *filename, bool force)
 Delete a file.
bool DeleteAFile (const char *dir, const char *filename, bool force)
 Delete dir/filename; see DeleteAFile().
bool DeleteADir (const char *dirname, bool force)
 Delete a directory (recursively when force).
bool CreateADir (const char *dirname)
 Create a directory (parents included where supported).
bool DoesADirExist (const char *dirname)
 Test whether a directory exists.
bool DoesAFileExist (const char *filename)
 Test whether a regular file exists.
bool DeleteFilesInADir (const char *dirname, bool force)
 Delete all files inside a directory, leaving the directory itself.
bool ChangeAFileAttr (const char *filename, bool read, bool write)
 Change read/write permission attributes of a file.
bool MoveAFile (const char *oldfilename, const char *newfilename, bool force=false)
 Move/rename a file.
bool MoveAFile (const char *olddir, const char *oldfilename, const char *newdir, const char *newfilename, bool force=false)
 Move a file between directories; see MoveAFile().
bool CopyAFile (const char *oldfilename, const char *newfilename, bool force=false)
 Copy a file.
bool CopyAFile (const char *olddir, const char *oldfilename, const char *newdir, const char *newfilename, bool force=false)
 Copy a file between directories; see CopyAFile().
ASCII ↔ number conversion

The Ascii2* parsers operate on a substring [start,end) of the input; end=0 means "until NUL".

They skip surrounding whitespace and never throw.

Note
Common behaviour of the Ascii2Int64/Uint64/Int32/Uint32/Float64 family: NULL input, start>end or entirely non-numeric text all yield 0, which is indistinguishable from a legitimate parsed zero — call IsTextNumeric() first when validity matters. Parsing is strtoll/strtod based, so leading whitespace is skipped, parsing stops at the first non-numeric character, and out-of-range values saturate to the type's min/max without an error indication. When end!=0 a temporary substring copy is allocated internally; the end=0 form is allocation-free. Ascii2Float64 always parses with '.' as the decimal point regardless of the process locale.
char * Int2Ascii (int64 value, char *result, uint16 size, uint8 base)
 Render a signed integer as text in an arbitrary base.
char * Uint2Ascii (uint64 value, char *result, uint16 size, uint8 base)
 Render an unsigned integer as text in an arbitrary base.
unsigned char * Ascii2UTF16LE (const char *ascii, uint32 len, uint32 &size)
 Convert 8-bit ASCII text to UTF-16LE (used for Windows wide APIs and some protocols).
bool IsTextNumeric (const char *ascii, uint32 start=0, uint32 end=0)
 Test whether a (sub)string is a valid number.
int64 Ascii2Int64 (const char *ascii, uint32 start=0, uint32 end=0)
 Parse a signed 64-bit decimal integer from a substring.
uint64 Ascii2Uint64 (const char *ascii, uint32 start=0, uint32 end=0)
 Parse an unsigned 64-bit decimal integer from a substring.
uint64 AsciiHex2Uint64 (const char *ascii, uint32 start=0, uint32 end=0)
 Parse an unsigned 64-bit hexadecimal integer (with or without 0x) from a substring.
int32 Ascii2Int32 (const char *ascii, uint32 start=0, uint32 end=0)
 Parse a signed 32-bit decimal integer from a substring.
uint32 Ascii2Uint32 (const char *ascii, uint32 start=0, uint32 end=0)
 Parse an unsigned 32-bit decimal integer from a substring.
uint32 AsciiHex2Uint32 (const char *ascii, uint32 start=0, uint32 end=0)
 Parse an unsigned 32-bit hexadecimal integer from a substring.
float64 Ascii2Float64 (const char *ascii, uint32 start=0, uint32 end=0)
 Parse a 64-bit float from a substring (decimal point, not locale dependent).
char * TextSubstringCopy (const char *ascii, uint32 start, uint32 end)
 Copy the substring [start,end) into a new NUL-terminated buffer.
std::string DecodeJSON (std::string str)
 Unescape a JSON string value (\" \\ \n \t \uXXXX etc.).
std::string EncodeJSON (std::string str)
 Escape text for embedding as a JSON string value.
Random numbers and human-readable sizes
bool SeedRandomValues (uint32 seedvalue=0)
 Seed the pseudo-random generator.
double RandomValue ()
 Uniform random double in [0,1).
double RandomValue (double to)
 Uniform random double in [0,to).
double RandomValue (double from, double to)
 Uniform random double in [from,to).
double RandomValue (double from, double to, double interval)
 Uniform random double in [from,to) quantized to multiples of interval.
int64 RandomInt (int64 from=0, int64 to=100)
 Uniform random integer in [from,to].
std::string BytifySize (double val)
 Format a byte count with binary units, e.g.
std::string BytifySizes (double val1, double val2)
 Format two byte counts as "x / y" with matching units.
std::string BytifyRate (double val)
 Format a byte rate, e.g.
std::string BytifyRates (double val1, double val2)
 Format two byte rates as "x / y" with matching units.

Variables

static SharedMemoryFileHandleMapTypeSharedMemoryFileHandleMap = NULL
static uint16 SharedSystemInstance = 0
static MutexSharedMemoryMutexMapMutex = NULL
static std::map< std::string, Mutex * > * SharedMemoryMutexMap = NULL
static MutexSharedMemorySemaphoreMapMutex = NULL
static std::map< std::string, Semaphore * > * SharedMemorySemaphoreMap = NULL
static MutexSharedMemoryEventMapMutex = NULL
static std::map< std::string, Event * > * SharedMemoryEventMap = NULL
char OSLocalHostName [1024] = {0}
char OSArchitectureName [1024] = {0}
char OSName [1024] = {0}

Synchronization primitives (mutexes, semaphores, events, drum beats)

Named primitives are backed by OS objects shared between processes (Windows kernel objects, POSIX shared memory + pthread process-shared objects, or dispatch/mach objects on macOS); unnamed ones are process-local.

typedef bool(* DrumBeatFunc) (uint32 id, uint32 count)
 Callback invoked on every drum-beat tick.
static std::map< uint32, DrumBeatInfo > * DrumBeatMap = NULL
bool SetSharedSystemInstance (uint32 inst)
 Set the instance number used to namespace shared OS objects, allowing several independent CMSDK systems on one host.
uint32 GetSharedSystemInstance ()
 Get the current shared-system instance number.
bool CreateDrumBeat (uint32 id, uint32 interval, DrumBeatFunc func, bool autostart=false)
 Create a periodic timer ("drum beat") that calls func every interval ms.
bool StartDrumBeat (uint32 id)
 Start (or resume) a previously created drum beat.
bool StopDrumBeat (uint32 id)
 Stop a running drum beat without destroying it.
bool EndDrumBeat (uint32 id)
 Destroy a drum beat and release its OS timer.
bool EnterMutex (const char *name, uint32 ms, bool autocreate=true)
 Acquire a named global mutex, creating it on first use.
bool LeaveMutex (const char *name)
 Release a named global mutex previously acquired with EnterMutex().
bool DestroyMutex (const char *name)
 Destroy a named global mutex and remove it from the registry.
SemaphoreGetSemaphore (const char *name, bool autocreate=true)
 Look up (and optionally create) a named semaphore in the global registry.
bool WaitForSemaphore (const char *name, uint32 ms, bool autocreate=true)
 Wait on a named global semaphore.
bool SignalSemaphore (const char *name)
 Signal a named global semaphore.
bool DestroySemaphore (const char *name)
 Destroy a named global semaphore.
bool WaitNextEvent (const char *name, uint32 ms, bool autocreate=true)
 Wait for the next signal on a named global event.
bool SignalEvent (const char *name)
 Signal a named global event.
bool DestroyEvent (const char *name)
 Destroy a named global event.

Dynamic libraries and command line

typedef int(* LibraryFunction) ()
 Signature of a plain function exported from a dynamically loaded library.
bool SetCommandLine (int argc, char *argv[])
 Parse and store the process command line for later retrieval by the Get/HasCommandLine* functions.
std::string GetCommandLine ()
 Get the full original command line as one string.
std::string GetCommandLinePath ()
 Get the directory portion of the executable path.
std::string GetCommandLineExecutable ()
 Get the full executable path as invoked.
std::string GetCommandLineExecutableOnly ()
 Get just the executable filename without path.
uint32 GetCommandLineArgCount ()
 Number of positional command line items (excluding the executable).
std::string GetCommandLineArg (uint16 n)
 Get the n-th positional command line item.
std::string GetCommandLineArg (const char *key)
 Get the value of a 'key=value' command line argument.
bool HasCommandLineArg (const char *key, std::string &value)
 Test for a 'key=value' argument without mutating the argument map.
LibraryOpenLibrary (const char *libName)
 Load a library by name, applying platform filename conventions.

Function Documentation

◆ CalcTimeout()

bool cmlabs::utils::CalcTimeout ( struct timespec & timeout,
uint32 ms )

◆ DeleteRegistryTree()

bool cmlabs::utils::DeleteRegistryTree ( const char * key)

Definition at line 8091 of file Utils.cpp.

◆ DrumBeatCallback()

◆ GetTime()

uint64 cmlabs::utils::GetTime ( )

Definition at line 448 of file Utils.cpp.

◆ hton64()

uint64 cmlabs::utils::hton64 ( const uint64 * input)

Definition at line 2428 of file Utils.cpp.

References ntoh64().

◆ ReadRegistryDWORD()

int32 cmlabs::utils::ReadRegistryDWORD ( const char * key)

Definition at line 8084 of file Utils.cpp.

◆ ReadRegistryQWORD()

int64 cmlabs::utils::ReadRegistryQWORD ( const char * key)

Definition at line 8085 of file Utils.cpp.

◆ ReadRegistryString()

std::string cmlabs::utils::ReadRegistryString ( const char * key)

Definition at line 8086 of file Utils.cpp.

◆ RenameRegistryTree()

bool cmlabs::utils::RenameRegistryTree ( const char * entry,
const char * newName )

Definition at line 8095 of file Utils.cpp.

◆ WaitForNextEvent()

bool cmlabs::utils::WaitForNextEvent ( const char * name,
uint32 ms,
bool autocreate )

◆ WriteRegistryDWORD()

bool cmlabs::utils::WriteRegistryDWORD ( const char * key,
int32 value )

Definition at line 8087 of file Utils.cpp.

◆ WriteRegistryQWORD()

bool cmlabs::utils::WriteRegistryQWORD ( const char * key,
int64 value )

Definition at line 8088 of file Utils.cpp.

◆ WriteRegistryString()

bool cmlabs::utils::WriteRegistryString ( const char * key,
const char * value )

Definition at line 8089 of file Utils.cpp.

Variable Documentation

◆ OSArchitectureName

char cmlabs::utils::OSArchitectureName[1024] = {0}

Definition at line 4507 of file Utils.cpp.

Referenced by GetSystemArchitecture().

◆ OSLocalHostName

char cmlabs::utils::OSLocalHostName[1024] = {0}

Definition at line 4506 of file Utils.cpp.

Referenced by GetComputerName().

◆ OSName

char cmlabs::utils::OSName[1024] = {0}

Definition at line 4508 of file Utils.cpp.

Referenced by GetSystemOSName().