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  ProcessData
 POSIX capture bookkeeping for children started via NewProcessEx(captureOutput). 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
typedef std::pair< uint32, ProcessData * > Proc_Pair

Functions

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.
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 ReapThread (ThreadHandle &hThread)
bool TryReapThread (ThreadHandle &hThread)
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.
Managed child launch (T1.4 external-executable support)

Extended launch/lifecycle helpers used by ExternalExecManager.

On POSIX these are thin conveniences; on Windows they carry the env block, working directory, optional stdout/stderr capture pipes and console-group/graceful-stop plumbing that plain NewProcess() does not.

uint32 NewProcessEx (const char *cmdline, const char *initdir, const char *title, const std::map< std::string, std::string > *env, bool captureOutput, bool ignoreOutput, bool newProcessGroup, int posixParentDeathSig=0, bool posixUseShell=false)
 Launch a child with environment overrides and optional output capture.
bool ReadProcessOutput (uint32 proc, std::string &out, std::string &err)
 Read any pending captured stdout/stderr from a child launched with captureOutput=true.
void ReleaseProcessCapture (uint32 proc)
 POSIX only: release the captured stdout/stderr read-pipes recorded for a child by NewProcessEx(captureOutput=true), WITHOUT signalling or reaping the child.
bool SendProcessBreak (uint32 proc, int sig)
 Attempt a graceful stop: POSIX sends the given signal; Windows posts a CTRL_BREAK to the child's process group (requires newProcessGroup=true at launch) and falls back to nothing if unsupported.
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
static std::map< uint32, ProcessData * > * ProcessInformationMap = 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.

Typedef Documentation

◆ LibraryFunction

typedef int(* cmlabs::utils::LibraryFunction) ()

Signature of a plain function exported from a dynamically loaded library.

Definition at line 1311 of file Utils.h.

Function Documentation

◆ AppendToAFile() [1/2]

bool cmlabs::utils::AppendToAFile ( const char * dir,
const char * filename,
const char * data,
uint32 length,
bool binary = false )

Append to dir/filename; see AppendToAFile().

Returns
true on success.

Definition at line 7301 of file Utils.cpp.

References AppendToAFile().

◆ AppendToAFile() [2/2]

bool cmlabs::utils::AppendToAFile ( const char * filename,
const char * data,
uint32 length,
bool binary = false )

Append to a file, creating it if missing.

Parameters
filenamePath.
dataBytes.
lengthByte count.
binaryBinary mode.
Returns
true on success.

Definition at line 7312 of file Utils.cpp.

Referenced by _wrap_AppendToAFile__SWIG_0(), _wrap_AppendToAFile__SWIG_1(), _wrap_AppendToAFile__SWIG_2(), _wrap_AppendToAFile__SWIG_3(), AppendToAFile(), cmlabs::Internal_StatsLog(), and cmlabs::LogSystem::LogSystemPrint().

◆ Ascii2Float64()

◆ Ascii2Int32()

int32 cmlabs::utils::Ascii2Int32 ( const char * ascii,
uint32 start = 0,
uint32 end = 0 )

Parse a signed 32-bit decimal integer from a substring.

Returns
Parsed value; 0 when not numeric.

Definition at line 7923 of file Utils.cpp.

References TextSubstringCopy().

Referenced by _wrap_Ascii2Int32__SWIG_0(), _wrap_Ascii2Int32__SWIG_1(), and _wrap_Ascii2Int32__SWIG_2().

◆ Ascii2Int64()

◆ Ascii2Uint32()

uint32 cmlabs::utils::Ascii2Uint32 ( const char * ascii,
uint32 start = 0,
uint32 end = 0 )

◆ Ascii2Uint64()

◆ Ascii2UTF16LE()

unsigned char * cmlabs::utils::Ascii2UTF16LE ( const char * ascii,
uint32 len,
uint32 & size )

Convert 8-bit ASCII text to UTF-16LE (used for Windows wide APIs and some protocols).

Parameters
asciiInput text.
lenInput length in bytes.
[out]sizeOutput size in bytes.
Returns
Allocated UTF-16LE buffer (caller frees).
Note
Bytes are widened as Latin-1; no multi-byte decoding.

Definition at line 5494 of file Utils.cpp.

Referenced by _wrap_Ascii2UTF16LE().

◆ AsciiHex2Uint32()

uint32 cmlabs::utils::AsciiHex2Uint32 ( const char * ascii,
uint32 start = 0,
uint32 end = 0 )

Parse an unsigned 32-bit hexadecimal integer from a substring.

Returns
Parsed value.

Definition at line 7943 of file Utils.cpp.

References TextSubstringCopy().

Referenced by _wrap_AsciiHex2Uint32__SWIG_0(), _wrap_AsciiHex2Uint32__SWIG_1(), and _wrap_AsciiHex2Uint32__SWIG_2().

◆ AsciiHex2Uint64()

uint64 cmlabs::utils::AsciiHex2Uint64 ( const char * ascii,
uint32 start = 0,
uint32 end = 0 )

Parse an unsigned 64-bit hexadecimal integer (with or without 0x) from a substring.

Returns
Parsed value.

Definition at line 7905 of file Utils.cpp.

References TextSubstringCopy().

Referenced by _wrap_AsciiHex2Uint64__SWIG_0(), _wrap_AsciiHex2Uint64__SWIG_1(), and _wrap_AsciiHex2Uint64__SWIG_2().

◆ BytifyRate()

std::string cmlabs::utils::BytifyRate ( double val)

Format a byte rate, e.g.

"1.5 KB/s".

Parameters
valBytes per second.
Returns
Human-readable text.

Definition at line 8214 of file Utils.cpp.

References BytifySize().

Referenced by _wrap_BytifyRate(), and cmlabs::MovingAverage::UnitTest().

◆ BytifyRates()

std::string cmlabs::utils::BytifyRates ( double val1,
double val2 )

Format two byte rates as "x / y" with matching units.

Parameters
val1,val2Bytes per second.
Returns
Human-readable text.

Definition at line 8226 of file Utils.cpp.

References BytifySizes().

Referenced by _wrap_BytifyRates().

◆ BytifySize()

std::string cmlabs::utils::BytifySize ( double val)

Format a byte count with binary units, e.g.

1536 → "1.5 KB".

Parameters
valByte count.
Returns
Human-readable text.
Note
Units are binary (1 KB = 1024 B) with two decimals, and the unit switches at 512 of the current unit (so 600000 renders as "585.94 KB", not "0.57 MB"). Intended for logs/UI — not parseable back losslessly.

Definition at line 8131 of file Utils.cpp.

Referenced by _wrap_BytifySize(), BytifyRate(), cmlabs::JSONM::getInfoString(), cmlabs::JSONMEntry::getInfoString(), cmlabs::MessagePlayer::initWrite(), cmlabs::TemporalMemory::logUsage(), cmlabs::MessagePlayer::printAllString(), and cmlabs::TemporalMemory::UnitTest().

◆ BytifySizes()

std::string cmlabs::utils::BytifySizes ( double val1,
double val2 )

Format two byte counts as "x / y" with matching units.

Parameters
val1,val2Byte counts.
Returns
Human-readable text.

Definition at line 8168 of file Utils.cpp.

References strcpyavail().

Referenced by _wrap_BytifySizes(), and BytifyRates().

◆ CalcTimeout()

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

◆ ChangeAFileAttr()

bool cmlabs::utils::ChangeAFileAttr ( const char * filename,
bool read,
bool write )

Change read/write permission attributes of a file.

Parameters
filenamePath.
readAllow reading.
writeAllow writing.
Returns
true on success.

Definition at line 7344 of file Utils.cpp.

Referenced by _wrap_ChangeAFileAttr(), and DeleteADir().

◆ CompareFloats()

int8 cmlabs::utils::CompareFloats ( float64 a,
float64 b )

Compare two doubles with epsilon tolerance.

Parameters
a,bValues.
Returns
-1 when a<b, 0 when approximately equal, 1 when a>b.

Definition at line 7167 of file Utils.cpp.

Referenced by _wrap_CompareFloats().

◆ CopyAFile() [1/2]

bool cmlabs::utils::CopyAFile ( const char * olddir,
const char * oldfilename,
const char * newdir,
const char * newfilename,
bool force = false )

Copy a file between directories; see CopyAFile().

Returns
true on success.

Definition at line 7445 of file Utils.cpp.

References CopyAFile().

◆ CopyAFile() [2/2]

bool cmlabs::utils::CopyAFile ( const char * oldfilename,
const char * newfilename,
bool force = false )

Copy a file.

Parameters
oldfilenameSource.
newfilenameDestination.
forceOverwrite an existing destination.
Returns
true on success.

Definition at line 7412 of file Utils.cpp.

References DeleteAFile(), cmlabs::utils::FileDetails::doesExist, FALSE, GetFileDetails(), cmlabs::utils::FileDetails::isDirectory, ReadAFile(), TRUE, and WriteAFile().

Referenced by _wrap_CopyAFile__SWIG_0(), _wrap_CopyAFile__SWIG_1(), _wrap_CopyAFile__SWIG_2(), _wrap_CopyAFile__SWIG_3(), CopyAFile(), and MoveAFile().

