|
CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
|
Implementation of the cross-platform utility layer declared in Utils.h. More...
#include "Utils.h"#include "ObjectIDs.h"#include "HTML.h"#include "ThreadManager.h"#include "UnitTestFramework.h"Go to the source code of this file.
Namespaces | |
| namespace | cmlabs |
| namespace | cmlabs::utils |
Macros | |
| #define | poly 0xEDB88320 |
Functions | |
| bool | cmlabs::ClearUtilsMaps () |
| Free all lazily-allocated global registries (mutex/semaphore/event/shared-memory maps). | |
| std::string | cmlabs::GetDataTypeName (uint32 datatype) |
| Translate a CMSDK datatype id (e.g. | |
| uint32 | cmlabs::GetDataTypeID (const char *typeName) |
| Inverse of GetDataTypeName(): look up the numeric datatype id for a type name. | |
| bool | cmlabs::utils::CalcTimeout (struct timespec &timeout, uint32 ms) |
| uint64 | cmlabs::utils::GetTime () |
| static void | cmlabs::utils::DrumBeatCallback (union sigval p) |
| bool | cmlabs::utils::WaitForNextEvent (const char *name, uint32 ms, bool autocreate) |
| uint64 | cmlabs::utils::hton64 (const uint64 *input) |
| int32 | cmlabs::utils::ReadRegistryDWORD (const char *key) |
| int64 | cmlabs::utils::ReadRegistryQWORD (const char *key) |
| std::string | cmlabs::utils::ReadRegistryString (const char *key) |
| bool | cmlabs::utils::WriteRegistryDWORD (const char *key, int32 value) |
| bool | cmlabs::utils::WriteRegistryQWORD (const char *key, int64 value) |
| bool | cmlabs::utils::WriteRegistryString (const char *key, const char *value) |
| bool | cmlabs::utils::DeleteRegistryTree (const char *key) |
| bool | cmlabs::utils::RenameRegistryTree (const char *entry, const char *newName) |
| static bool | cmlabs::Test_Utils () |
| static bool | cmlabs::Test_Timer () |
| void | cmlabs::Register_Utils_Tests () |
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. | |
| bool | cmlabs::utils::CreateDrumBeat (uint32 id, uint32 interval, DrumBeatFunc func, bool autostart=false) |
Create a periodic timer ("drum beat") that calls func every interval ms. | |
| bool | cmlabs::utils::StartDrumBeat (uint32 id) |
| Start (or resume) a previously created drum beat. | |
| bool | cmlabs::utils::StopDrumBeat (uint32 id) |
| Stop a running drum beat without destroying it. | |
| bool | cmlabs::utils::EndDrumBeat (uint32 id) |
| Destroy a drum beat and release its OS timer. | |
| bool | cmlabs::utils::EnterMutex (const char *name, uint32 ms, bool autocreate=true) |
| Acquire a named global mutex, creating it on first use. | |
| bool | cmlabs::utils::LeaveMutex (const char *name) |
| Release a named global mutex previously acquired with EnterMutex(). | |
| bool | cmlabs::utils::DestroyMutex (const char *name) |
| Destroy a named global mutex and remove it from the registry. | |
| Semaphore * | cmlabs::utils::GetSemaphore (const char *name, bool autocreate=true) |
| Look up (and optionally create) a named semaphore in the global registry. | |
| bool | cmlabs::utils::WaitForSemaphore (const char *name, uint32 ms, bool autocreate=true) |
| Wait on a named global semaphore. | |
| bool | cmlabs::utils::SignalSemaphore (const char *name) |
| Signal a named global semaphore. | |
| bool | cmlabs::utils::DestroySemaphore (const char *name) |
| Destroy a named global semaphore. | |
| bool | cmlabs::utils::SignalEvent (const char *name) |
| Signal a named global event. | |
| bool | cmlabs::utils::DestroyEvent (const char *name) |
| Destroy a named global event. | |
| bool | cmlabs::utils::SetSharedSystemInstance (uint32 inst) |
| Set the instance number used to namespace shared OS objects, allowing several independent CMSDK systems on one host. | |
| uint32 | cmlabs::utils::GetSharedSystemInstance () |
| Get the current shared-system instance number. | |
Timers and queues | |
| static void | cmlabs::utils::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 | cmlabs::utils::UnitTest_Timer () |
| Self test for the Timer class. | |
| bool | cmlabs::utils::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 * | cmlabs::utils::CreateSharedMemorySegment (const char *name, uint64 size, bool force=false) |
| Create a named shared memory segment and map it into this process. | |
| char * | cmlabs::utils::OpenSharedMemorySegment (const char *name, uint64 size) |
| Open and map an existing named shared memory segment. | |
| bool | cmlabs::utils::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 | cmlabs::utils::ntoh64 (const uint64 *input) |
| Convert a 64-bit value from network to host byte order. | |
| uint32 | cmlabs::utils::Calc32BitFieldSize (uint32 bitsize) |
Compute the byte size needed for a bitfield of bitsize bits, rounded up to a 32-bit boundary. | |
| bool | cmlabs::utils::Reset32BitField (char *bitfield, uint32 bytesize) |
| Zero the whole bitfield, marking every bit as free. | |
| bool | cmlabs::utils::GetFirstFreeBitLoc (const char *bitfield, uint32 bytesize, uint32 &loc) |
| Find the first 0 (free) bit. | |
| bool | cmlabs::utils::GetFirstFreeBitLocN (const char *bitfield, uint32 bytesize, uint32 num, uint32 &loc) |
Find the first run of num consecutive 0 bits. | |
| bool | cmlabs::utils::SetBit (uint32 loc, bit value, char *bitfield, uint32 bytesize) |
Set bit loc to value. | |
| bool | cmlabs::utils::SetBitN (uint32 loc, uint32 num, bit value, char *bitfield, uint32 bytesize) |
Set num consecutive bits starting at loc to value. | |
| bool | cmlabs::utils::GetBit (uint32 loc, const char *bitfield, uint32 bytesize, bit &val) |
Read bit loc. | |
| bool | cmlabs::utils::GetLastOccupiedBitLoc (const char *bitfield, uint32 bytesize, uint32 &loc) |
| Find the highest set (occupied) bit. | |
| std::string | cmlabs::utils::GetBitFieldAsString (const char *bitfield, uint32 bytesize, uint32 size) |
Render the first size bits as a '0'/'1' string, for debugging. | |
| std::string | cmlabs::utils::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 | |
| int32 | cmlabs::utils::AtomicIncrement32 (int32 volatile &v) |
| Atomically increment a 32-bit value. | |
| int64 | cmlabs::utils::AtomicIncrement64 (int64 volatile &v) |
| Atomically increment a 64-bit value. | |
| int32 | cmlabs::utils::AtomicDecrement32 (int32 volatile &v) |
| Atomically decrement a 32-bit value. | |
| int64 | cmlabs::utils::AtomicDecrement64 (int64 volatile &v) |
| Atomically decrement a 64-bit value. | |
| bool | cmlabs::utils::Sleep (uint32 ms) |
| Suspend the calling thread. | |
| std::string | cmlabs::utils::PrintProgramTrace (uint32 startLine=0, uint32 endLine=0) |
| Format the current call stack as printable text. | |
| std::list< std::string > | cmlabs::utils::GetProgramTrace () |
| Capture the current call stack. | |
| bool | cmlabs::utils::CreateThread (THREAD_FUNCTION func, void *args, ThreadHandle &thread, uint32 &osID) |
| Start a new OS thread. | |
| bool | cmlabs::utils::CheckForThreadFinished (ThreadHandle hThread) |
| Non-blocking check whether a thread has terminated. | |
| bool | cmlabs::utils::WaitForThreadToFinish (ThreadHandle hThread, uint32 timeoutMS=0) |
| Join a thread. | |
| bool | cmlabs::utils::TerminateThread (ThreadHandle hThread) |
| Forcibly kill a thread. | |
| bool | cmlabs::utils::PauseThread (ThreadHandle hThread) |
| Suspend a thread's execution. | |
| bool | cmlabs::utils::ContinueThread (ThreadHandle hThread) |
| Resume a thread paused with PauseThread(). | |
| bool | cmlabs::utils::GetCurrentThreadUniqueID (uint32 &tid) |
| Get a process-unique id for the calling thread. | |
| bool | cmlabs::utils::GetCurrentThreadOSID (uint32 &tid) |
| Get the OS-level id of the calling thread (gettid / GetCurrentThreadId). | |
| bool | cmlabs::utils::GetCurrentThread (ThreadHandle &thread) |
| Get the handle of the calling thread. | |
| bool | cmlabs::utils::IsThreadRunning (ThreadHandle hThread) |
| Check whether a thread is still alive. | |
| uint32 | cmlabs::utils::GetThreadStatColAbility () |
| Report this platform's capability for per-thread CPU statistics collection. | |
| bool | cmlabs::utils::GetCPUTicks (ThreadHandle hThread, uint64 &ticks) |
| Get accumulated CPU time of a specific thread. | |
| bool | cmlabs::utils::GetCPUTicks (uint64 &ticks) |
| Get accumulated CPU time of the calling thread. | |
| bool | cmlabs::utils::GetProcessCPUTicks (uint32 osProcID, uint64 &ticks) |
| Get accumulated CPU time of another process. | |
| bool | cmlabs::utils::GetProcessCPUTicks (uint64 &ticks) |
| Get accumulated CPU time of the current process. | |
| bool | cmlabs::utils::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 | cmlabs::utils::GetProcAndOSCPUUsage (uint32 osProcID, double &procPercentUse, double &osPercentUse, uint64 &prevOSTicks, uint64 &prevOSIdleTicks, uint64 &prevProcTicks) |
| As GetProcAndOSCPUUsage() above, but for an arbitrary process. | |
| bool | cmlabs::utils::GetOSCPUUsage (double &percentUse) |
| Get the instantaneous total OS CPU usage. | |
| bool | cmlabs::utils::GetThreadPriority (ThreadHandle hThread, uint16 priority) |
| Query a thread's scheduling priority. | |
| bool | cmlabs::utils::SetThreadPriority (ThreadHandle hThread, uint16 priority) |
| Set a thread's scheduling priority. | |
| int | cmlabs::utils::ToOSPriority (int pri) |
| Map a CMSDK priority value to the platform's native priority scale. | |
| int | cmlabs::utils::FromOSPriority (int pri) |
| Map a native OS priority back to the CMSDK priority scale. | |
| bool | cmlabs::utils::SignalThread (ThreadHandle hThread, int32 signal) |
| Send a signal to a thread (POSIX pthread_kill; limited emulation on Windows). | |
Desktop and console | |
| bool | cmlabs::utils::GetDesktopSize (uint32 &width, uint32 &height) |
| Get the primary desktop resolution. | |
| bool | cmlabs::utils::RenameConsoleWindow (const char *name, bool prepend=false) |
| Set the console window title. | |
| bool | cmlabs::utils::MoveConsoleWindow (int32 x=-1, int32 y=-1, int32 w=-1, int32 h=-1) |
| Move/resize the console window. | |
Process management | |
| uint32 | cmlabs::utils::GetLocalProcessID () |
| Get the OS process id of the current process. | |
| int | cmlabs::utils::RunOSCommand (const char *cmdline, const char *initdir, uint32 timeout, std::string &stdoutString, std::string &stderrString) |
| Run a command synchronously and capture its output. | |
| uint32 | cmlabs::utils::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 | cmlabs::utils::GetProcessStatus (uint32 proc, int &returncode) |
| Poll a child started with NewProcess(). | |
| bool | cmlabs::utils::EndProcess (uint32 proc) |
| Forcibly terminate a child process. | |
| uint8 | cmlabs::utils::WaitForProcess (uint32 proc, uint32 timeout, int &returncode) |
| Wait for a child to exit. | |
Dynamic libraries and command line | |
| bool | cmlabs::utils::SetCommandLine (int argc, char *argv[]) |
| Parse and store the process command line for later retrieval by the Get/HasCommandLine* functions. | |
| std::string | cmlabs::utils::GetCommandLine () |
| Get the full original command line as one string. | |
| std::string | cmlabs::utils::GetCommandLinePath () |
| Get the directory portion of the executable path. | |
| std::string | cmlabs::utils::GetCommandLineExecutable () |
| Get the full executable path as invoked. | |
| std::string | cmlabs::utils::GetCommandLineExecutableOnly () |
| Get just the executable filename without path. | |
| uint32 | cmlabs::utils::GetCommandLineArgCount () |
| Number of positional command line items (excluding the executable). | |
| std::string | cmlabs::utils::GetCommandLineArg (uint16 n) |
| Get the n-th positional command line item. | |
| std::string | cmlabs::utils::GetCommandLineArg (const char *key) |
| Get the value of a 'key=value' command line argument. | |
| bool | cmlabs::utils::HasCommandLineArg (const char *key, std::string &value) |
| Test for a 'key=value' argument without mutating the argument map. | |
| Library * | cmlabs::utils::OpenLibrary (const char *libName) |
| Load a library by name, applying platform filename conventions. | |
OS and hardware information | |
| const char * | cmlabs::utils::GetComputerName () |
| Get this machine's hostname. | |
| uint64 | cmlabs::utils::GetProcessMemoryUsage () |
| Current resident memory usage of this process. | |
| uint64 | cmlabs::utils::GetPeakProcessMemoryUsage () |
| Peak resident memory usage of this process. | |
| uint16 | cmlabs::utils::GetCPUCount () |
| Number of logical CPU cores. | |
| uint16 | cmlabs::utils::GetCPUArchitecture () |
| CPU architecture id. | |
| uint64 | cmlabs::utils::GetCPUSpeed () |
| Nominal CPU clock speed. | |
| uint64 | cmlabs::utils::GetSystemMemorySize () |
| Total physical RAM installed. | |
| bool | cmlabs::utils::GetSystemMemoryUsage (uint64 &totalRAM, uint64 &freeRAM) |
| Query total and free physical memory. | |
| const char * | cmlabs::utils::GetSystemArchitecture () |
| Architecture name string, e.g. | |
| const char * | cmlabs::utils::GetSystemOSName () |
| OS name string, e.g. | |
| bool | cmlabs::utils::GetSystemOSVersion (uint16 &major, uint16 &minor, uint16 &build, char *text, uint16 textSize) |
| Detailed OS version. | |
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.
| |
| char * | cmlabs::utils::Int2Ascii (int64 value, char *result, uint16 size, uint8 base) |
| Render a signed integer as text in an arbitrary base. | |
| char * | cmlabs::utils::Uint2Ascii (uint64 value, char *result, uint16 size, uint8 base) |
| Render an unsigned integer as text in an arbitrary base. | |
| 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). | |
| char * | cmlabs::utils::TextSubstringCopy (const char *ascii, uint32 start, uint32 end) |
| Copy the substring [start,end) into a new NUL-terminated buffer. | |
| bool | cmlabs::utils::IsTextNumeric (const char *ascii, uint32 start=0, uint32 end=0) |
| Test whether a (sub)string is a valid number. | |
| int64 | cmlabs::utils::Ascii2Int64 (const char *ascii, uint32 start=0, uint32 end=0) |
| Parse a signed 64-bit decimal integer from a substring. | |
| uint64 | cmlabs::utils::Ascii2Uint64 (const char *ascii, uint32 start=0, uint32 end=0) |
| Parse an unsigned 64-bit decimal integer from a substring. | |
| 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. | |
| int32 | cmlabs::utils::Ascii2Int32 (const char *ascii, uint32 start=0, uint32 end=0) |
| Parse a signed 32-bit decimal integer from a substring. | |
| uint32 | cmlabs::utils::Ascii2Uint32 (const char *ascii, uint32 start=0, uint32 end=0) |
| Parse an unsigned 32-bit decimal integer from a substring. | |
| uint32 | cmlabs::utils::AsciiHex2Uint32 (const char *ascii, uint32 start=0, uint32 end=0) |
| Parse an unsigned 32-bit hexadecimal integer from a substring. | |
| float64 | cmlabs::utils::Ascii2Float64 (const char *ascii, uint32 start=0, uint32 end=0) |
| Parse a 64-bit float from a substring (decimal point, not locale dependent). | |
| std::string | cmlabs::utils::DecodeJSON (std::string str) |
| Unescape a JSON string value (\" \\ \n \t \uXXXX etc.). | |
| std::string | cmlabs::utils::EncodeJSON (std::string str) |
| Escape text for embedding as a JSON string value. | |
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 | cmlabs::utils::GetSocketError (int wsaError, char *errorString, uint16 errorStringMaxSize, bool *isRecoverable) |
| Translate a socket error code into text and classify it. | |
| int | cmlabs::utils::GetLastOSErrorNumber () |
| Get the last OS error number (errno / GetLastError()). | |
| std::string | cmlabs::utils::GetLastOSErrorMessage () |
| Get the last OS error as human-readable text. | |
| bool | cmlabs::utils::WaitForSocketWriteability (SOCKET s, int32 timeout) |
| Wait until a socket can be written without blocking. | |
| bool | cmlabs::utils::WaitForSocketReadability (SOCKET s, int32 timeout) |
| Wait until a socket has data to read. | |
| bool | cmlabs::utils::SetSocketNonBlockingMode (SOCKET s) |
| Put a socket into non-blocking mode. | |
| bool | cmlabs::utils::SetSocketBlockingMode (SOCKET s) |
| Put a socket into blocking mode. | |
| bool | cmlabs::utils::LookupIPAddress (const char *name, uint32 &address) |
| Resolve a hostname to an IPv4 address. | |
| bool | cmlabs::utils::LookupHostname (uint32 address, char *name, uint32 maxSize) |
| Reverse-resolve an IPv4 address to a hostname. | |
| std::string | cmlabs::utils::GetLocalHostnameString () |
| Local hostname as std::string. | |
| bool | cmlabs::utils::GetLocalHostname (char *name, uint32 maxSize) |
| Local hostname into a caller buffer. | |
| bool | cmlabs::utils::GetLocalMACAddress (uint64 &address) |
| Get the primary local MAC address. | |
| uint64 * | cmlabs::utils::GetLocalMACAddresses (uint32 &count) |
| List all local MAC addresses. | |
| bool | cmlabs::utils::IsLocalIPAddress (const char *addr) |
| Test whether a textual address refers to this machine (loopback or a local interface). | |
| bool | cmlabs::utils::IsLocalIPAddress (uint32 &address) |
| Test whether a numeric IPv4 address is local. | |
| bool | cmlabs::utils::GetLocalIPAddress (uint32 &address) |
| Get the primary local IPv4 address. | |
| uint32 * | cmlabs::utils::GetLocalIPAddresses (uint32 &count) |
| List all local IPv4 addresses. | |
| NetworkInterfaces * | cmlabs::utils::GetLocalInterfaces (uint32 &count) |
| Enumerate local network interfaces with address, MAC and names. | |
| bool | cmlabs::utils::GetNextAvailableLocalPort (uint16 lastPort, uint16 &nextPort) |
Find the next free TCP port above lastPort. | |
C-string helpers | |
Low-level, allocation-free operations on raw char buffers. | |
| bool | cmlabs::utils::UtilsTest () |
| Run the built-in self test of the utils module. | |
| void | cmlabs::utils::PrintBinary (void *p, uint32 size, bool asInt, const char *title) |
| Hex/decimal dump a memory region to stdout for debugging. | |
| const char * | cmlabs::utils::stristr (const char *str, const char *substr, uint32 len=0) |
| Case-insensitive strstr. | |
| uint32 | cmlabs::utils::strcpyavail (char *dst, const char *src, uint32 maxlen, bool copyAvailable) |
| Bounded strcpy that always NUL-terminates. | |
| bool | cmlabs::utils::GetNextLineEnd (const char *str, uint32 size, uint32 &len, uint32 &crSize) |
| Find the end of the current line. | |
| uint32 | cmlabs::utils::TextReplaceCharsInPlace (char *str, uint32 size, char find, char replace) |
| Replace every occurrence of a character, in place. | |
| const char * | cmlabs::utils::laststrstr (const char *str1, const char *str2) |
Find the last occurrence of str2 in str1. | |
| const char * | cmlabs::utils::laststristr (const char *str1, const char *str2) |
| Case-insensitive laststrstr(). | |
| bool | cmlabs::utils::TextEndsWith (const char *str, const char *end, bool caseSensitive=true) |
Test whether str ends with end. | |
| bool | cmlabs::utils::TextStartsWith (const char *str, const char *start, bool caseSensitive=true) |
Test whether str starts with start. | |
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 | cmlabs::utils::TextCapitalise (const char *text) |
Capitalise the first letter of text. | |
| std::string | cmlabs::utils::TextUppercase (const char *text) |
| Convert to upper case (ASCII/current locale). | |
| std::string | cmlabs::utils::TextLowercase (const char *text) |
| Convert to lower case (ASCII/current locale). | |
| std::string | cmlabs::utils::TextIndent (const char *text, const char *indent) |
Prefix every line of text with indent. | |
| std::string | cmlabs::utils::TextUnindent (const char *text) |
| Remove one level of leading indentation from every line. | |
| std::string | cmlabs::utils::TextTrimQuotes (const char *text) |
| Strip a single pair of surrounding quotes if present. | |
| std::string | cmlabs::utils::TextTrim (const char *text) |
| Strip leading and trailing whitespace. | |
| 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). | |
| 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). | |
| char ** | cmlabs::utils::SplitCommandline (const char *cmdline, int &argc) |
| Split a command line into a malloc'ed argv array. | |
| wchar_t ** | cmlabs::utils::SplitCommandlineW (const char *cmdline, int &argc) |
| Wide-character variant of SplitCommandline() (for Windows APIs). | |
| bool | cmlabs::utils::DeleteCommandline (char **argv, int argc) |
| Free an argv array produced by SplitCommandline(). | |
| std::vector< std::string > | cmlabs::utils::TextCommandlineSplit (const char *cmdline) |
| Split a command line into arguments, honouring quoting rules. | |
| 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. | |
| std::vector< std::string > | cmlabs::utils::TextListBreakLines (const char *text, uint32 maxLineLength=80) |
Word-wrap text into lines no longer than maxLineLength. | |
| std::string | cmlabs::utils::TextListBreakLines (const char *text, uint32 maxLineLength, const char *breakstr) |
Word-wrap text, joining the wrapped lines with breakstr. | |
| std::string | cmlabs::utils::TextJoin (std::vector< std::string > &list, const char *split, uint32 start=0, uint32 count=0) |
Join vector elements with split. | |
| std::string | cmlabs::utils::TextJoin (std::list< std::string > &list, const char *split, uint32 start=0, uint32 count=0) |
Join list elements with split. | |
| 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. | |
| std::string | cmlabs::utils::TextJoinJSON (std::map< std::string, std::string > &map) |
| Serialize a map as a JSON object (keys/values escaped). | |
| 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. | |
| std::vector< std::string > | cmlabs::utils::TextListSplit (const char *text, const char *split, bool keepEmpty=true, bool autoTrim=false) |
| Split text on a separator. | |
| std::string | cmlabs::utils::TextVectorConcat (std::vector< std::string >, const char *sep, bool allowEmpty=true) |
Concatenate vector entries with sep. | |
printf-style string formatting | |
| char * | cmlabs::utils::StringFormat (uint32 &size, const char *format,...) |
| printf into a freshly allocated buffer. | |
| char * | cmlabs::utils::StringFormatVA (uint32 &size, const char *format, va_list args) |
| va_list core used by the other StringFormat overloads. | |
| bool | cmlabs::utils::StringFormatInto (char *dst, uint32 maxsize, const char *format,...) |
| printf into a caller-supplied buffer with truncation. | |
| std::string | cmlabs::utils::StringFormat (const char *format,...) |
| printf into a std::string. | |
String replacement and templating | |
| uint32 | cmlabs::utils::StringSingleReplace (std::string &text, std::string key, std::string value, bool onlyFirst) |
Replace occurrences of key with value in text. | |
| uint32 | cmlabs::utils::StringMultiReplace (std::string &text, std::map< std::string, std::string > &map, bool onlyFirst) |
| Apply many key→value replacements in one pass. | |
| 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. | |
Numeric conversion and checksums | |
| unsigned char | cmlabs::utils::Hex2Char (const char *str) |
| Parse two hex digits into a byte. | |
| unsigned char | cmlabs::utils::Dec2Char (const char *str) |
| Parse up to three decimal digits into a byte. | |
| int8 | cmlabs::utils::CompareFloats (float64 a, float64 b) |
| Compare two doubles with epsilon tolerance. | |
| int | cmlabs::utils::CRC32 (const char *addr, uint32 length, int32 crc=0) |
| Compute (or continue) a CRC-32 checksum. | |
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 | cmlabs::utils::ReadAFileString (std::string filename) |
| Read an entire file into a std::string. | |
| char * | cmlabs::utils::ReadAFile (const char *dir, const char *filename, uint32 &length, bool binary=false) |
Read dir/ a new buffer; see ReadAFile(). | |
| char * | cmlabs::utils::ReadAFile (const char *filename, uint32 &length, bool binary=false) |
| Read an entire file into a new buffer. | |
| bool | cmlabs::utils::WriteAFile (const char *dir, const char *filename, const char *data, uint32 length, bool binary=false) |
Write dir/ see WriteAFile(). | |
| bool | cmlabs::utils::WriteAFile (const char *filename, const char *data, uint32 length, bool binary=false) |
| Write (create/overwrite) a file. | |
| bool | cmlabs::utils::AppendToAFile (const char *dir, const char *filename, const char *data, uint32 length, bool binary=false) |
Append to dir/ see AppendToAFile(). | |
| bool | cmlabs::utils::AppendToAFile (const char *filename, const char *data, uint32 length, bool binary=false) |
| Append to a file, creating it if missing. | |
| bool | cmlabs::utils::DeleteAFile (const char *dir, const char *filename, bool force) |
Delete dir/ see DeleteAFile(). | |
| bool | cmlabs::utils::DeleteAFile (const char *filename, bool force) |
| Delete a file. | |
| bool | cmlabs::utils::ChangeAFileAttr (const char *filename, bool read, bool write) |
| Change read/write permission attributes of a file. | |
| bool | cmlabs::utils::MoveAFile (const char *oldfilename, const char *newfilename, bool force=false) |
| Move/rename a file. | |
| 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(). | |
| bool | cmlabs::utils::CopyAFile (const char *oldfilename, const char *newfilename, bool force=false) |
| Copy a file. | |
| 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(). | |
| bool | cmlabs::utils::CreateADir (const char *dirname) |
| Create a directory (parents included where supported). | |
| bool | cmlabs::utils::DeleteADir (const char *dirname, bool force) |
Delete a directory (recursively when force). | |
| bool | cmlabs::utils::DeleteFilesInADir (const char *dirname, bool force) |
| Delete all files inside a directory, leaving the directory itself. | |
| std::string | cmlabs::utils::GetFilePath (const char *filename) |
| Directory portion of a path. | |
| const char * | cmlabs::utils::GetFileBasename (const char *filename) |
| Filename portion of a path. | |
| std::string | cmlabs::utils::GetCurrentDir () |
| Current working directory. | |
| 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. | |
| bool | cmlabs::utils::DoesADirExist (const char *dirname) |
| Test whether a directory exists. | |
| bool | cmlabs::utils::DoesAFileExist (const char *filename) |
| Test whether a regular file exists. | |
| FileDetails | cmlabs::utils::GetFileDetails (const char *filename) |
| Stat a file. | |
Random numbers and human-readable sizes | |
| bool | cmlabs::utils::SeedRandomValues (uint32 seedvalue=0) |
| Seed the pseudo-random generator. | |
| double | cmlabs::utils::RandomValue () |
| Uniform random double in [0,1). | |
| double | cmlabs::utils::RandomValue (double to) |
Uniform random double in [0,to). | |
| double | cmlabs::utils::RandomValue (double from, double to) |
Uniform random double in [from,to). | |
| double | cmlabs::utils::RandomValue (double from, double to, double interval) |
Uniform random double in [from,to) quantized to multiples of interval. | |
| int64 | cmlabs::utils::RandomInt (int64 from=0, int64 to=100) |
Uniform random integer in [from,to]. | |
| std::string | cmlabs::utils::BytifySize (double val) |
| Format a byte count with binary units, e.g. | |
| std::string | cmlabs::utils::BytifySizes (double val1, double val2) |
| Format two byte counts as "x / y" with matching units. | |
| std::string | cmlabs::utils::BytifyRate (double val) |
| Format a byte rate, e.g. | |
| std::string | cmlabs::utils::BytifyRates (double val1, double val2) |
| Format two byte rates as "x / y" with matching units. | |
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. | |
| bool | cmlabs::utils::DeleteRegistryKey (const char *key) |
| Delete a (leaf) registry key. | |
| bool | cmlabs::utils::CopyRegistryTree (const char *entry, const char *newName) |
| Recursively copy a registry subtree. | |
Variables | |
| uint32 | cmlabs::CleanShutdownInstanceCount = 0 |
| CleanShutdown | cmlabs::CleanShutdownInstance |
| char | cmlabs::utils::OSLocalHostName [1024] = {0} |
| char | cmlabs::utils::OSArchitectureName [1024] = {0} |
| char | cmlabs::utils::OSName [1024] = {0} |
Implementation of the cross-platform utility layer declared in Utils.h.
Contains the Windows/Linux/macOS implementations of synchronization primitives, shared memory, threads/processes, sockets, file and string helpers. See Utils.h for the API documentation.
Definition in file Utils.cpp.
| #define poly 0xEDB88320 |
Definition at line 6771 of file Utils.cpp.
Referenced by cmlabs::utils::CRC32().