◆ CopyRegistryTree()

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

Recursively copy a registry subtree.

Parameters
entrySource subtree.
newNameDestination name.
Returns
true on success.

Definition at line 8500 of file Utils.cpp.

◆ CRC32()

int cmlabs::utils::CRC32 ( const char * addr,
uint32 length,
int32 crc = 0 )

Compute (or continue) a CRC-32 checksum.

Parameters
addrData.
lengthBytes.
crcPrevious CRC to continue from (0 to start fresh).
Returns
Updated CRC value.
Note
Bitwise implementation using the reflected ZIP/IEEE-802.3 polynomial, but without the standard 0xFFFFFFFF pre-conditioning and final XOR, so the value differs from zlib's crc32()/PKZIP for the same input. Use it only for CMSDK-internal integrity checks where both sides call this function. To checksum streamed data, feed each chunk in sequence, passing the previous return value as crc.

Definition at line 7186 of file Utils.cpp.

References poly.

Referenced by _wrap_CRC32__SWIG_0(), and _wrap_CRC32__SWIG_1().

◆ CreateADir()

bool cmlabs::utils::CreateADir ( const char * dirname)

Create a directory (parents included where supported).

Parameters
dirnamePath.
Returns
true on success or when it already exists.

Definition at line 7460 of file Utils.cpp.

References cmlabs::utils::FileDetails::doesExist, GetFileDetails(), and cmlabs::utils::FileDetails::isDirectory.

Referenced by _wrap_CreateADir(), and cmlabs::MessagePlayer::initWrite().

◆ Dec2Char()

unsigned char cmlabs::utils::Dec2Char ( const char * str)

Parse up to three decimal digits into a byte.

Parameters
strDecimal text.
Returns
Byte value.

Definition at line 7159 of file Utils.cpp.

Referenced by _wrap_Dec2Char().

◆ DecodeJSON()

std::string cmlabs::utils::DecodeJSON ( std::string str)

Unescape a JSON string value (\" \\ \n \t \uXXXX etc.).

Parameters
strEscaped text (without surrounding quotes).
Returns
Decoded text.
Warning
\uXXXX sequences are decoded by truncating the code point to a single 8-bit char, so only U+0000..U+00FF survive; anything higher is mangled (no UTF-8 expansion, no surrogate-pair handling). A malformed trailing escape (e.g. a \u with fewer than four digits at end of input) advances past the string end — only feed well-formed JSON string content.

Definition at line 7964 of file Utils.cpp.

Referenced by _wrap_DecodeJSON().

◆ DeleteADir()

bool cmlabs::utils::DeleteADir ( const char * dirname,
bool force )

Delete a directory (recursively when force).

Parameters
dirnamePath.
forceDelete non-empty directories.
Returns
true on success.

Definition at line 7486 of file Utils.cpp.

References ChangeAFileAttr(), DeleteFilesInADir(), cmlabs::utils::FileDetails::doesExist, GetFileDetails(), and cmlabs::utils::FileDetails::isDirectory.

Referenced by _wrap_DeleteADir(), DeleteAFile(), DeleteAFile(), and DeleteFilesInADir().

◆ DeleteAFile() [1/2]

bool cmlabs::utils::DeleteAFile ( const char * dir,
const char * filename,
bool force )

Delete dir/filename; see DeleteAFile().

Returns
true on success.

Definition at line 7329 of file Utils.cpp.

References DeleteADir().

◆ DeleteAFile() [2/2]

bool cmlabs::utils::DeleteAFile ( const char * filename,
bool force )

Delete a file.

Parameters
filenamePath.
forceClear read-only attribute first when needed.
Returns
true on success.

Definition at line 7340 of file Utils.cpp.

References DeleteADir().

Referenced by _wrap_DeleteAFile__SWIG_0(), _wrap_DeleteAFile__SWIG_1(), CopyAFile(), cmlabs::Internal_StatsLog(), and MoveAFile().

◆ DeleteCommandline()

bool cmlabs::utils::DeleteCommandline ( char ** argv,
int argc )

Free an argv array produced by SplitCommandline().

Parameters
argvArray.
argcCount.
Returns
true on success.

Definition at line 6684 of file Utils.cpp.

Referenced by _wrap_DeleteCommandline(), NewProcess(), and NewProcessEx().

◆ DeleteFilesInADir()

bool cmlabs::utils::DeleteFilesInADir ( const char * dirname,
bool force )

Delete all files inside a directory, leaving the directory itself.

Parameters
dirnamePath.
forceClear read-only attributes as needed.
Returns
true on success.

Definition at line 7553 of file Utils.cpp.

References DeleteADir(), GetFileList(), and MAXFILENAMELEN.

Referenced by _wrap_DeleteFilesInADir(), and DeleteADir().

◆ DeleteRegistryEntry()

bool cmlabs::utils::DeleteRegistryEntry ( const char * key,
const char * entry )

Delete a single value from a key.

Returns
true on success.

◆ DeleteRegistryKey()

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

Delete a (leaf) registry key.

Returns
true on success.

Definition at line 8497 of file Utils.cpp.

◆ DeleteRegistryTree() [1/2]

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

Definition at line 8498 of file Utils.cpp.

◆ DeleteRegistryTree() [2/2]

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

Recursively delete a key and all subkeys.

Parameters
rootRoot key path.
keySubtree to delete.
Returns
true on success.

◆ DoesADirExist()

bool cmlabs::utils::DoesADirExist ( const char * dirname)

Test whether a directory exists.

Parameters
dirnamePath.
Returns
true when present and a directory.

Definition at line 7761 of file Utils.cpp.

References cmlabs::utils::FileDetails::doesExist, GetFileDetails(), and cmlabs::utils::FileDetails::isDirectory.

Referenced by _wrap_DoesADirExist().

◆ DoesAFileExist()

bool cmlabs::utils::DoesAFileExist ( const char * filename)

Test whether a regular file exists.

Parameters
filenamePath.
Returns
true when present.

Definition at line 7766 of file Utils.cpp.

References cmlabs::utils::FileDetails::doesExist, GetFileDetails(), and cmlabs::utils::FileDetails::isDirectory.

Referenced by _wrap_DoesAFileExist(), cmlabs::Internal_BitmapPoster(), and cmlabs::Internal_StatsLog().

◆ DrumBeatCallback()

◆ EncodeJSON()

std::string cmlabs::utils::EncodeJSON ( std::string str)

Escape text for embedding as a JSON string value.

Parameters
strRaw text.
Returns
Escaped text (without surrounding quotes).
Note
Bytes are escaped individually; multi-byte UTF-8 sequences pass through unmodified (which is valid JSON). The caller adds the surrounding double quotes.

Definition at line 8003 of file Utils.cpp.

Referenced by _wrap_EncodeJSON(), TextJoinJSON(), and cmlabs::LogEntry::toJSON().

◆ GetCommandLine()

std::string cmlabs::utils::GetCommandLine ( )

Get the full original command line as one string.

Returns
Command line text.

Definition at line 4653 of file Utils.cpp.

References cmlabs::utils::CommandLineInfo::CommandLineInfoSingleton.

Referenced by _wrap_GetCommandLine().

◆ GetCommandLineArg() [1/2]

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

Get the value of a 'key=value' command line argument.

Parameters
keyArgument name (case as given).
Returns
Value, or empty string when absent.
Note
Inserts an empty entry into the map on miss; use HasCommandLineArg() to test without side effects.

Definition at line 4711 of file Utils.cpp.

References cmlabs::utils::CommandLineInfo::CommandLineInfoSingleton.

◆ GetCommandLineArg() [2/2]

std::string cmlabs::utils::GetCommandLineArg ( uint16 n)

Get the n-th positional command line item.

Parameters
nZero-based index.
Returns
Item text, or empty when out of range.

Definition at line 4705 of file Utils.cpp.

References cmlabs::utils::CommandLineInfo::CommandLineInfoSingleton.

Referenced by _wrap_GetCommandLineArg__SWIG_0(), and _wrap_GetCommandLineArg__SWIG_1().

◆ GetCommandLineArgCount()

uint32 cmlabs::utils::GetCommandLineArgCount ( )

Number of positional command line items (excluding the executable).

Returns
Count.

Definition at line 4699 of file Utils.cpp.

References cmlabs::utils::CommandLineInfo::CommandLineInfoSingleton.

Referenced by _wrap_GetCommandLineArgCount().

◆ GetCommandLineExecutable()

std::string cmlabs::utils::GetCommandLineExecutable ( )

Get the full executable path as invoked.

Returns
Path + filename.

Definition at line 4676 of file Utils.cpp.

References cmlabs::utils::CommandLineInfo::CommandLineInfoSingleton.

Referenced by _wrap_GetCommandLineExecutable().

◆ GetCommandLineExecutableOnly()

std::string cmlabs::utils::GetCommandLineExecutableOnly ( )

Get just the executable filename without path.

Returns
Filename.

Definition at line 4682 of file Utils.cpp.

References cmlabs::utils::CommandLineInfo::CommandLineInfoSingleton.

Referenced by _wrap_GetCommandLineExecutableOnly().

◆ GetCommandLinePath()

std::string cmlabs::utils::GetCommandLinePath ( )

Get the directory portion of the executable path.

Returns
Path (platform separators).

Definition at line 4659 of file Utils.cpp.

References cmlabs::utils::CommandLineInfo::CommandLineInfoSingleton.

Referenced by _wrap_GetCommandLinePath(), cmlabs::PsySpace::getCrankAPI(), and cmlabs::utils::Library::load().

◆ GetComputerName()

const char * cmlabs::utils::GetComputerName ( )

Get this machine's hostname.

Returns
Pointer to an internal static buffer; do not free.

Definition at line 4917 of file Utils.cpp.

References GetComputerName(), OSLocalHostName, RunOSCommand(), and strcpyavail().

Referenced by _wrap_GetComputerName(), and GetComputerName().

◆ GetCPUArchitecture()

uint16 cmlabs::utils::GetCPUArchitecture ( )

CPU architecture id.

Returns
One of OSCPU_X86 / OSCPU_AMD64 / OSCPU_IA64 / OSCPU_UNKNOWN.

Definition at line 5055 of file Utils.cpp.

References OSCPU_AMD64, OSCPU_IA64, OSCPU_UNKNOWN, and OSCPU_X86.

Referenced by _wrap_GetCPUArchitecture(), and GetSystemOSName().

◆ GetCPUCount()

uint16 cmlabs::utils::GetCPUCount ( )

Number of logical CPU cores.

Returns
Core count.

Definition at line 5036 of file Utils.cpp.

Referenced by _wrap_GetCPUCount().

◆ GetCPUSpeed()

uint64 cmlabs::utils::GetCPUSpeed ( )

Nominal CPU clock speed.

Returns
Hz (approximate; read from OS info).

Definition at line 5092 of file Utils.cpp.

Referenced by _wrap_GetCPUSpeed().

◆ GetCurrentDir()

std::string cmlabs::utils::GetCurrentDir ( )

Current working directory.

Returns
Absolute path.

Definition at line 7687 of file Utils.cpp.

References GetCurrentDirEx.

Referenced by _wrap_GetCurrentDir().

◆ GetFileBasename()

const char * cmlabs::utils::GetFileBasename ( const char * filename)

Filename portion of a path.

Parameters
filenamePath.
Returns
Pointer into filename after the last separator.

Definition at line 7671 of file Utils.cpp.

Referenced by _wrap_GetFileBasename().

◆ GetFileDetails()

◆ GetFileList()

char * cmlabs::utils::GetFileList ( const char * dirname,
const char * ext,
uint32 & count,
bool fullpath,
uint32 maxNameLen = 256 )

List files in a directory matching an extension.

Parameters
dirnameDirectory.
extExtension filter (NULL/empty = all).
[out]countNumber of names.
fullpathPrepend the directory to each name.
maxNameLenFixed per-name slot size in the returned block.
Returns
Single allocated block of count zero-padded name slots each maxNameLen bytes (caller frees), or NULL.
Note
The result is not an array of pointers: entry i starts at buffer+i*maxNameLen and is a NUL-terminated string within its fixed slot. Names longer than maxNameLen-1 are truncated. Ordering follows the OS directory enumeration (not sorted).
uint32 n = 0;
char* names = utils::GetFileList("./logs", "txt", n, true);
for (uint32 i = 0; i < n; i++)
printf("%s\n", names + i*256); // default maxNameLen = 256
free(names);
char * GetFileList(const char *dirname, const char *ext, uint32 &count, bool fullpath, uint32 maxNameLen=256)
List files in a directory matching an extension.
Definition Utils.cpp:7700

Definition at line 7700 of file Utils.cpp.

References cmlabs::closedir(), cmlabs::dirent::d_name, cmlabs::opendir(), cmlabs::readdir(), strcpyavail(), and TextEndsWith().

Referenced by _wrap_GetFileList__SWIG_0(), _wrap_GetFileList__SWIG_1(), DeleteFilesInADir(), and cmlabs::Internal_BitmapPoster().

◆ GetFilePath()

std::string cmlabs::utils::GetFilePath ( const char * filename)

Directory portion of a path.

Parameters
filenamePath.
Returns
Directory (without the trailing name).

Definition at line 7655 of file Utils.cpp.

Referenced by _wrap_GetFilePath().

◆ GetLastOSErrorMessage()

std::string cmlabs::utils::GetLastOSErrorMessage ( )

Get the last OS error as human-readable text.

Returns
Message string.

Definition at line 5659 of file Utils.cpp.

References StringFormat().

Referenced by _wrap_GetLastOSErrorMessage(), CreateSharedMemorySegment(), MoveAFile(), and OpenSharedMemorySegment().

◆ GetLastOSErrorNumber()

◆ GetLocalHostname()

bool cmlabs::utils::GetLocalHostname ( char * name,
uint32 maxSize )

Local hostname into a caller buffer.

Parameters
[out]nameBuffer.
maxSizeBuffer size.
Returns
true on success.

Definition at line 5915 of file Utils.cpp.

References CHECKNETWORKINIT.

Referenced by _wrap_GetLocalHostname(), GetLocalHostnameString(), and UtilsTest().

◆ GetLocalHostnameString()

std::string cmlabs::utils::GetLocalHostnameString ( )

Local hostname as std::string.

Returns
Hostname.

Definition at line 5903 of file Utils.cpp.

References GetLocalHostname().

Referenced by _wrap_GetLocalHostnameString().

◆ GetLocalInterfaces()

NetworkInterfaces * cmlabs::utils::GetLocalInterfaces ( uint32 & count)

Enumerate local network interfaces with address, MAC and names.

Parameters
[out]countNumber of entries.
Returns
malloc'ed array (caller frees) or NULL.

Definition at line 6171 of file Utils.cpp.

References cmlabs::utils::NetworkInterfaces::address, CHECKNETWORKINIT, cmlabs::FREE, cmlabs::utils::NetworkInterfaces::friendlyName, LOCALHOSTIP, cmlabs::utils::NetworkInterfaces::mac, MALLOC, MAXKEYNAMELEN, cmlabs::utils::NetworkInterfaces::name, and strcpyavail().

Referenced by _wrap_GetLocalInterfaces(), GetLocalIPAddresses(), GetLocalMACAddress(), GetLocalMACAddresses(), and UtilsTest().

◆ GetLocalIPAddress()

bool cmlabs::utils::GetLocalIPAddress ( uint32 & address)

Get the primary local IPv4 address.

Parameters
[out]addressAddress (network byte order).
Returns
true on success.

Definition at line 6029 of file Utils.cpp.

References CHECKNETWORKINIT, GetLocalIPAddresses(), and LOCALHOSTIP.

Referenced by _wrap_GetLocalIPAddress(), cmlabs::SSLConnection::findRemoteAddress(), cmlabs::TCPConnection::findRemoteAddress(), cmlabs::HTTPTestServer::receiveHTTPRequest(), and UtilsTest().

◆ GetLocalIPAddresses()

uint32 * cmlabs::utils::GetLocalIPAddresses ( uint32 & count)

List all local IPv4 addresses.

Parameters
[out]countNumber of entries.
Returns
malloc'ed array (caller frees) or NULL.

Definition at line 6061 of file Utils.cpp.

References cmlabs::utils::NetworkInterfaces::address, CHECKNETWORKINIT, GetLastOSErrorNumber(), GetLocalInterfaces(), and LOCALHOSTIP.

Referenced by _wrap_GetLocalIPAddresses(), GetLocalIPAddress(), IsLocalIPAddress(), and UtilsTest().

◆ GetLocalMACAddress()

bool cmlabs::utils::GetLocalMACAddress ( uint64 & address)

Get the primary local MAC address.

Parameters
[out]address48-bit MAC in the low bytes.
Returns
true on success.

Definition at line 5975 of file Utils.cpp.

References GetLocalInterfaces(), LOCALHOSTIP, and cmlabs::utils::NetworkInterfaces::mac.

Referenced by _wrap_GetLocalMACAddress().

◆ GetLocalMACAddresses()

uint64 * cmlabs::utils::GetLocalMACAddresses ( uint32 & count)

List all local MAC addresses.

Parameters
[out]countNumber of entries.
Returns
malloc'ed array (caller frees) or NULL.

Definition at line 5987 of file Utils.cpp.

References GetLocalInterfaces(), LOCALHOSTIP, and cmlabs::utils::NetworkInterfaces::mac.

Referenced by _wrap_GetLocalMACAddresses().

◆ GetNextAvailableLocalPort()

bool cmlabs::utils::GetNextAvailableLocalPort ( uint16 lastPort,
uint16 & nextPort )

Find the next free TCP port above lastPort.

Parameters
lastPortPort to start after.
[out]nextPortReceives the available port.
Returns
true when one was found.

Definition at line 6317 of file Utils.cpp.

References CHECKNETWORKINIT, closesocket, INVALID_SOCKET, SD_BOTH, SOCKET, and SOCKET_ERROR.

Referenced by _wrap_GetNextAvailableLocalPort().

◆ GetPeakProcessMemoryUsage()

uint64 cmlabs::utils::GetPeakProcessMemoryUsage ( )

Peak resident memory usage of this process.

Returns
Bytes.
  • AIX and Solaris ---------------------------------------— *‍/

Definition at line 4996 of file Utils.cpp.

Referenced by _wrap_GetPeakProcessMemoryUsage().

◆ GetProcessMemoryUsage()

uint64 cmlabs::utils::GetProcessMemoryUsage ( )

Current resident memory usage of this process.

Returns
Bytes.

Definition at line 4964 of file Utils.cpp.

Referenced by _wrap_GetProcessMemoryUsage(), cmlabs::ProcessMemory::addLocalPerformanceStats(), and cmlabs::ProcessMemory::setProcessStatus().

◆ GetSocketError()

bool cmlabs::utils::GetSocketError ( int wsaError,
char * errorString,
uint16 errorStringMaxSize,
bool * isRecoverable )

Translate a socket error code into text and classify it.

Parameters
wsaErrorError number (WSAGetLastError()/errno).
[out]errorStringBuffer for the message.
errorStringMaxSizeBuffer size.
[out]isRecoverableSet true for transient errors (e.g. would-block) where a retry makes sense.
Returns
true when the code was recognized.

Definition at line 5513 of file Utils.cpp.

References strcpyavail(), and WSAEWOULDBLOCK.

Referenced by _wrap_GetSocketError().

◆ GetSystemArchitecture()

const char * cmlabs::utils::GetSystemArchitecture ( )

Architecture name string, e.g.

"x86_64".

Returns
Pointer to an internal static buffer.

Definition at line 5203 of file Utils.cpp.

References OSArchitectureName, and strcpyavail().

Referenced by _wrap_GetSystemArchitecture().

◆ GetSystemMemorySize()

uint64 cmlabs::utils::GetSystemMemorySize ( )

Total physical RAM installed.

Returns
Bytes.

Definition at line 5139 of file Utils.cpp.

Referenced by _wrap_GetSystemMemorySize().

◆ GetSystemMemoryUsage()

bool cmlabs::utils::GetSystemMemoryUsage ( uint64 & totalRAM,
uint64 & freeRAM )

Query total and free physical memory.

Parameters
[out]totalRAMBytes.
[out]freeRAMBytes.
Returns
true on success.

Definition at line 5162 of file Utils.cpp.

Referenced by _wrap_GetSystemMemoryUsage().

◆ GetSystemOSName()

const char * cmlabs::utils::GetSystemOSName ( )

OS name string, e.g.

"Windows", "Linux", "Darwin".

Returns
Pointer to an internal static buffer.

Definition at line 5264 of file Utils.cpp.

References GetCPUArchitecture(), OSCPU_AMD64, OSCPU_IA64, OSCPU_X86, OSName, and strcpyavail().

Referenced by _wrap_GetSystemOSName().

◆ GetSystemOSVersion()

bool cmlabs::utils::GetSystemOSVersion ( uint16 & major,
uint16 & minor,
uint16 & build,
char * text,
uint16 textSize )

Detailed OS version.

Parameters
[out]major,minor,buildVersion numbers.
[out]textBuffer receiving a descriptive string.
textSizeSize of text.
Returns
true on success.

Definition at line 5292 of file Utils.cpp.

References strcpyavail().

Referenced by _wrap_GetSystemOSVersion().

◆ GetTime()

uint64 cmlabs::utils::GetTime ( )

Definition at line 448 of file Utils.cpp.

◆ HasCommandLineArg()

bool cmlabs::utils::HasCommandLineArg ( const char * key,
std::string & value )

Test for a 'key=value' argument without mutating the argument map.

Parameters
keyArgument name.
[out]valueReceives the value when present.
Returns
true if the key was given on the command line.

Definition at line 4717 of file Utils.cpp.

References cmlabs::utils::CommandLineInfo::CommandLineInfoSingleton.

Referenced by _wrap_HasCommandLineArg().

◆ Hex2Char()

unsigned char cmlabs::utils::Hex2Char ( const char * str)

Parse two hex digits into a byte.

Parameters
strPointer to at least two hex characters.
Returns
Byte value.

Definition at line 7151 of file Utils.cpp.

Referenced by _wrap_Hex2Char().

◆ hton64()

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

Definition at line 2456 of file Utils.cpp.

References ntoh64().

◆ Int2Ascii()

char * cmlabs::utils::Int2Ascii ( int64 value,
char * result,
uint16 size,
uint8 base )

Render a signed integer as text in an arbitrary base.

Parameters
valueNumber.
resultDestination buffer.
sizeBuffer capacity.
baseRadix 2–36.
Returns
result, or NULL when it does not fit.

Definition at line 5443 of file Utils.cpp.

Referenced by _wrap_Int2Ascii().

◆ IsLocalIPAddress() [1/2]

bool cmlabs::utils::IsLocalIPAddress ( const char * addr)

Test whether a textual address refers to this machine (loopback or a local interface).

Parameters
addrHostname or dotted quad.
Returns
true when local.

Definition at line 6002 of file Utils.cpp.

References IsLocalIPAddress(), and LookupIPAddress().

Referenced by _wrap_IsLocalIPAddress__SWIG_0(), _wrap_IsLocalIPAddress__SWIG_1(), and IsLocalIPAddress().

◆ IsLocalIPAddress() [2/2]

bool cmlabs::utils::IsLocalIPAddress ( uint32 & address)

Test whether a numeric IPv4 address is local.

Parameters
addressAddress (network byte order).
Returns
true when local.

Definition at line 6009 of file Utils.cpp.

References CHECKNETWORKINIT, and GetLocalIPAddresses().

◆ IsTextNumeric()

bool cmlabs::utils::IsTextNumeric ( const char * ascii,
uint32 start = 0,
uint32 end = 0 )

Test whether a (sub)string is a valid number.

Parameters
asciiText.
startFirst index.
endOne past last index (0 = NUL).
Returns
true when numeric.

Definition at line 7857 of file Utils.cpp.

Referenced by _wrap_IsTextNumeric__SWIG_0(), _wrap_IsTextNumeric__SWIG_1(), _wrap_IsTextNumeric__SWIG_2(), cmlabs::RESTParser::parseRequest(), cmlabs::RESTParser::setParameterValue(), and cmlabs::RESTParser::setParameterValue().

◆ LookupHostname()

bool cmlabs::utils::LookupHostname ( uint32 address,
char * name,
uint32 maxSize )

Reverse-resolve an IPv4 address to a hostname.

Parameters
addressAddress (network byte order).
[out]nameBuffer.
maxSizeBuffer size.
Returns
true on success.

Definition at line 5847 of file Utils.cpp.

References CHECKNETWORKINIT, and strcpyavail().

Referenced by _wrap_LookupHostname().

◆ LookupIPAddress()

bool cmlabs::utils::LookupIPAddress ( const char * name,
uint32 & address )

Resolve a hostname to an IPv4 address.

Parameters
nameHostname or dotted quad.
[out]addressAddress in network byte order.
Returns
true on success.

Definition at line 5768 of file Utils.cpp.

References CHECKNETWORKINIT.

Referenced by _wrap_LookupIPAddress(), cmlabs::SSLConnection::connect(), cmlabs::TCPConnection::connect(), cmlabs::SSLConnection::delayedConnect(), cmlabs::TCPConnection::delayedConnect(), IsLocalIPAddress(), cmlabs::PsyAPI::queryCatalog(), cmlabs::PsyAPI::queryCatalog(), and cmlabs::PsyAPI::queryRemoteCatalog().

◆ MoveAFile() [1/2]

bool cmlabs::utils::MoveAFile ( const char * olddir,
const char * oldfilename,
const char * newdir,
const char * newfilename,
bool force = false )

Move a file between directories; see MoveAFile().

Returns
true on success.

Definition at line 7397 of file Utils.cpp.

References MoveAFile().

◆ MoveAFile() [2/2]

bool cmlabs::utils::MoveAFile ( const char * oldfilename,
const char * newfilename,
bool force = false )

Move/rename a file.

Parameters
oldfilenameSource.
newfilenameDestination.
forceOverwrite an existing destination.
Returns
true on success.

Definition at line 7364 of file Utils.cpp.

References CopyAFile(), DeleteAFile(), cmlabs::utils::FileDetails::doesExist, GetFileDetails(), GetLastOSErrorMessage(), LOG_SYSTEM, and LogPrint.

Referenced by _wrap_MoveAFile__SWIG_0(), _wrap_MoveAFile__SWIG_1(), _wrap_MoveAFile__SWIG_2(), _wrap_MoveAFile__SWIG_3(), cmlabs::MessagePlayer::initWrite(), cmlabs::Internal_StatsLog(), and MoveAFile().

◆ OpenLibrary()

Library * cmlabs::utils::OpenLibrary ( const char * libName)

Load a library by name, applying platform filename conventions.

Parameters
libNameBase name.
Returns
Heap-allocated Library (caller owns) or NULL on failure.

Definition at line 4899 of file Utils.cpp.

References cmlabs::utils::Library::load().

Referenced by _wrap_OpenLibrary().

◆ RandomInt()

int64 cmlabs::utils::RandomInt ( int64 from = 0,
int64 to = 100 )

◆ RandomValue() [1/4]

double cmlabs::utils::RandomValue ( )

Uniform random double in [0,1).

Returns
Random value.
Note
Combines three rand() calls to obtain far more resolution than a single RAND_MAX (important on Windows where RAND_MAX is only 32767). Uses the global C rand() state: results interleave across threads and the sequence is only reproducible in single-threaded use after SeedRandomValues() with a fixed seed.

Definition at line 8085 of file Utils.cpp.

Referenced by _wrap_RandomValue__SWIG_0(), _wrap_RandomValue__SWIG_1(), _wrap_RandomValue__SWIG_2(), _wrap_RandomValue__SWIG_3(), cmlabs::RandomPathGenerator::generateNextPoint(), cmlabs::HTTPServerTest(), cmlabs::PsySpace::PsySpace(), RandomInt(), RandomValue(), RandomValue(), RandomValue(), and cmlabs::TemporalMemory::UnitTest().

◆ RandomValue() [2/4]

double cmlabs::utils::RandomValue ( double from,
double to )

Uniform random double in [from,to).

Returns
Random value.

Definition at line 8102 of file Utils.cpp.

References RandomValue().

◆ RandomValue() [3/4]

double cmlabs::utils::RandomValue ( double from,
double to,
double interval )

Uniform random double in [from,to) quantized to multiples of interval.

Returns
Random value.

Definition at line 8110 of file Utils.cpp.

References RandomValue().

◆ RandomValue() [4/4]

double cmlabs::utils::RandomValue ( double to)

Uniform random double in [0,to).

Parameters
toUpper bound.
Returns
Random value.

Definition at line 8097 of file Utils.cpp.

References RandomValue().

◆ ReadAFile() [1/2]

char * cmlabs::utils::ReadAFile ( const char * dir,
const char * filename,
uint32 & length,
bool binary = false )

Read dir/filename into a new buffer; see ReadAFile().

Returns
Allocated buffer or NULL.

Definition at line 7214 of file Utils.cpp.

References ReadAFile().

◆ ReadAFile() [2/2]

char * cmlabs::utils::ReadAFile ( const char * filename,
uint32 & length,
bool binary = false )

Read an entire file into a new buffer.

Parameters
filenamePath.
[out]lengthBytes read.
binaryOpen in binary mode (no newline translation on Windows).
Returns
new[]-allocated, NUL-terminated buffer (caller deletes) or NULL.
Note
The buffer is allocated one byte larger than the file and always NUL-terminated, so text reads can be used directly as C strings. In text mode on Windows, length is the byte count after CRLF translation and may be smaller than the on-disk size. Empty or unreadable files return NULL (with length = 0) — an empty file is not distinguishable from a missing one; call DoesAFileExist() first when that matters.
uint32 len = 0;
char* xml = utils::ReadAFile("config.xml", len);
if (xml) {
parse(xml, len);
delete [] xml; // caller owns the buffer
}
char * ReadAFile(const char *filename, uint32 &length, bool binary=false)
Read an entire file into a new buffer.
Definition Utils.cpp:7225

Definition at line 7225 of file Utils.cpp.

References LogPrint.

Referenced by _wrap_ReadAFile__SWIG_0(), _wrap_ReadAFile__SWIG_1(), _wrap_ReadAFile__SWIG_2(), _wrap_ReadAFile__SWIG_3(), CopyAFile(), cmlabs::HTTPReply::createFromFile(), cmlabs::MessagePlayer::exportToCSV(), cmlabs::MessagePlayer::initRead(), cmlabs::MessagePlayer::printAllString(), ReadAFile(), ReadAFileString(), cmlabs::Bitmap::readFromFile(), cmlabs::BitmapUpdate::readFromFile(), cmlabs::BitmapUpdate::readFromFileDiff(), cmlabs::BitmapUpdate::readFromFileRLE(), cmlabs::BitmapUpdate::readFromFileRLEDiff(), cmlabs::MessagePlayer::readMetadata(), and cmlabs::MessagePlayer::waitForNextMessage().

◆ ReadAFileString()

std::string cmlabs::utils::ReadAFileString ( std::string filename)

Read an entire file into a std::string.

Parameters
filenamePath.
Returns
File contents, or empty string when unreadable (indistinguishable from an empty file).
Note
Opens in text mode; on Windows CRLF pairs are collapsed to \n. Binary data containing NUL bytes is not preserved reliably — use ReadAFile() with binary=true instead.

Definition at line 7204 of file Utils.cpp.

References ReadAFile().

Referenced by _wrap_ReadAFileString(), cmlabs::HTTPReply::createFromFile(), and cmlabs::ut_readChildResult().

◆ ReadRegistryDWORD() [1/2]

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

Definition at line 8491 of file Utils.cpp.

◆ ReadRegistryDWORD() [2/2]

uint32 cmlabs::utils::ReadRegistryDWORD ( const char * key,
const char * entry )

Read a 32-bit registry value.

Parameters
keyFull key path.
entryValue name.
Returns
Value, or ERROR32 on failure.

◆ ReadRegistryQWORD() [1/2]

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

Definition at line 8492 of file Utils.cpp.

◆ ReadRegistryQWORD() [2/2]

uint64 cmlabs::utils::ReadRegistryQWORD ( const char * key,
const char * entry )

Read a 64-bit registry value.

Parameters
keyFull key path.
entryValue name.
Returns
Value, or ERROR64 on failure.

◆ ReadRegistryString() [1/2]

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

Definition at line 8493 of file Utils.cpp.

◆ ReadRegistryString() [2/2]

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

Read a string registry value.

Parameters
keyFull key path.
entryValue name.
Returns
Value, or empty string on failure.

◆ RenameRegistryTree()

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

Definition at line 8502 of file Utils.cpp.

◆ SeedRandomValues()

bool cmlabs::utils::SeedRandomValues ( uint32 seedvalue = 0)

Seed the pseudo-random generator.

Parameters
seedvalueSeed; 0 = derive from current time.
Returns
true on success.
Note
Wraps the C library srand(), i.e. one global generator shared by the whole process — seeding affects every user of rand()/RandomValue(). Seed once at startup; reseeding repeatedly (e.g. per call) destroys the distribution. Not suitable for cryptographic purposes.

Definition at line 8079 of file Utils.cpp.

References cmlabs::GetTimeNow().

Referenced by _wrap_SeedRandomValues__SWIG_0(), _wrap_SeedRandomValues__SWIG_1(), and cmlabs::HTTPServerTest().

◆ SetCommandLine()

bool cmlabs::utils::SetCommandLine ( int argc,
char * argv[] )

Parse and store the process command line for later retrieval by the Get/HasCommandLine* functions.

Parameters
argcArgument count from main().
argvArgument vector from main().
Returns
true on success.
Note
Call once early in main().

Definition at line 4612 of file Utils.cpp.

References cmlabs::utils::CommandLineInfo::CommandLineInfoSingleton.

Referenced by _wrap_SetCommandLine().

◆ SetSocketBlockingMode()

bool cmlabs::utils::SetSocketBlockingMode ( SOCKET s)

Put a socket into blocking mode.

Parameters
sSocket.
Returns
true on success.

Definition at line 5756 of file Utils.cpp.

References SOCKET.

Referenced by _wrap_SetSocketBlockingMode().

◆ SetSocketNonBlockingMode()

◆ SplitCommandline()

char ** cmlabs::utils::SplitCommandline ( const char * cmdline,
int & argc )

Split a command line into a malloc'ed argv array.

Parameters
cmdlineRaw command line.
[out]argcArgument count.
Returns
argv array; free with DeleteCommandline().

Definition at line 6644 of file Utils.cpp.

References TextCommandlineSplit().

Referenced by _wrap_SplitCommandline(), NewProcess(), and NewProcessEx().

◆ SplitCommandlineW()

wchar_t ** cmlabs::utils::SplitCommandlineW ( const char * cmdline,
int & argc )

Wide-character variant of SplitCommandline() (for Windows APIs).

Parameters
cmdlineRaw command line.
[out]argcArgument count.
Returns
Wide argv array.

Definition at line 6664 of file Utils.cpp.

References TextCommandlineSplit().

Referenced by _wrap_SplitCommandlineW().

◆ StringFormat() [1/2]

std::string cmlabs::utils::StringFormat ( const char * format,
... )

printf into a std::string.

Parameters
formatprintf format string followed by varargs.
Returns
Formatted text. Formats into a heap buffer sized to fit, so arbitrarily long results are safe (unlike fixed-size snprintf patterns). An empty format string, or a formatting failure, yields an empty string.
Warning
The usual varargs rules apply: pass c_str() for std::string arguments and make integer argument widths match the format specifier (use lld/llu style specifiers for 64-bit values).
std::string s = StringFormat("%u items in %.2f s", n, secs);
std::string StringFormat(const char *format,...)
printf into a std::string.
Definition Utils.cpp:7033

Definition at line 7033 of file Utils.cpp.

References StringFormatVA().

Referenced by _wrap_StringFormat__SWIG_0__varargs__(), _wrap_StringFormat__SWIG_1__varargs__(), cmlabs::RequestGateway::addAuthUser(), cmlabs::RESTRequest::addToErrorString(), AddToJSONRoot(), cmlabs::RequestGateway::addToRequestQueue(), cmlabs::RequestGateway::callInternalAPI(), cmlabs::MemoryRequestConnection::connect(), cmlabs::PostSpec::contentFromXML(), cmlabs::ComponentMemory::create(), cmlabs::MasterMemory::create(), cmlabs::ProcessMemory::create(), cmlabs::TemporalMemory::create(), cmlabs::HTTPReply::createFromFile(), cmlabs::HTTPRequest::createMultipartRequest(), cmlabs::HTTPRequest::createRequest(), cmlabs::HTTPRequest::createRequest(), cmlabs::HTTPReply::createWebsocketHTTPReply(), cmlabs::HTTPRequest::createWebsocketRequest(), cmlabs::MessagePlayer::exportToCSV(), cmlabs::RESTParser::extractArrayParameters(), cmlabs::RESTParser::extractArrayParameters(), cmlabs::RESTParser::extractParameters(), cmlabs::RESTParser::extractParameters(), cmlabs::DataMessage::getArraySize(), cmlabs::DataMessage::getAsFloatArray(), cmlabs::DataMessage::getAsFloatMap(), cmlabs::DataMessage::getAsIntArray(), cmlabs::DataMessage::getAsIntMap(), cmlabs::DataMessage::getAsString(), cmlabs::DataMessage::getAsString(), cmlabs::DataMessage::getAsString(), cmlabs::DataMessage::getAsStringArray(), cmlabs::DataMessage::getAsStringMap(), cmlabs::DataMessage::getAttachedMessageArray(), cmlabs::DataMessage::getAttachedMessageCopy(), cmlabs::DataMessage::getAttachedMessageCopy(), cmlabs::DataMessage::getAttachedMessageMap(), cmlabs::DataMessage::getContentSize(), cmlabs::DataMessage::getContentSize(), cmlabs::DataMessage::getContentType(), cmlabs::DataMessage::getContentType(), cmlabs::DataMessage::GetCSVHeader(), cmlabs::DataMessage::getData(), cmlabs::DataMessage::getData(), cmlabs::DataMessage::getDataCopy(), cmlabs::DataMessage::getDataCopy(), cmlabs::DataMessage::getDouble(), cmlabs::DataMessage::getDouble(), cmlabs::DataMessage::getDouble(), cmlabs::DataMessage::getDouble(), cmlabs::DataMessage::getDoubleArray(), cmlabs::DataMessage::getDoubleMap(), cmlabs::DataMessage::getFloat(), cmlabs::DataMessage::getFloat(), cmlabs::DataMessage::getFloat(), cmlabs::DataMessage::getFloat(), cmlabs::DataMessage::getFloatArray(), cmlabs::DataMessage::getFloatMap(), cmlabs::JSONM::getInfoString(), cmlabs::JSONMEntry::getInfoString(), cmlabs::DataMessage::getInt(), cmlabs::DataMessage::getInt(), cmlabs::DataMessage::getInt(), cmlabs::DataMessage::getInt(), cmlabs::DataMessage::getIntArray(), cmlabs::DataMessage::getIntMap(), cmlabs::DataMessage::getKeyType(), GetLastOSErrorMessage(), cmlabs::DataMessage::getMapSize(), cmlabs::MovingAverage::getPerfJSON(), cmlabs::MovingAverage::getPerfXML(), GetProcAndOSCPUUsage(), cmlabs::RESTRequest::getStorageMessageCopy(), cmlabs::DataMessage::getString(), cmlabs::DataMessage::getString(), cmlabs::DataMessage::getString(), cmlabs::DataMessage::getString(), cmlabs::DataMessage::getStringArray(), cmlabs::DataMessage::getStringMap(), cmlabs::DataMessage::getTime(), cmlabs::DataMessage::getTime(), cmlabs::DataMessage::getTimeArray(), cmlabs::DataMessage::getTimeMap(), cmlabs::DataMessage::getUserEntriesAsJSON(), cmlabs::DataMessage::getUserEntriesAsString(), cmlabs::MemoryRequestServer::init(), cmlabs::RESTParser::init(), cmlabs::MessagePlayer::initRead(), cmlabs::MessagePlayer::initWrite(), cmlabs::Internal_MessageToggler(), cmlabs::Internal_RetrieveTest(), cmlabs::Internal_StatsLog(), cmlabs::DataMessage::isArrayContent(), cmlabs::DataMessage::isMapContent(), cmlabs::utils::Library::load(), cmlabs::PsyAPI::logPrint(), cmlabs::LogSystem::LogSystemPrint(), cmlabs::TemporalMemory::logUsage(), cmlabs::MemoryRequestConnection::makeRequest(), cmlabs::ComponentMemory::open(), cmlabs::DataMapsMemory::open(), cmlabs::MasterMemory::open(), cmlabs::ProcessMemory::open(), cmlabs::TemporalMemory::open(), cmlabs::RESTParser::parseParamSet(), cmlabs::RESTParser::parseRequest(), cmlabs::RESTParser::parseRequest(), cmlabs::RESTParser::parseRequest(), cmlabs::utils::Library::patchLibraryFilename(), cmlabs::Box::print(), cmlabs::Line::print(), cmlabs::ObsDimension::print(), cmlabs::ObsFloat::print(), cmlabs::ObsInteger::print(), cmlabs::ObsLocation::print(), cmlabs::ObsString::print(), cmlabs::ObsTime::print(), cmlabs::Point::print(), cmlabs::PointFloat::print(), cmlabs::PolyLine::print(), cmlabs::Size::print(), cmlabs::Vector2D::print(), cmlabs::Vector3D::print(), cmlabs::GenericMemoryMap< T, ID >::PrintAllEntries(), cmlabs::GenericMemoryMap< T, ID >::PrintAllEntriesHTML(), cmlabs::MessagePlayer::printAllString(), PrintBitFieldString(), cmlabs::ComponentMemory::printFriendly(), cmlabs::HTTPRequest::processHeader(), cmlabs::PsySpace::PsySpace(), cmlabs::RequestGateway::receiveHTTPRequest(), cmlabs::WebsocketTestServer::receiveWebsocketData(), RenameConsoleWindow(), cmlabs::RequestGateway::replyToClient(), cmlabs::MemoryRequestConnection::replyToRequest(), cmlabs::RequestExecutor::RequestExecutor(), cmlabs::TestWebRequestClient::run(), cmlabs::TestWebSocketRequestClient::run(), RunOSCommand(), cmlabs::DataMessage::setAttachedMessage(), cmlabs::DataMessage::setAttachedMessage(), cmlabs::HTTPRequest::setBasicAuthorization(), cmlabs::RESTRequest::setBinary(), cmlabs::DataMessage::setData(), cmlabs::DataMessage::setData(), cmlabs::DataMessage::setDouble(), cmlabs::DataMessage::setDouble(), cmlabs::RESTRequest::setFilter(), cmlabs::RESTRequest::setFilter(), cmlabs::DataMessage::setFloat(), cmlabs::DataMessage::setFloat(), cmlabs::DataMessage::setInt(), cmlabs::DataMessage::setInt(), cmlabs::RESTParser::setParameterValue(), cmlabs::RESTParser::setParameterValue(), cmlabs::DataMessage::setString(), cmlabs::DataMessage::setString(), cmlabs::DataMessage::setTime(), cmlabs::DataMessage::setTime(), TextIndent(), cmlabs::DataMessage::toCSV(), cmlabs::CallLogEntry::toJSON(), cmlabs::DataMessage::toJSON(), cmlabs::DataMessageHeader::toJSON(), cmlabs::GenericObservation< T >::toJSON(), cmlabs::JSONMEntry::toJSON(), cmlabs::LogEntry::toJSON(), cmlabs::ObsDimension::toJSON(), cmlabs::ObsFloat::toJSON(), cmlabs::ObsInteger::toJSON(), cmlabs::ObsLocation::toJSON(), cmlabs::ObsString::toJSON(), cmlabs::ObsTime::toJSON(), cmlabs::RequestQueue::toJSON(), cmlabs::Color::toRGBString(), cmlabs::GenericMemoryMap< T, ID >::ToXML(), cmlabs::AveragePerfStats::toXML(), cmlabs::ComponentInfoStruct::toXML(), cmlabs::ComponentMemory::toXML(), cmlabs::ComponentStats::toXML(), cmlabs::ContextMapEntry::toXML(), cmlabs::CrankMapEntry::toXML(), cmlabs::DataMapsMemory::toXML(), cmlabs::DataMessage::toXML(), cmlabs::DataMessageHeader::toXML(), cmlabs::FilterSpec::toXML(), cmlabs::LogEntry::toXML(), cmlabs::PostSpec::toXML(), cmlabs::ProcessInfoStruct::toXML(), cmlabs::ProcessStats::toXML(), cmlabs::QuerySpec::toXML(), cmlabs::RequestMapEntry::toXML(), cmlabs::RequestQueue::toXML(), cmlabs::RetrieveSpec::toXML(), cmlabs::SignalSpec::toXML(), cmlabs::TagMapEntry::toXML(), cmlabs::TriggerSpec::toXML(), cmlabs::TypeMapEntry::toXML(), cmlabs::MemoryManager::typeToText(), and cmlabs::MessagePlayer::waitForNextMessage().

◆ StringFormat() [2/2]

char * cmlabs::utils::StringFormat ( uint32 & size,
const char * format,
... )

printf into a freshly allocated buffer.

Parameters
[out]sizeReceives the text length.
formatprintf format + varargs.
Returns
new[]-allocated buffer (caller deletes).

Definition at line 6959 of file Utils.cpp.

References StringFormatVA().

◆ StringFormatInto()

bool cmlabs::utils::StringFormatInto ( char * dst,
uint32 maxsize,
const char * format,
... )

printf into a caller-supplied buffer with truncation.

Parameters
dstDestination.
maxsizeCapacity.
formatprintf format + varargs.
Returns
true when it fit.

Definition at line 7003 of file Utils.cpp.

References strcpyavail(), and StringFormatVA().

Referenced by _wrap_StringFormatInto__varargs__().

◆ StringFormatVA()

char * cmlabs::utils::StringFormatVA ( uint32 & size,
const char * format,
va_list args )

va_list core used by the other StringFormat overloads.

Parameters
[out]sizeReceives the length.
formatprintf format.
argsVariadic arguments.
Returns
Allocated buffer (caller deletes).

Definition at line 6973 of file Utils.cpp.

Referenced by cmlabs::PsyAPI::logPrint(), cmlabs::LogSystem::LogSystemDebug(), cmlabs::LogSystem::LogSystemPrint(), StringFormat(), StringFormat(), StringFormatInto(), and cmlabs::unittest::ut_vformat().

◆ StringMultiReplace()

uint32 cmlabs::utils::StringMultiReplace ( std::string & text,
std::map< std::string, std::string > & map,
bool onlyFirst )

Apply many key→value replacements in one pass.

Parameters
[in,out]textText to modify.
mapSearch/replace pairs.
onlyFirstReplace only the first hit per key.
Returns
Total replacements.

Definition at line 7069 of file Utils.cpp.

References StringSingleReplace().

Referenced by _wrap_StringMultiReplace(), and StringScriptReplace().

◆ StringScriptReplace()

uint32 cmlabs::utils::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.

Parameters
[in,out]textTemplate text.
nameBlock name marker.
listOne map of substitutions per repetition.
Returns
Number of substitutions performed.

Definition at line 7103 of file Utils.cpp.

References StringMultiReplace().

Referenced by _wrap_StringScriptReplace().

◆ StringSingleReplace()

uint32 cmlabs::utils::StringSingleReplace ( std::string & text,
std::string key,
std::string value,
bool onlyFirst )

Replace occurrences of key with value in text.

Parameters
[in,out]textText to modify.
keySearch string.
valueReplacement.
onlyFirstStop after the first replacement.
Returns
Number of replacements performed.

Definition at line 7051 of file Utils.cpp.

Referenced by _wrap_StringSingleReplace(), cmlabs::DataMessage::GetCSVHeader(), cmlabs::utils::Library::load(), cmlabs::RESTParser::setParameterValue(), cmlabs::RESTParser::setParameterValue(), StringMultiReplace(), TextUnindent(), and cmlabs::DataMessage::toCSV().

◆ TextCapitalise()

std::string cmlabs::utils::TextCapitalise ( const char * text)

Capitalise the first letter of text.

Parameters
textInput.
Returns
New string.

Definition at line 6500 of file Utils.cpp.

Referenced by _wrap_TextCapitalise().

◆ TextCommandlineSplit()

std::vector< std::string > cmlabs::utils::TextCommandlineSplit ( const char * cmdline)

Split a command line into arguments, honouring quoting rules.

Parameters
cmdlineRaw command line.
Returns
Argument vector.

Definition at line 6691 of file Utils.cpp.

Referenced by _wrap_TextCommandlineSplit(), SplitCommandline(), and SplitCommandlineW().

◆ TextIndent()

std::string cmlabs::utils::TextIndent ( const char * text,
const char * indent )

Prefix every line of text with indent.

Parameters
textInput.
indentIndent string (e.g. "\t").
Returns
New string.

Definition at line 6526 of file Utils.cpp.

References StringFormat(), and TextListSplitLines().

Referenced by _wrap_TextIndent(), and cmlabs::DataMessage::getUserEntriesAsString().

◆ TextJoin() [1/3]

std::string cmlabs::utils::TextJoin ( std::list< std::string > & list,
const char * split,
uint32 start = 0,
uint32 count = 0 )

Join list elements with split.

Parameters
listElements.
splitSeparator.
startFirst index.
countElements to join (0 = all remaining).
Returns
Joined string.

Definition at line 6852 of file Utils.cpp.

◆ TextJoin() [2/3]

std::string cmlabs::utils::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.

Parameters
mapPairs.
innersplitKey/value separator.
outersplitPair separator.
keyquotesQuote keys.
valquotesQuote values.
Returns
Joined string.

Definition at line 6867 of file Utils.cpp.

◆ TextJoin() [3/3]

std::string cmlabs::utils::TextJoin ( std::vector< std::string > & list,
const char * split,
uint32 start = 0,
uint32 count = 0 )

Join vector elements with split.

Parameters
listElements.
splitSeparator.
startFirst index.
countElements to join (0 = all remaining).
Returns
Joined string.

Definition at line 6837 of file Utils.cpp.

Referenced by _wrap_TextJoin__SWIG_0(), _wrap_TextJoin__SWIG_1(), _wrap_TextJoin__SWIG_2(), _wrap_TextJoin__SWIG_3(), _wrap_TextJoin__SWIG_4(), _wrap_TextJoin__SWIG_5(), _wrap_TextJoin__SWIG_6(), and TextListBreakLines().

◆ TextJoinJSON()

std::string cmlabs::utils::TextJoinJSON ( std::map< std::string, std::string > & map)

Serialize a map as a JSON object (keys/values escaped).

Parameters
mapPairs.
Returns
JSON text.

Definition at line 6884 of file Utils.cpp.

References EncodeJSON().

Referenced by _wrap_TextJoinJSON().

◆ TextJoinXML()

std::string cmlabs::utils::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.

Returns
XML text.

Definition at line 6900 of file Utils.cpp.

References cmlabs::html::EncodeHTML().

Referenced by _wrap_TextJoinXML().

◆ TextListBreakLines() [1/2]

std::string cmlabs::utils::TextListBreakLines ( const char * text,
uint32 maxLineLength,
const char * breakstr )

Word-wrap text, joining the wrapped lines with breakstr.

Parameters
textInput.
maxLineLengthMax characters per line.
breakstrLine separator to insert.
Returns
Wrapped text.

Definition at line 6829 of file Utils.cpp.

References TextJoin(), and TextListBreakLines().

◆ TextListBreakLines() [2/2]

std::vector< std::string > cmlabs::utils::TextListBreakLines ( const char * text,
uint32 maxLineLength = 80 )

Word-wrap text into lines no longer than maxLineLength.

Parameters
textInput.
maxLineLengthMax characters per line.
Returns
Wrapped lines.

Definition at line 6759 of file Utils.cpp.

References TextTrim().

Referenced by _wrap_TextListBreakLines__SWIG_0(), _wrap_TextListBreakLines__SWIG_1(), _wrap_TextListBreakLines__SWIG_2(), and TextListBreakLines().

◆ TextListSplit()

std::vector< std::string > cmlabs::utils::TextListSplit ( const char * text,
const char * split,
bool keepEmpty = true,
bool autoTrim = false )

Split text on a separator.

Parameters
textInput.
splitSeparator string.
keepEmptyKeep zero-length fields.
autoTrimTrim whitespace from each field.
Returns
Fields in order.
std::vector<std::string> parts = TextListSplit("a, b,,c", ",", false, true); // {"a","b","c"}
std::vector< std::string > TextListSplit(const char *text, const char *split, bool keepEmpty=true, bool autoTrim=false)
Split text on a separator.
Definition Utils.cpp:6918

Definition at line 6918 of file Utils.cpp.

References TextTrim().

Referenced by _wrap_TextListSplit__SWIG_0(), _wrap_TextListSplit__SWIG_1(), _wrap_TextListSplit__SWIG_2(), cmlabs::PostSpec::addContentToMsg(), cmlabs::HTTPRequest::getBasicAuthorizationPassword(), cmlabs::HTTPRequest::getBasicAuthorizationUser(), cmlabs::VantagePoints::init(), cmlabs::HTTPRequest::parseContentChunk(), cmlabs::RESTParser::parseRequest(), cmlabs::RequestGateway::receiveMessage(), TextListSplitLines(), and cmlabs::PostSpec::toXML().

◆ TextListSplitLines()

std::vector< std::string > cmlabs::utils::TextListSplitLines ( const char * text,
bool keepEmpty = true,
bool autoTrim = false )

Split text into lines, handling both \n and \r\n.

Parameters
textInput.
keepEmptyKeep empty lines.
autoTrimTrim each line.
Returns
Lines in order.

Definition at line 6741 of file Utils.cpp.

References TextListSplit().

Referenced by _wrap_TextListSplitLines__SWIG_0(), _wrap_TextListSplitLines__SWIG_1(), _wrap_TextListSplitLines__SWIG_2(), and TextIndent().

◆ TextLowercase()

std::string cmlabs::utils::TextLowercase ( const char * text)

Convert to lower case (ASCII/current locale).

Parameters
textInput.
Returns
New string.

Definition at line 6520 of file Utils.cpp.

Referenced by _wrap_TextLowercase().

◆ TextMapSplit()

std::map< std::string, std::string > cmlabs::utils::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).

Parameters
textInput.
outersplitSeparator between pairs.
innersplitSeparator between key and value.
Returns
Parsed map.
Note
Same trimming, skipping and single-character-separator caveats as TextMultiMapSplit().
std::map<std::string, std::string> m =
utils::TextMapSplit("host=10.0.0.1; port=8080; port=9090", ";", "=");
// m["host"] == "10.0.0.1", m["port"] == "9090" (last duplicate wins)
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).
Definition Utils.cpp:6618

Definition at line 6618 of file Utils.cpp.

References TextTrim().

Referenced by _wrap_TextMapSplit(), and cmlabs::RESTRequest::RESTRequest().

◆ TextMultiMapSplit()

std::multimap< std::string, std::string > cmlabs::utils::TextMultiMapSplit ( const char * text,
const char * outersplit,
const char * innersplit )

Split "k=v<sep>k=v..." text into a multimap (duplicate keys preserved).

Parameters
textInput.
outersplitSeparator between pairs.
innersplitSeparator between key and value.
Returns
Parsed multimap.
Note
Keys and values are TextTrim()med. Segments that contain no innersplit before the next outersplit are silently skipped.
Warning
The scanner advances only one character past each outersplit match and takes the value from one character after the innersplit match, so both separators should be single characters; multi-character separators leave their remaining characters in the parsed fields.

Definition at line 6591 of file Utils.cpp.

References TextTrim().

Referenced by _wrap_TextMultiMapSplit(), cmlabs::HTTPRequest::parseContentChunk(), cmlabs::RESTParser::parseRequest(), cmlabs::HTTPRequest::parseURIParameters(), and cmlabs::HTTPRequest::processHeader().

◆ TextSubstringCopy()

char * cmlabs::utils::TextSubstringCopy ( const char * ascii,
uint32 start,
uint32 end )

Copy the substring [start,end) into a new NUL-terminated buffer.

Parameters
asciiSource.
start,endBounds.
Returns
new[]-allocated copy (caller deletes).

Definition at line 7838 of file Utils.cpp.

Referenced by _wrap_TextSubstringCopy(), Ascii2Float64(), Ascii2Int32(), Ascii2Int64(), Ascii2Uint32(), Ascii2Uint64(), AsciiHex2Uint32(), and AsciiHex2Uint64().

◆ TextTrim()

std::string cmlabs::utils::TextTrim ( const char * text)

Strip leading and trailing whitespace.

Parameters
textInput.
Returns
New string.
Note
"Whitespace" here means every character with a value of 32 or below, so control characters (tabs, CR/LF, NUL-adjacent bytes) are trimmed too. NULL input yields an empty string.

Definition at line 6576 of file Utils.cpp.

Referenced by _wrap_TextTrim(), TextListBreakLines(), TextListSplit(), TextMapSplit(), and TextMultiMapSplit().

◆ TextTrimQuotes()

std::string cmlabs::utils::TextTrimQuotes ( const char * text)

Strip a single pair of surrounding quotes if present.

Parameters
textInput.
Returns
New string.

Definition at line 6558 of file Utils.cpp.

Referenced by _wrap_TextTrimQuotes(), cmlabs::HTTPRequest::parseContentChunk(), cmlabs::RESTParser::parseRequest(), and cmlabs::PsySpace::PsySpace().

◆ TextUnindent()

std::string cmlabs::utils::TextUnindent ( const char * text)

Remove one level of leading indentation from every line.

Parameters
textInput.
Returns
New string.

Definition at line 6537 of file Utils.cpp.

References StringSingleReplace().

Referenced by _wrap_TextUnindent().

◆ TextUppercase()

std::string cmlabs::utils::TextUppercase ( const char * text)

Convert to upper case (ASCII/current locale).

Parameters
textInput.
Returns
New string.

Definition at line 6514 of file Utils.cpp.

Referenced by _wrap_TextUppercase().

◆ TextVectorConcat()

std::string cmlabs::utils::TextVectorConcat ( std::vector< std::string > vect,
const char * sep,
bool allowEmpty = true )

Concatenate vector entries with sep.

Parameters
vectEntries to join.
sepSeparator.
allowEmptyInclude empty entries when true.
Returns
Joined string.

Definition at line 6946 of file Utils.cpp.

Referenced by _wrap_TextVectorConcat__SWIG_0(), _wrap_TextVectorConcat__SWIG_1(), and cmlabs::RequestExecutor::addGateway().

◆ Uint2Ascii()

char * cmlabs::utils::Uint2Ascii ( uint64 value,
char * result,
uint16 size,
uint8 base )

Render an unsigned integer as text in an arbitrary base.

Parameters
valueNumber.
resultDestination buffer.
sizeBuffer capacity.
baseRadix 2–36.
Returns
result, or NULL when it does not fit.

Definition at line 5470 of file Utils.cpp.

Referenced by _wrap_Uint2Ascii().

◆ WaitForNextEvent()

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

◆ WaitForSocketReadability()

◆ WaitForSocketWriteability()

bool cmlabs::utils::WaitForSocketWriteability ( SOCKET s,
int32 timeout )

Wait until a socket can be written without blocking.

Parameters
sSocket.
timeoutMax wait in ms.
Returns
true when writable.

Definition at line 5675 of file Utils.cpp.

References INVALID_SOCKET, and SOCKET.

Referenced by _wrap_WaitForSocketWriteability(), cmlabs::SSLConnection::connect(), cmlabs::SSLConnection::send(), cmlabs::TCPConnection::send(), cmlabs::UDPConnection::send(), and cmlabs::NetworkConnection::waitForDataToBeWritten().

◆ WriteAFile() [1/2]

bool cmlabs::utils::WriteAFile ( const char * dir,
const char * filename,
const char * data,
uint32 length,
bool binary = false )

Write dir/filename; see WriteAFile().

Returns
true on success.

Definition at line 7273 of file Utils.cpp.

References WriteAFile().

◆ WriteAFile() [2/2]

bool cmlabs::utils::WriteAFile ( const char * filename,
const char * data,
uint32 length,
bool binary = false )

Write (create/overwrite) a file.

Parameters
filenamePath.
dataBytes.
lengthByte count.
binaryBinary mode.
Returns
true on success.
Note
Truncates any existing file — there is no append or atomic-replace behaviour (see AppendToAFile() for appending). Pass binary=true for non-text payloads, otherwise Windows expands \n to CRLF on disk.

Definition at line 7284 of file Utils.cpp.

Referenced by _wrap_WriteAFile__SWIG_0(), _wrap_WriteAFile__SWIG_1(), _wrap_WriteAFile__SWIG_2(), _wrap_WriteAFile__SWIG_3(), CopyAFile(), cmlabs::MessagePlayer::exportToCSVFile(), cmlabs::MessagePlayer::initWrite(), cmlabs::Bitmap::saveToFile(), cmlabs::ut_writeChildResult(), WriteAFile(), and cmlabs::MessagePlayer::writeMetadata().

◆ WriteRegistryDWORD() [1/2]

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

Write a 32-bit registry value (creates the key when needed).

Returns
true on success.

◆ WriteRegistryDWORD() [2/2]

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

Definition at line 8494 of file Utils.cpp.

◆ WriteRegistryQWORD() [1/2]

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

Write a 64-bit registry value.

Returns
true on success.

◆ WriteRegistryQWORD() [2/2]

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

Definition at line 8495 of file Utils.cpp.

◆ WriteRegistryString() [1/2]

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

Write a string registry value.

Returns
true on success.

◆ WriteRegistryString() [2/2]

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

Definition at line 8496 of file Utils.cpp.

Variable Documentation

◆ OSArchitectureName

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

Definition at line 4914 of file Utils.cpp.

Referenced by GetSystemArchitecture().

◆ OSLocalHostName

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

Definition at line 4913 of file Utils.cpp.

Referenced by GetComputerName().

◆ OSName

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

Definition at line 4915 of file Utils.cpp.

Referenced by GetSystemOSName().