Skip to content

R API

The Safe Runtime (R) is a portable runtime library for embedded applications.

The R library provides management for binary searching, buffering, error handling, events, events, files, hashing, lists, logging, memory, ssl, sockets, strings, and date/time functions. It also provides a foundation of safe routines for secure programming, that help to prevent buffer overflows and other security threats. The library can be used in both C and C++ programs.

The R library uses a set extended typedefs for common types. These include: bool, cchar, cvoid, uchar, short, ushort, int, uint, long, ulong, int32, uint32, int64, uint64, float, and double. The cchar type is a const char, cvoid is const void. Several types have "u" prefixes to denote unsigned qualifiers.

The library includes a memory allocator and global memory allocation handler.

The library provides support for fiber coroutines to enable parallel programming without callbacks or complex threads. The network APIs use fibers to transparently block the fiber and resume other fibers automatically. This enables a straight-line "blocking" programming paradigm while enabling other fibers to run as required.

Function Index

PUBLIC voidassert(bool cond)
 Asser that a condition is true.
PUBLIC intrAccessFile(cchar *path, int mode)
 Test if a file can be accessed with the given mode (F_OK, R_OK, W_OK, X_OK).
PUBLIC voidrAddDirectory(cchar *prefix, cchar *path)
 Add a directory to the directory lookup hash.
PUBLIC RName,*rAddFmtName(RHash *hash, cchar *name, int flags, cchar *fmt, ...)
 Add a name and formatted string value into the hash table.
PUBLIC RName,*rAddIntName(RHash *hash, cchar *name, int64 value)
 Add a name and integer value.
PUBLIC RName,*rAddName(RHash *table, cchar *name, void *ptr, int flags)
 Add a name and value into the hash table.
PUBLIC RName,*rAddNameSubstring(RHash *hash, cchar *name, ssize nameSize, char *value, ssize valueSize)
 Add a name and value substring into the hash table.
PUBLIC void,*rAlloc(size_t size)
 Allocate a block of memory.
PUBLIC REventrAllocEvent(RFiber *fiber, REventProc proc, void *data, Ticks delay, int flags)
 Allocate and schedule a new event to be run from the event loop.
PUBLIC voidrAllocException(int cause, size_t size)
 Signal a memory allocation exception.
PUBLIC RFiber,*rAllocFiber(cchar *name, RFiberProc fn, cvoid *data)
 Allocate a fiber coroutine object.
PUBLIC RHash,*rAllocHash(int size, int flags)
 Create a hash table.
PUBLIC RLock,*rAllocLock(void)
 Allocate a lock object.
PUBLIC RSocket,*rAllocSocket(void)
 Allocate a socket object.
PUBLIC void,*rAllocType(RType type)
 Allocate an object of a given type.
PUBLIC RWait,*rAllocWait(int fd)
 Allocate a wait object for a file descriptor.
PUBLIC intrBackupFile(cchar *path, int count)
 Backup the given file.
PUBLIC cchar,*rBasename(cchar *path)
 Return the basename (filename) portion of a filename.
PUBLIC voidrBreakpoint(void)
 Trigger a breakpoint.
PUBLIC RHash,*rCloneHash(RHash *master)
 Copy a hash table.
PUBLIC voidrCloseSocket(RSocket *sp)
 Close a socket.
PUBLIC intrConnectSocket(RSocket *sp, cchar *host, int port, Ticks deadline)
 Connect a client socket.
PUBLIC ssizerCopyFile(cchar *from, cchar *to, int mode)
 Copy a file.
PUBLIC intrCreateThread(cchar *name, void *proc, void *data)
 Create an O/S thread.
PUBLIC intrDaemonize(void)
 For the current process and run as a daemon.
PUBLIC char,*rDirname(char *path)
 Return the directory name portion of a filename.
PUBLIC intrEnter(bool *access, Ticks deadline)
 Enter a fiber critical section.
PUBLIC boolrFileExists(cchar *path)
 Test if a file exists.
PUBLIC intrFlushFile(int fd)
 Flush file buffers.
PUBLIC char,*rFormatLocalTime(cchar *format, Time time)
 Convert a time value to local time and format as a string.
PUBLIC char,*rFormatUniversalTime(cchar *format, Time time)
 Convert a time value to universal time and format as a string.
PUBLIC ssizerFprintf(FILE *fp, cchar *fmt, ...)
 Formatted print to the standard error channel.
PUBLIC voidrFree(void *ptr)
 Free a block of memory allocated via rAlloc.
PUBLIC voidrFreeFiber(RFiber *fiber)
 Free a fiber coroutine.
PUBLIC voidrFreeHash(RHash *hash)
 Free a hash table.
PUBLIC voidrFreeLock(RLock *mutex)
 Free a dynamically allocated lock object.
PUBLIC voidrFreeSocket(RSocket *sp)
 Free a socket object.
PUBLIC voidrFreeWait(RWait *wp)
 Free a wait object.
PUBLIC char,*rGetAppDir(void)
 Get the directory containing the application executable.
PUBLIC cchar,*rGetAppName(void)
 Get the application name defined via rSetAppName.
PUBLIC RThreadrGetCurrentThread(void)
 Get the current Thread.
PUBLIC char,*rGetCwd(void)
 Get the current application working directory.
PUBLIC char,*rGetDate(cchar *format)
 Get a string representation of the current date/time.
PUBLIC TicksrGetElapsedTicks(Ticks mark)
 Get the elapsed time since a ticks mark.
PUBLIC cchar,*rGetError(int error)
 Return a string representation of an R error code.
PUBLIC RFiber,*rGetFiber(void)
 Get the current fiber object.
PUBLIC void,*rGetFiberStack(void)
 Get the base address of the fiber stack.
PUBLIC char,*rGetFilePath(cchar *path)
 Get a file path name.
PUBLIC ssizerGetFileSize(cchar *path)
 Return the size of a file.
PUBLIC RList,*rGetFiles(cchar *base, cchar *pattern, int flags)
 Create a list of files in a directory or subdirectories that match the given wildcard pattern.
PUBLIC RList,*rGetFilesEx(RList *results, cchar *base, cchar *pattern, int flags)
 Get a list of files in a directory or subdirectories that match the given wildcard pattern.
PUBLIC intrGetHashLength(RHash *hash)
 Return the count of symbols in a symbol entry.
uint64rGetHiResTicks(void)
 Get the CPU tick count.
PUBLIC char,*rGetIsoDate(Time time)
 Get an ISO Date string representation of the given date/time.
PUBLIC RThreadrGetMainThread(void)
 Get the main Thread.
PUBLIC RName,*rGetNextName(RHash *hash, RName *next)
 Return the next symbol in a symbol entry.
PUBLIC intrGetOsError(void)
 Return the native O/S error code.
PUBLIC TicksrGetRemainingTicks(Ticks mark, Ticks timeout)
 Return the time remaining until a timeout has elapsed.
PUBLIC cchar,*rGetServerName(void)
 Get the application server name string.
PUBLIC intrGetSocketAddr(RSocket *sp, char *ipbuf, int ipbufLen, int *port)
 Get the locally bound socket IP address and port for the socket.
PUBLIC RSocketCustomrGetSocketCustom(void)
 Get the custom socket callback handler.
PUBLIC cchar,*rGetSocketError(RSocket *sp)
 Get the socket error.
PUBLIC SocketrGetSocketHandle(RSocket *sp)
 Get the socket file descriptor.
PUBLIC RWait,*rGetSocketWait(RSocket *sp)
 Get the socket wait handler.
PUBLIC intrGetState(void)
 Get the current R state.
PUBLIC char,*rGetTempFile(cchar *dir, cchar *prefix)
 Get a temp filename.
PUBLIC TicksrGetTicks(void)
 Get the system time.
PUBLIC TimerGetTime(void)
 Get the time.
PUBLIC boolrGetTimeouts(void)
 Return true if timeouts are enabled.
PUBLIC intrGetWaitFd(void)
 Get the global wait descriptor.
PUBLIC voidrGlobalLock(void)
 Globally lock the application.
PUBLIC voidrGlobalUnlock(void)
 Unlock the global mutex.
PUBLIC voidrGracefulStop(void)
 Gracefully stop the app.
PUBLIC RBuf,*rHashToBuf(RHash *hash, cchar *join)
 Convert a hash of strings to a single string in a buffer.
PUBLIC char,*rHashToJson(RHash *hash, int pretty)
 Convert a hash into JSON.
PUBLIC RBuf,*rHashToJsonBuf(RHash *hash, RBuf *buf, int pretty)
 Convert a hash into JSON in the given buffer.
PUBLIC char,*rHashToString(RHash *hash, cchar *join)
 Convert a hash of strings to a single string.
PUBLIC intrInit(RFiberProc fn, cvoid *arg)
 Initialize the runtime.
PUBLIC intrInitFibers(void)
 Initialize the fiber coroutine module.
PUBLIC intrInitFile(void)
 Create and initialze the file subsystem.
PUBLIC RLock,*rInitLock(RLock *mutex)
 Initialize a statically allocated lock object.
PUBLIC intrInitOs(void)
 Create and initialze the O/S dependent subsystem.
PUBLIC intrInitWait(void)
 Initialize the I/O wait subsystem.
PUBLIC boolrIsFileAbs(cchar *path)
 Determine if a file path is an absolute path.
PUBLIC boolrIsMain(void)
 Test if a fiber is the main fiber.
PUBLIC boolrIsSocketClosed(RSocket *sp)
 Test if the socket has been closed.
PUBLIC boolrIsSocketConnected(RSocket *sp)
 Determine if the socket has connected to a remote pper.
PUBLIC boolrIsSocketEof(RSocket *sp)
 Test if the other end of the socket has been closed.
PUBLIC boolrIsSocketSecure(RSocket *sp)
 Determine if the socket is secure.
PUBLIC char,*rJoinFile(cchar *base, cchar *other)
 Join file paths.
PUBLIC char,*rJoinFileBuf(char *buf, ssize bufsize, cchar *base, cchar *other)
 Join paths into a buffer.
PUBLIC voidrLeave(bool *access)
 Leave a fiber critical section.
PUBLIC intrListenSocket(RSocket *sp, cchar *host, int port, RSocketProc handler, void *arg)
 Listen on a server socket for incoming connections.
PUBLIC voidrLock(RLock *lock)
 Lock access.
PUBLIC boolrLookupEvent(REvent id)
 Lookup an event ID.
PUBLIC void,*rLookupName(RHash *hash, cchar *name)
 Lookup a symbol in the hash table.
PUBLIC RName,*rLookupNameEntry(RHash *hash, cchar *name)
 Lookup a symbol in the hash table and return the hash entry.
PUBLIC boolrMatchFile(cchar *path, cchar *pattern)
 Matach a file against a glob pattern.
PUBLIC void,*rMemdup(cvoid *ptr, size_t size)
 Duplicate a block of memory.
PUBLIC voidrMemoryBarrier(void)
 Perform a memory barrier where all queued writes are flushed to memory.
PUBLIC TimerParseIsoDate(cchar *when)
 Parse an ISO date string.
PUBLIC ssizerPrintf(cchar *fmt, ...)
 Formatted print.
PUBLIC char,*rReadFile(cchar *path, ssize *lenp)
 Read data from a file.
PUBLIC ssizerReadSocket(RSocket *sp, char *buf, ssize bufsize, Ticks deadline)
 Read from a socket.
PUBLIC ssizerReadSocketSync(RSocket *sp, char *buf, ssize bufsize)
 Read from a socket.
PUBLIC void,*rRealloc(void *ptr, size_t size)
 Allocate a block of memory.
PUBLIC intrRemoveName(RHash *hash, cchar *name)
 Remove a symbol entry from the hash table.
PUBLIC voidrResetSocket(RSocket *sp)
 Reset a socket.
PUBLIC void,*rResumeFiber(RFiber *fiber, void *result)
 Resume a fiber.
PUBLIC voidrResumeWait(RWait *wp, int mask)
 Release a waiting fiber waiting for an event.
PUBLIC char,*rRun(cchar *command, int *status)
 Run a command using the system shell.
PUBLIC intrRunEvent(REvent id)
 Run an event now.
PUBLIC TicksrRunEvents(void)
 Run due events.
PUBLIC intrServiceEvents(void)
 Service events.
PUBLIC voidrSetFiberLimits(int maxFibers)
 Set the fiber limits.
PUBLIC voidrSetFiberStack(ssize size)
 Set the default fiber stack size.
PUBLIC voidrSetMemHandler(RMemProc handler)
 Define a global memory exhaustion handler.
PUBLIC voidrSetOsError(int error)
 Set the O/S error code.
PUBLIC voidrSetSocketBlocking(RSocket *sp, bool on)
 Set a socket into blocking I/O mode.
PUBLIC voidrSetSocketCerts(RSocket *sp, cchar *ca, cchar *key, cchar *cert, cchar *revoke)
 Configure the socket TLS certificates.
PUBLIC voidrSetSocketCiphers(RSocket *sp, cchar *ciphers)
 Set the ciphers to use for communications.
PUBLIC voidrSetSocketCustom(RSocketCustom custom)
 Set the socket custom configuration callback.
PUBLIC voidrSetSocketDefaultCerts(cchar *ca, cchar *key, cchar *cert, cchar *revoke)
 Configure the default TLS certificates.
PUBLIC voidrSetSocketDefaultCiphers(cchar *ciphers)
 Set the default TLS ciphers to use for communications.
PUBLIC voidrSetSocketDefaultVerify(int verifyPeer, int verifyIssuer)
 Set the default TLS verification parameters.
PUBLIC intrSetSocketError(RSocket *sp, cchar *fmt, ...)
 Set the socket error message.
PUBLIC voidrSetSocketVerify(RSocket *sp, int verifyPeer, int verifyIssuer)
 Set the socket TLS verification parameters.
PUBLIC voidrSetSocketWaitMask(RSocket *sp, int64 mask, Ticks deadline)
 Update the wait mask for a socket.
PUBLIC voidrSetState(int state)
 Set the R state.
PUBLIC voidrSetTimeouts(bool on)
 Control timeouts.
PUBLIC voidrSetWaitHandler(RWait *wp, RWaitProc handler, cvoid *arg, int64 mask, Ticks deadline)
 Define a wait handler function on a wait object.
PUBLIC voidrSetWaitMask(RWait *wp, int64 mask, Ticks deadline)
 Update the wait mask for a wait handler.
PUBLIC voidrSignal(cchar *name, cvoid *arg)
 Signal watches of a named event.
PUBLIC voidrSignalSync(cchar *name, cvoid *arg)
 Signal watches of a named event synchronously (blocking).
PUBLIC voidrSleep(Ticks ticks)
 Sleep a fiber for the requested number of milliseconds.
PUBLIC char,*rSnprintf(char *buf, ssize maxsize, cchar *fmt, ...)
 Format a string into a buffer.
PUBLIC intrSpawnFiber(cchar *name, RFiberProc fn, void *arg)
 Spawn a fiber coroutine.
PUBLIC void,*rSpawnThread(RThreadProc fn, void *arg)
 Spawn an O/S thread and wait until it completes.
PUBLIC REventrStartEvent(REventProc proc, void *data, Ticks delay)
 Start a callback event.
PUBLIC voidrStartFiber(RFiber *fiber, void *data)
 Start a fiber coroutine.
PUBLIC voidrStop(void)
 Immediately stop the app.
PUBLIC intrStopEvent(REvent id)
 Stop an event.
PUBLIC voidrTermFibers(void)
 Terminate the fiber coroutine module.
PUBLIC voidrTermFile(void)
 Stop the file subsystem.
PUBLIC voidrTermLock(RLock *mutex)
 Terminate a statically allocated lock object.
PUBLIC voidrTermOs(void)
 Stop the O/S dependent subsystem.
PUBLIC voidrTermWait(void)
 Terminate the I/O wait subsystem.
PUBLIC boolrTryLock(RLock *lock)
 Attempt to lock access.
PUBLIC voidrUnlock(RLock *lock)
 Unlock a mutex.
PUBLIC char,*rVsnprintf(char *buf, ssize maxsize, cchar *fmt, va_list args)
 Format a string into a buffer.
PUBLIC intrWait(Ticks timeout)
 Wait for an I/O event.
PUBLIC intrWaitForIO(RWait *wp, int mask, Ticks deadline)
 Wait for an IO event on a wait object.
PUBLIC voidrWakeup(void)
 Wakeup the event loop.
PUBLIC intrWalkDir(cchar *dir, cchar *pattern, RWalkDirProc callback, void *arg, int flags)
 Walk a directory tree and invoke a callback for each path that matches a given pattern.
PUBLIC voidrWatch(cchar *name, RWatchProc proc, void *data)
 Watch for a named event to happen.
PUBLIC voidrWatchOff(cchar *name, RWatchProc proc, void *data)
 Stop watching for a named event to happen.
PUBLIC ssizerWriteFile(cchar *path, cchar *buf, ssize len, int mode)
 Write data to a file.
PUBLIC intrWritePid(void)
 Write the current process pid to /var/run.
PUBLIC ssizerWriteSocket(RSocket *sp, cvoid *buf, ssize bufsize, Ticks deadline)
 Write to a socket.
PUBLIC ssizerWriteSocketSync(RSocket *sp, cvoid *buf, ssize len)
 Write to a socket.
PUBLIC void,*rYieldFiber(void *value)
 Yield a fiber back to the main fiber.
PUBLIC RbTree,*rbAlloc(int flags, RbCompare compare, RbFree free, void *arg)
 Allocate a red/black tree.
PUBLIC RbNode,*rbFirst(RbTree *rbt)
 Return the lexically first node.
PUBLIC voidrbFree(RbTree *rbt)
 Free a red/black tree.
PUBLIC RbNode,*rbInsert(RbTree *rbt, void *data)
 Insert a new data item in the tree.
PUBLIC RbNode,*rbLookup(RbTree *rbt, cvoid *data, void *ctx)
 Lookup a data item.
PUBLIC RbNode,*rbLookupFirst(RbTree *rbt, cvoid *data, void *ctx)
 Return the lexically first matching node.
PUBLIC RbNode,*rbLookupNext(RbTree *rbt, RbNode *node, cvoid *data, void *ctx)
 Return the next matching node after the given node.
PUBLIC RbNode,*rbNext(RbTree *rbt, RbNode *node)
 Return the next node in sequence.
PUBLIC void,*rbRemove(RbTree *rbt, RbNode *node, int keep)
 Remove a data item from the tree.
PUBLIC char,*scamel(cchar *str)
 Create a camel case version of the string.
PUBLIC intscaselesscmp(cchar *s1, cchar *s2)
 Compare strings ignoring case.
PUBLIC boolscaselessmatch(cchar *s1, cchar *s2)
 Compare strings ignoring case.
PUBLIC char,*schr(cchar *str, int c)
 Find a character in a string.
PUBLIC char,*sclone(cchar *str)
 Clone a string.
PUBLIC char,*scloneNull(cchar *str)
 Clone a string and preserve NULLs.
PUBLIC intscmp(cchar *s1, cchar *s2)
 Compare strings.
PUBLIC char,*scontains(cchar *str, cchar *pattern)
 Find a pattern in a string.
PUBLIC ssizescopy(char *dest, ssize destMax, cchar *src)
 Copy a string.
PUBLIC cchar,*sends(cchar *str, cchar *suffix)
 Test if the string ends with a given pattern.
PUBLIC char,*sfmt(cchar *fmt, ...)
 Format a string.
PUBLIC char,*sfmtbuf(char *buf, ssize maxSize, cchar *fmt, ...)
 Format a string into a static buffer.
PUBLIC char,*sfmtbufv(char *buf, ssize maxSize, cchar *fmt, va_list args)
 Format a string into a statically allocated buffer.
PUBLIC char,*sfmtv(cchar *fmt, va_list args)
 Format a string.
PUBLIC uintshash(cchar *str, ssize len)
 Compute a hash code for a string.
PUBLIC uintshashlower(cchar *str, ssize len)
 Compute a caseless hash code for a string.
PUBLIC char,*sitos(int64 value)
 Convert an integer to a string.
PUBLIC char,*sitosbuf(char *buf, ssize size, int64 value, int radix)
 Convert an integer to a string buffer.
PUBLIC char,*sitosradix(int64 value, int radix)
 Convert an integer to a string.
PUBLIC char,*sjoin(cchar *str, ...)
 Catenate strings.
PUBLIC char,*sjoinArgs(int argc, cchar **argv, cchar *sep)
 Join an array of strings.
PUBLIC ssizesjoinbuf(char *buf, ssize bufsize, cchar *str1, cchar *str2)
 Catenate strings into a buffer.
PUBLIC char,*sjoinfmt(cchar *str, cchar *fmt, ...)
 Join a formatted string to an existing string.
PUBLIC char,*sjoinv(cchar *str, va_list args)
 Catenate strings.
PUBLIC ssizeslen(cchar *str)
 Return the length of a string.
PUBLIC char,*slower(char *str)
 Convert a string to lower case.
PUBLIC boolsmatch(cchar *s1, cchar *s2)
 Compare strings.
PUBLIC intsncaselesscmp(cchar *s1, cchar *s2, ssize len)
 Compare strings ignoring case.
PUBLIC char,*sncaselesscontains(cchar *str, cchar *pattern, ssize limit)
 Find a pattern in a string with a limit using a caseless comparison.
PUBLIC char,*snclone(cchar *str, ssize len)
 Clone a substring.
PUBLIC intsncmp(cchar *s1, cchar *s2, ssize len)
 Compare strings.
PUBLIC char,*sncontains(cchar *str, cchar *pattern, ssize limit)
 Find a pattern in a string with a limit.
PUBLIC ssizesncopy(char *dest, ssize destMax, cchar *src, ssize len)
 Copy characters from a string.
PUBLIC char,*spbrk(cchar *str, cchar *set)
 Locate the a character from a set in a string.
PUBLIC char,*sptok(char *str, cchar *pattern, char **nextp)
 Tokenize a string.
PUBLIC char,*srchr(cchar *str, int c)
 Find a character in a string by searching backwards.
PUBLIC char,*srejoin(char *buf, ...)
 Append strings to an existing string and reallocate as required.
PUBLIC char,*srejoinv(char *buf, va_list args)
 Append strings to an existing string and reallocate as required.
PUBLIC char,*ssplit(char *str, cchar *delim, char **last)
 Split a string at a delimiter.
PUBLIC ssizesspn(cchar *str, cchar *set)
 Find the end of a spanning prefix.
PUBLIC boolsstarts(cchar *str, cchar *prefix)
 Test if the string starts with a given pattern.
PUBLIC char,*ssub(cchar *str, ssize offset, ssize length)
 Create a substring.
PUBLIC char,*stemplate(cchar *str, void *tokens)
 Replace template tokens in a string with values from a lookup table.
PUBLIC char,*stitle(cchar *str)
 Create a Title Case version of the string.
PUBLIC doublestod(cchar *str)
 Convert a string to a double floating point value.
PUBLIC doublestof(cchar *str)
 Convert a string to a double.
PUBLIC int64stoi(cchar *str)
 Convert a string to an integer.
PUBLIC int64stoiradix(cchar *str, int radix, int *err)
 Convert a string to an integer.
PUBLIC char,*stok(char *str, cchar *delim, char **last)
 Tokenize a string.
PUBLIC struct,RList,*stolist(cchar *src)
 String to list.
PUBLIC char,*strim(char *str, cchar *set, int where)
 Trim a string.
PUBLIC char,*supper(char *str)
 Convert a string to upper case.
PUBLIC uint64svalue(cchar *value)
 Parse a value string.
PUBLIC voidszero(char *str)
 Erase the contents of a string.

Typedef Index

REventEvent Subsystem.
REventProcCallback function for events.
RFiberFiber state.
RFiberProcFiber entry point function.
RFileR File Module.
RHashHash table structure.
RHashProcHashing function to use for the table.
RLockMultithreading lock control structure.
RMemProcMemory exhaustion callback procedure.
RNamePer item structure.
RStringR String Module.
RThreadProcThread entry point function.
RWaitWait object.
RWaitProcCallback function for IO wait events.
RWalkDirProcCallback function for rWalkDir.
RWatchProcCallback function for watched events.
RbCompareCallback to compare a data nodes.
RbFreeCallback to free a nodes associated data.
SocketArgument for sockets.
size_tUnsigned integral type.
time_tUnsigned time type.

Defines

#defineITERATE_INDEX    node = rbLookupFirst(rbt, data, ctx); node; node = rbLookupNext(rbt, node, \ data, ctx)
 Traverse an index over matching nodes.
#defineITERATE_TREE   node = rbFirst(rbt); node; node = rbNext(rbt, node)
#defineR_DEFAULT_DATE   "%a %b %d %T %Y %Z"
 Default date format used in rFormatLocalTime/rFormatUniversalTime when no format supplied E.g.
#defineR_DYNAMIC_NAME   0x8
 Dynamic name provided, hash will free.
#defineR_DYNAMIC_VALUE   0x1
 Dynamic (allocated) value provided, hash/list will free.
#defineR_EVENT_ASYNC   1
 Windows async select.
#defineR_EVENT_EPOLL   2
 epoll_wait.
#defineR_EVENT_FAST   0x1
 Fast event flag - must not block and runs off main fiber.
#defineR_EVENT_KQUEUE   3
 BSD kqueue.
#defineR_EVENT_SELECT   4
 traditional select().
#defineR_HASH_CASELESS   0x40
 Ignore case in comparisons.
#defineR_IO   0x6
 Wait mask for readable or writeable events.
#defineR_MEM_FAIL   0x4
 Memory allocation failed - immediate exit.
#defineR_MEM_LIMIT   0x2
 Memory use exceeds memory limit - invoking policy.
#defineR_MEM_STACK   0x10
 Too many fiber stack.
#defineR_MEM_TOO_BIG   0x8
 Memory allocation request is too big - immediate exit.
#defineR_MEM_WARNING   0x1
 Memory use exceeds warnHeap level limit.
#defineR_MODIFIED   0x200
 Wait mask for modify events.
#defineR_READABLE   0x2
 Wait mask for readable events.
#defineR_SOCKET_CLOSED   0x1
 RSocket has been closed.
#defineR_SOCKET_CONFIG_TLS   1
 Custom callback to configure TLS.
#defineR_SOCKET_EOF   0x2
 Seen end of file.
#defineR_SOCKET_LISTENER   0x4
 RSocket is server listener.
#defineR_SOCKET_SERVER   0x8
 Socket is on the server-side.
#defineR_STATIC_NAME   0x10
 Static name provided no need to clone or free.
#defineR_STATIC_VALUE   0x2
 Static value provided, no need to clone or free.
#defineR_TEMPORAL_NAME   0x20
 Temporal name provided, hash will clone and free.
#defineR_TEMPORAL_VALUE   0x4
 Temporal value provided, hash/list will clone and free.
#defineR_TIMEOUT   0x400
 Wait mask for timeout.
#defineR_TLS_HAS_AUTHORITY   0x1
 Signal to the custom callback that authority certs are available.
#defineR_TRIM_BOTH   0x3
 Flag for strim to trim from both the start and the end of the string.
#defineR_TRIM_END   0x2
 Flag for strim to trim from the end of the string.
#defineR_TRIM_START   0x1
 Flag for strim to trim from the start of the string.
#defineR_WALK_DEPTH_FIRST   0x1
 Flag for rGetFiles to do a depth-first traversal.
#defineR_WALK_DIRS   0x4
 Include hidden files starting with "." except for "." and "..".
#defineR_WALK_FILES   0x8
 Include hidden files starting with "." except for "." and "..".
#defineR_WALK_HIDDEN   0x2
 Include hidden files starting with "." except for "." and "..".
#defineR_WALK_MISSING   0x20
 Allow walking missing paths.
#defineR_WALK_RELATIVE   0x10
 Return paths relative to the original path.
#defineR_WRITABLE   0x4
 Wait mask for writable events.
#defineRB_DUP   0x1
 Flags for rbAlloc to permit duplicate keys.

Typedefs

typedef int(* RbCompare) (cvoid *n1, cvoid *n2, cvoid *ctx)

Callback to compare a data nodes.

Description:
The comparison function may perform a simple "strcmp" style comparison function or it may perform a modified comparison using the supplied context information. For example: a comparison could perform a "startsWith" style comparison. The context argument can control the type of comparison that is performed.
Parameters:
n1Reference to first item.
n2Reference to item to compare.
ctxContext provided to rbLookup.
Returns:
Return -1 if n1 is lexically less than n2. Zero if equal and 1 if n1 is greater than n2.
API Stability:
Evolving.

typedef void(* RbFree) (void *arg, void *data)

Callback to free a nodes associated data.

Parameters:
dataReference to the associated data for a node.
API Stability:
Evolving.

typedef int64 REvent

Event Subsystem.

Description:
R provides a simple based eventing mechanism. Events are described by REvent objects which are created and queued via rStartEvent. Events are scheduled once unless restarted via rRestartEvent.
API Stability:
Internal.

typedef void(* REventProc) (void *data)

Callback function for events.

Parameters:
dataOpaque data argument.
API Stability:
Evolving.

typedef void(* RFiberProc) (void *data)

Fiber entry point function.

Parameters:
dataCustom function argument.
API Stability:
Evolving.

typedef uint(* RHashProc) (cvoid *name, ssize len)

Hashing function to use for the table.

Parameters:
nameName to hash.
lenLength of the name to hash.
Returns:
An integer hash index.
API Stability:
Internal.

typedef void(* RMemProc) (int cause, size_t size)

Memory exhaustion callback procedure.

Parameters:
causeThe cause of the memory failure.
sizeThe size of the failing block allocation.

typedef void *(* RThreadProc) (void *data)

Thread entry point function.

Parameters:
dataCustom function argument.
Returns:
Value to pass back from rSpawnThread.
API Stability:
Evolving.

typedef void(* RWaitProc) (cvoid *data, int mask)

Callback function for IO wait events.

Parameters:
dataOpaque data argument.
maskIO event selection mask.
API Stability:
Evolving.

typedef int(* RWalkDirProc) (void *arg, cchar *path, int flags)

Callback function for rWalkDir.

Parameters:
argArgument supplied to rWalkDir.
pathCurrent filename path to walk.
flagsFlags supplied to rWalkDir.
API Stability:
Evolving.

typedef void(* RWatchProc) (cvoid *data, cvoid *arg)

Callback function for watched events.

Parameters:
dataOpaque data argument supplied via rWatchEvent.
argWatched event arg passed via rSignal.
API Stability:
Evolving.

typedef long size_t

Unsigned integral type.

Equivalent in size to void*

typedef int Socket

Argument for sockets.

typedef unsigned long time_t

Unsigned time type.

Time in seconds since Jan 1, 1970

RFiber

Fiber state.

API Stability:
Evolving.
Fields:

RFile

R File Module.

See Also:
Fields:
API Stability:
Internal.

RHash

Hash table structure.

Description:
The hash structure supports growable hash tables collision resistant hashes.
Fields:
int *buckets Hash collision bucket table.
uintflags Hash control flags.
RHashProcfn Hash function.
intfree Free list of names.
uintlength Number of names in the hash.
struct RName *names Hash items.
uintnumBuckets Number of buckets in the first-level hash.
uintsize Size of allocated names.
See Also:
RName
API Stability:
Evolving.

RLock

Multithreading lock control structure.

Description:
RLock is used for multithread locking in multithreaded applications.
Fields:
API Stability:
Evolving.

RName

Per item structure.

Fields:
uintcustom Custom data bits.
uintflags Name was allocated.
char *name Hash name.
intnext Next name in hash chain or next free if on free list.
void *value Pointer to data.

RString

R String Module.

Description:
The RT provides a suite of r ascii string manipulation routines to help prevent buffer overflows and other potential security traps.
Fields:
See Also:
API Stability:
Internal.

RWait

Wait object.

Description:
The RWait service provides a flexible IO waiting mechansim.
Fields:
cvoid *arg Argument to pass to the handler.
Ticksdeadline System deadline time to wait until.
intfd File descriptor to wait upon.
RFiber *fiber Current fiber for rWaitForIO.
RWaitProchandler Handler function to invoke as the entrypoint in the fiber coroute.
intmask Current event mask.
API Stability:
Evolving.

Functions

PUBLIC void assert (bool cond)

Asser that a condition is true.

Parameters:
condBoolean result of a conditional test.
API Stability:
Evolving.

PUBLIC int rAccessFile (cchar *path, int mode)

Test if a file can be accessed with the given mode (F_OK, R_OK, W_OK, X_OK).

Parameters:
pathFilename to read.
modeSet to F_OK, R_OK, W_OK, or X_OK.
Returns:
Zero if successful, otherwise a negative value.
API Stability:
Evolving.

PUBLIC void rAddDirectory (cchar *prefix, cchar *path)

Add a directory to the directory lookup hash.

Parameters:
prefixThe directory prefix name.
pathThe corresponding directory.
API Stability:
Evolving.

PUBLIC RName,* rAddFmtName (RHash *hash, cchar *name, int flags, cchar *fmt, ...)

Add a name and formatted string value into the hash table.

Description:
Associate an arbitrary value with a string name and inser into the hash table.
Parameters:
hashHash table returned via rAllocHash.
nameString name to associate with the data.
flagsSet flags to R_STATIC_NAME if providing statically allocated names. Set to R_TEMPORAL_NAME if the hash must copy the names. Set to R_DYNAMIC_NAME when providing allocated names that the hash may use, own and ultimately free when the hash is free. Set flags to R_STATIC_VALUE if providing statically allocated values. Set to R_DYNAMIC_VALUE when providing allocated values that the hash may use, own and ultimately free when the hash is free. If flags are zero, the flags provided to rAllocHash are used.
fmtPrintf style format string.
...Variable arguments for the format string.
Returns:
Added RName reference.
API Stability:
Evolving.

PUBLIC RName,* rAddIntName (RHash *hash, cchar *name, int64 value)

Add a name and integer value.

Parameters:
hashHash table returned via rAllocHash.
nameString name to associate with the data.
valueA 64 bit integer value.
Returns:
Added RName reference.
API Stability:
Evolving.

PUBLIC RName,* rAddName (RHash *table, cchar *name, void *ptr, int flags)

Add a name and value into the hash table.

Description:
Associate an arbitrary value with a string name and inser into the hash table.
Parameters:
tableHash table returned via rAllocHash.
nameString name to associate with the data.
ptrArbitrary pointer to associate with the name in the table.
flagsSet flags to R_STATIC_NAME if providing statically allocated names. Set to R_TEMPORAL_NAME if the hash must copy the names. Set to R_DYNAMIC_NAME when providing allocated names that the hash may use, own and ultimately free when the hash is free. Set flags to R_STATIC_VALUE if providing statically allocated values. Set to R_DYNAMIC_VALUE when providing allocated values that the hash may use, own and ultimately free when the hash is free. If flags are zero, the flags provided to rAllocHash are used.
Returns:
Added RName reference.
API Stability:
Evolving.

PUBLIC RName,* rAddNameSubstring (RHash *hash, cchar *name, ssize nameSize, char *value, ssize valueSize)

Add a name and value substring into the hash table.

Description:
Associate an arbitrary value with a string name and inser into the hash table. The flags used are: R_DYNAMIC_NAME | R_DYNAMIC_VALUE.
Parameters:
hashHash table returned via rAllocHash.
nameString name to associate with the data.
nameSizeSize of the name string.
valueValue string to store.
valueSizeLength of string value.
Returns:
Added RName reference.
API Stability:
Evolving.

PUBLIC void,* rAlloc (size_t size)

Allocate a block of memory.

Description:
This is the lowest level of memory allocation routine. Memory is freed via rFree.
Parameters:
sizeSize of the memory block to allocate.
Returns:
Returns a pointer to the allocated block. If memory is not available the memory exhaustion handler will be invoked.
Remarks:
Do not mix calls to rAlloc and malloc.
API Stability:
Evolving.

PUBLIC REvent rAllocEvent (RFiber *fiber, REventProc proc, void *data, Ticks delay, int flags)

Allocate and schedule a new event to be run from the event loop.

Description:
Allocate an event to run a callback via the event loop. The safe runtime (R) is not THREAD SAFE in general. A few APIs are THREAD SAFE to enable data interchange between R and foreign threads.

This API is THREAD SAFE and may be called by foreign threads provided the caller supplies a proc function and ensures the fiber is still valid. This routine is the ONLY safe way to invoke R services from a foreign-thread.
Parameters:
fiberFiber object.
procFunction to invoke when the event is run.
dataData to associate with the event and stored in event->data.
delayTime in milliseconds used by continuous events between firing of the event.
flagsSet to R_EVENT_FAST for a "faster" event. Fast events must not block or yield as they run directly off the main service fiber.
Returns:
The event object. If called from a foreign thread, note that the event may have already run n return.
API Stability:
Internal.

PUBLIC void rAllocException (int cause, size_t size)

Signal a memory allocation exception.

Description:
R uses a global memory allocaction error handler. If doing direct malloc() allocations that fail, call this routine to signal the memory failure and run the allocation handler.
Parameters:
causeSet to R_MEM_WARNING, R_MEM_LIMIT, R_MEM_FAIL or R_MEM_TO_BIG.
sizeSize in bytes of the failing allocation.
API Stability:
Evolving.

PUBLIC RFiber,* rAllocFiber (cchar *name, RFiberProc fn, cvoid *data)

Allocate a fiber coroutine object.

Description:
This allocates a new fiber coroutine. Use rStartFiber to launch.
Parameters:
nameFiber name.
fnFiber entry point.
dataEntry point argument.
Returns:
A fiber object.
API Stability:
Internal.

PUBLIC RHash,* rAllocHash (int size, int flags)

Create a hash table.

Description:
Creates a hash table that can store arbitrary objects associated with string names.
Parameters:
sizeEstimated number of names in the hash table. Set to 0 or -1 to get a default (small) hash table.
flagsSet flags to R_STATIC_NAME if providing statically allocated names. Set to R_TEMPORAL_NAME if the hash must copy the names. Set to R_DYNAMIC_NAME when providing allocated names that the hash may use, own and ultimately free when the hash is free. Set flags to R_STATIC_VALUE if providing statically allocated values. Set to R_DYNAMIC_VALUE when providing allocated values that the hash may use, own and ultimately free when the hash is free. Set to R_TEMPORAL_VALUE when providing a string value that the hash must clone and free. Set to R_HASH_CASELESS for case insensitive matching for names. The default flags is: R_STATIC_NAME | R_STATIC_VALUE.
Returns:
Returns a pointer to the allocated hash table.
API Stability:
Evolving.

PUBLIC RLock,* rAllocLock (void )

Allocate a lock object.

Description:
This call creates a lock object that can be used in rLock rTryLock and rUnlock calls. This routine is THREAD SAFE.
API Stability:
Evolving.

PUBLIC RSocket,* rAllocSocket (void )

Allocate a socket object.

Returns:
A socket object instance.
API Stability:
Evolving.

PUBLIC void,* rAllocType (RType type)

Allocate an object of a given type.

Description:
Allocates a zeroed block of memory large enough to hold an instance of the specified type.
Parameters:
typeRType of the object to allocate.
Returns:
Returns a pointer to the allocated block. If memory is not available the memory allocation handler will be invoked.
API Stability:
Evolving.

PUBLIC RWait,* rAllocWait (int fd)

Allocate a wait object for a file descriptor.

Parameters:
fdFile descriptor.
Returns:
A RWait object.
API Stability:
Evolving.

PUBLIC int rBackupFile (cchar *path, int count)

Backup the given file.

Description:
This creates backup copies of the file using the form: filename-d.ext.
Parameters:
pathFilename to backup.
countNumber of backup copies to keep.
API Stability:
Evolving.

PUBLIC RbTree,* rbAlloc (int flags, RbCompare compare, RbFree free, void *arg)

Allocate a red/black tree.

Parameters:
flagsSet to RB_DUP if you wish to store duplicate nodes.
compareCallback to compare two nodes.
freeCallback to free a node's item data.
argArg to pass to callback.
Returns:
An RbTree instance.
API Stability:
Evolving.

PUBLIC cchar,* rBasename (cchar *path)

Return the basename (filename) portion of a filename.

Parameters:
pathFilename to examine.
Returns:
A pointer to the basename portion of the supplied filename path. This call does not allocate a new string.
API Stability:
Evolving.

PUBLIC RbNode,* rbFirst (RbTree *rbt)

Return the lexically first node.

Parameters:
rbtRbTree allocated via rbAlloc.
Returns:
The first node.
API Stability:
Evolving.

PUBLIC void rbFree (RbTree *rbt)

Free a red/black tree.

Parameters:
rbtRbTree to free. Allocated via rbAlloc.
API Stability:
Evolving.

PUBLIC RbNode,* rbInsert (RbTree *rbt, void *data)

Insert a new data item in the tree.

Parameters:
rbtRbTree allocated via rbAlloc.
dataUser data to store in the tree. The data should contain the lookup key value for the data. The comparison callback will be passed the data and it should be able to extract the key from the data.
Returns:
The inserted node.
API Stability:
Evolving.

PUBLIC RbNode,* rbLookup (RbTree *rbt, cvoid *data, void *ctx)

Lookup a data item.

Parameters:
rbtRbTree allocated via rbAlloc.
dataUser data item to search for. This is passed to the comparison callback supplied when calling rbOpen.
ctxContext to provide to the comparison callback.
Returns:
The located node or NULL if not found. If there are multiple matching nodes, the first node encountered is returned which may not be the first lexically. If you need the first item lexically, use rbLookupFirst.
API Stability:
Evolving.

PUBLIC RbNode,* rbLookupFirst (RbTree *rbt, cvoid *data, void *ctx)

Return the lexically first matching node.

Parameters:
rbtRbTree allocated via rbAlloc.
dataUser data item to search for. This is passed to the comparison callback supplied when calling rbOpen.
ctxContext to provide to the comparison callback.
Returns:
The located node or NULL if not found. If there are multiple matching nodes, the first node encountered is returned which may not be the first lexically. If you need the first item lexically, use rbLookupFirst.
API Stability:
Evolving.

PUBLIC RbNode,* rbLookupNext (RbTree *rbt, RbNode *node, cvoid *data, void *ctx)

Return the next matching node after the given node.

Description:
This call finds the next matching node after the current node. It is assumed that the given node matches the supplied user data.
Parameters:
rbtRbTree allocated via rbAlloc.
nodeStarting node for the search.
dataUser data item to search for. This is passed to the comparison callback supplied when calling rbOpen.
ctxContext to provide to the comparison callback.
Returns:
The located node or NULL if not found. If there are multiple matching nodes, the first node encountered is returned which may not be the first lexically. If you need the first item lexically, use rbLookupFirst.
API Stability:
Evolving.

PUBLIC RbNode,* rbNext (RbTree *rbt, RbNode *node)

Return the next node in sequence.

Parameters:
rbtRbTree allocated via rbAlloc.
nodeStarting node.
Returns:
The next node in the tree.
API Stability:
Evolving.

PUBLIC void rBreakpoint (void )

Trigger a breakpoint.

Description:
This routine is invoked for asserion errors from rAssert and errors from rError. It is useful in debuggers as breakpoint location for detecting errors.
API Stability:
Evolving.

PUBLIC void,* rbRemove (RbTree *rbt, RbNode *node, int keep)

Remove a data item from the tree.

Parameters:
rbtRbTree allocated via rbAlloc.
nodeNode to remove. The node is identified by calling rbLookup.
keepIf true, the data item will not be freed. Otherwise the free callback will be invoked on the data item.
Returns:
The node data item.
API Stability:
Evolving.

PUBLIC RHash,* rCloneHash (RHash *master)

Copy a hash table.

Parameters:
masterOriginal hash table.
Returns:
Returns a pointer to the new allocated hash table.
API Stability:
Evolving.

PUBLIC void rCloseSocket (RSocket *sp)

Close a socket.

Description:
Close a socket.
Parameters:
spSocket object returned from rAllocSocket.
API Stability:
Evolving.

PUBLIC int rConnectSocket (RSocket *sp, cchar *host, int port, Ticks deadline)

Connect a client socket.

Description:
Open a client connection. May be called from a fiber or from main.
If using TLS, this must only be called from a fiber.
Parameters:
spSocket object returned via rAllocSocket.
hostHost or IP address to connect to.
portTCP/IP port number to connect to.
deadlineMaximum system time for connect to wait until completion. Use rGetTicks() + elapsed to create a deadline. Set to 0 for no deadline.
Returns:
Zero if successful.
API Stability:
Evolving.

PUBLIC ssize rCopyFile (cchar *from, cchar *to, int mode)

Copy a file.

Description:
Copy a file to a destination path.
Parameters:
fromSource file name.
toDestination file name.
modePosix file mode on created file.
Returns:
Number of bytes copied or negative error code.
API Stability:
Evolving.

PUBLIC int rCreateThread (cchar *name, void *proc, void *data)

Create an O/S thread.

Parameters:
nameDescriptive name for the thread.
procThread main function to invoke.
dataArgument to proc.
API Stability:
Evolving.

PUBLIC int rDaemonize (void )

For the current process and run as a daemon.

API Stability:
Evolving.

PUBLIC char,* rDirname (char *path)

Return the directory name portion of a filename.

Description:
This trims off the basename portion of the path by modifying the supplied path.
Parameters:
pathFilename to examine and modify.
Returns:
A pointer to the dirname portion of the supplied filename path. This call does not allocate a new string and the caller must not free.
API Stability:
Evolving.

PUBLIC int rEnter (bool *access, Ticks deadline)

Enter a fiber critical section.

Description:
This routine supports fiber critical sections where a fiber can sleep and ensure no other fiber executes the routine at the same time. The second and subsequent fibers will yield on this call until the first fiber leaves the critical section.
Parameters:
accessPointer to a boolean initialized to false.
deadlineTime in ticks to wait for access. Set to zero for an infinite wait.
Returns:
Zero if access is granted.
API Stability:
Prototype.

PUBLIC bool rFileExists (cchar *path)

Test if a file exists.

Parameters:
pathFilename to test.
Returns:
True if the file exists.
API Stability:
Evolving.

PUBLIC int rFlushFile (int fd)

Flush file buffers.

Parameters:
fdO/S file descriptor.
Returns:
Zero if successful.
API Stability:
Evolving.

PUBLIC char,* rFormatLocalTime (cchar *format, Time time)

Convert a time value to local time and format as a string.

Description:
R replacement for ctime.
Parameters:
formatTime format string. See rFormatUniversalTime for time formats.
timeTime to format. Use rGetTime to retrieve the current time.
Returns:
The formatting time string. Caller msut free.
API Stability:
Evolving.

PUBLIC char,* rFormatUniversalTime (cchar *format, Time time)

Convert a time value to universal time and format as a string.

Description:
Format a time string. This uses strftime if available and so the supported formats vary from platform to platform. Strftime should supports some of these these formats described below.
Parameters:
formatTime format string
A ... full weekday name (Monday)
a ... abbreviated weekday name (Mon)
B ... full month name (January)
b ... abbreviated month name (Jan)
C ... century. Year / 100. (0-N)
c ... standard date and time representation
D ... date (m/d/y)
d ... day-of-month (01-31)
e ... day-of-month with a leading space if only one digit ( 1-31)
F ... same as Y-m-d
H ... hour (24 hour clock) (00-23)
h ... same as b
I ... hour (12 hour clock) (01-12)
j ... day-of-year (001-366)
k ... hour (24 hour clock) (0-23)
l ... the hour (12-hour clock) as a decimal number (1-12); single digits are preceded by a blank.
M ... minute (00-59)
m ... month (01-12)
n ... a newline
P ... lower case am / pm
p ... AM / PM
R ... same as H:M
r ... same as H:M:S p
S ... second (00-59)
s ... seconds since epoch
T ... time (H:M:S)
t ... a tab.
U ... week-of-year, first day sunday (00-53)
u ... the weekday (Monday as the first day of the week) as a decimal number (1-7).
v ... is equivalent to `e-b-Y'.
W ... week-of-year, first day monday (00-53)
w ... weekday (0-6, sunday is 0)
X ... standard time representation
x ... standard date representation
Y ... year with century
y ... year without century (00-99)
Z ... timezone name
z ... offset from UTC (-hhmm or +hhmm)
%+ ... national representation of the date and time (the format is similar to that produced by date(1)).
%% ... percent sign

Some platforms may also support the following format extensions:
E* ... POSIX locale extensions. Where "*" is one of the characters: c, C, x, X, y, Y.
G ... a year as a decimal number with century. This year is the one that contains the greater par of the week (Monday as the first day of the week).
g ... the same year as in `G', but as a decimal number without century (00-99).
O* ... POSIX locale extensions. Where "*" is one of the characters: d, e, H, I, m, M, S, u, U, V, w, W, y. Additionly OB implemented to represent alternative months names (used standalone, without day mentioned).
V ... the week number of the year (Monday as the first day of the week) as a decimal number (01-53). If the week containing January 1 has four or more days in the new year, then it is week 1; otherwise it is the last week of the previous year, and the next week is week 1.

Useful formats:
RFC822: "%a, %d %b %Y %H:%M:%S %Z "Fri, 07 Jan 2003 12:12:21 PDT" \n "T F "12:12:21 2007-01-03"
"%v "07-Jul-2003" \n RFC3399: "FTTZ" "1985-04-12T23:20:50.52Z" which is April 12 1985, 23:20.50 and 52 msec

timeTime to format. Use rGetTime to retrieve the current time.
Returns:
The formatting time string. Caller must free.
API Stability:
Evolving.

PUBLIC ssize rFprintf (FILE *fp, cchar *fmt, ...)

Formatted print to the standard error channel.

Description:
This is a secure replacement for fprintf. It can handle null arguments without crashes.
Parameters:
fpFile handle.
fmtPrintf style format string.
...Variable arguments to format.
Returns:
The number of bytes written.
API Stability:
Evolving.

PUBLIC void rFree (void *ptr)

Free a block of memory allocated via rAlloc.

Description:
This releases a block of memory allocated via rAllocMem.
Parameters:
ptrPointer to the block. If ptr is null, the call is skipped.
Remarks:
The rFree routine is a macro over rFreeMem. Do not mix calls to rFreeMem and free.
API Stability:
Evolving.

PUBLIC void rFreeFiber (RFiber *fiber)

Free a fiber coroutine.

Description:
The fiber must have already completed before invoking this routine. This routine is typically only called internally by the fiber module.
Parameters:
fiberFiber to free.
API Stability:
Internal.

PUBLIC void rFreeHash (RHash *hash)

Free a hash table.

Parameters:
hashHash table to free.
API Stability:
Evolving.

PUBLIC void rFreeLock (RLock *mutex)

Free a dynamically allocated lock object.

Description:
This routine is THREAD SAFE.
Parameters:
mutexReference to an RLock structure to initialize.
API Stability:
Evolving.

PUBLIC void rFreeSocket (RSocket *sp)

Free a socket object.

API Stability:
Evolving.

PUBLIC void rFreeWait (RWait *wp)

Free a wait object.

Parameters:
wpRWait object.
API Stability:
Evolving.

PUBLIC char,* rGetAppDir (void )

Get the directory containing the application executable.

Returns:
An allocated string containing the application directory. Caller must free.
API Stability:
Evolving.

PUBLIC cchar,* rGetAppName (void )

Get the application name defined via rSetAppName.

Returns:
The one-word lower case application name defined via rSetAppName.
API Stability:
Evolving.

PUBLIC RThread rGetCurrentThread (void )

Get the current Thread.

Description:
This routine is THREAD SAFE.
Returns:
The currently executing thread.
API Stability:
Evolving.

PUBLIC char,* rGetCwd (void )

Get the current application working directory.

Returns:
An allocated string containing the working directory. Caller must free.
API Stability:
Evolving.

PUBLIC char,* rGetDate (cchar *format)

Get a string representation of the current date/time.

Description:
Get the current date/time as a string according to the given format.
Parameters:
formatDate formatting string. See strftime for acceptable date format specifiers. If null, then this routine uses the R_DEFAULT_DATE format.
Returns:
A date string. Caller must free.
API Stability:
Evolving.

PUBLIC Ticks rGetElapsedTicks (Ticks mark)

Get the elapsed time since a ticks mark.

Create the ticks mark with rGetTicks()
Parameters:
markStaring time stamp.
Returns:
The time elapsed since the mark was taken.
API Stability:
Evolving.

PUBLIC cchar,* rGetError (int error)

Return a string representation of an R error code.

Parameters:
errorAn R error code. These codes are always negative for errors and zero for R_OK.
Returns:
A static string error representation.
API Stability:
Evolving.

PUBLIC RFiber,* rGetFiber (void )

Get the current fiber object.

Returns:
Fiber Fiber object.
API Stability:
Evolving.

PUBLIC void,* rGetFiberStack (void )

Get the base address of the fiber stack.

Returns:
A pointer to the base of the fiber stack.
API Stability:
Evolving.

PUBLIC char,* rGetFilePath (cchar *path)

Get a file path name.

Description:
Expand any "@token" prefix in the path.
Parameters:
pathSource file path.
Returns:
The expanded path. Caller must free.
API Stability:
Evolving.

PUBLIC RList,* rGetFiles (cchar *base, cchar *pattern, int flags)

Create a list of files in a directory or subdirectories that match the given wildcard pattern.

This call returns a list of filenames
Description:
Get the list of files in a directory and return a list. The pattern list may contain wildcards. The supported wildcard patterns are: "?" Matches any single character, "*" matches zero or more characters of the file or directory, "**"/ matches zero or more directories, "**" matches zero or more files or directories.

If the pattern is absolute.
Parameters:
baseBase directory from which to interpret the pattern. If the patternDirectory to list.
patternWild card patterns to match.
flagsSet to R_FILES_HIDDEN to include hidden files that start with ".". Set to R_FILES_DEPTH_FIRST to do a depth-first traversal, i.e. traverse subdirectories before considering adding the directory to the list. Set R_FILES_RELATIVE to return files relative to the given base. Set R_FILES_NO_DIRS to omit directories. Use R_FILES_DIRS_ONLY to omit regular files.
Returns:
A list (RList) of filenames.
API Stability:
Evolving.

PUBLIC RList,* rGetFilesEx (RList *results, cchar *base, cchar *pattern, int flags)

Get a list of files in a directory or subdirectories that match the given wildcard pattern.

This call adds the files to the supplied results list
Description:
Get the list of files in a directory and return a list. The pattern list may contain wildcards. The supported wildcard patterns are: "?" Matches any single character, "*" matches zero or more characters of the file or directory, "**"/ matches zero or more directories, "**" matches zero or more files or directories.
Parameters:
resultsInstance of RList. See rAllocList.
baseBase directory from which to interpret the pattern. If the patternDirectory to list.
patternWild card patterns to match.
flagsSet to R_FILES_HIDDEN to include hidden files that start with ".". Set to R_FILES_DEPTH_FIRST to do a depth-first traversal, i.e. traverse subdirectories before considering adding the directory to the list. Set R_FILES_RELATIVE to return files relative to the given base. Set R_FILES_NO_DIRS to omit directories. Use R_FILES_DIRS_ONLY to omit regular files.
Returns:
A list (RList) of filenames.
API Stability:
Evolving.

PUBLIC ssize rGetFileSize (cchar *path)

Return the size of a file.

Parameters:
pathFilename to test.
Returns:
The size of the file or a negative RT error code if the file does not exist.
API Stability:
Evolving.

PUBLIC int rGetHashLength (RHash *hash)

Return the count of symbols in a symbol entry.

Description:
Returns the number of symbols currently existing in a symbol table.
Parameters:
hashSymbol table returned via rAllocHash.
Returns:
Integer count of the number of entries.
API Stability:
Evolving.

uint64 rGetHiResTicks (void )

Get the CPU tick count.

Description:
Get the current CPU tick count. This is a system dependant high resolution timer. On some systems, this returns time in nanosecond resolution.
Returns:
The CPU time in ticks. Will return the system time if CPU ticks are not available.
API Stability:
Internal.

PUBLIC char,* rGetIsoDate (Time time)

Get an ISO Date string representation of the given date/time.

Description:
Get the date/time as an ISO string.
Parameters:
timeGiven time to convert.
Returns:
A date string. Caller must free.
API Stability:
Evolving.

PUBLIC RThread rGetMainThread (void )

Get the main Thread.

Description:
This routine is THREAD SAFE.
Returns:
The original main thread.
API Stability:
Evolving.

PUBLIC RName,* rGetNextName (RHash *hash, RName *next)

Return the next symbol in a symbol entry.

Description:
Continues walking the contents of a symbol table by returning the next entry in the symbol table. A previous call to rGetFirstSymbol or rGetNextSymbol is required to supply the value of the last argument.
Parameters:
hashHash table hash returned via rAllocHash.
nextIndex of next name.
Returns:
Pointer to the first entry in the symbol table.
API Stability:
Evolving.

PUBLIC int rGetOsError (void )

Return the native O/S error code.

Description:
Returns an O/S error code from the most recent system call. This returns errno on Unix systems or GetLastError() on Windows.
Returns:
The O/S error code.
API Stability:
Evolving.

PUBLIC Ticks rGetRemainingTicks (Ticks mark, Ticks timeout)

Return the time remaining until a timeout has elapsed.

Parameters:
markStaring time stamp.
timeoutTime in milliseconds.
Returns:
Time in milliseconds until the timeout elapses.
API Stability:
Evolving.

PUBLIC cchar,* rGetServerName (void )

Get the application server name string.

Returns:
A string containing the application server name string.
API Stability:
Evolving.

PUBLIC int rGetSocketAddr (RSocket *sp, char *ipbuf, int ipbufLen, int *port)

Get the locally bound socket IP address and port for the socket.

Description:
Get the file descriptor associated with a socket.
Parameters:
spSocket object returned from rAllocSocket.
ipbufBuffer to receive the IP address.
ipbufLenSize of the ipbuf.
portAddress of an integer to receive the port unumber.
Returns:
Zero if successful.
API Stability:
Evolving.

PUBLIC RSocketCustom rGetSocketCustom (void )

Get the custom socket callback handler.

Returns:
The custom socket callback handler.
API Stability:
Evolving.

PUBLIC cchar,* rGetSocketError (RSocket *sp)

Get the socket error.

Parameters:
spSocket object returned from rAllocSocket.
Returns:
The socket error message. Returns NULL if no error. Caller must NOT free.
API Stability:
Evolving.

PUBLIC Socket rGetSocketHandle (RSocket *sp)

Get the socket file descriptor.

Description:
Get the file descriptor associated with a socket.
Parameters:
spSocket object returned from rAllocSocket.
Returns:
The Socket file descriptor used by the O/S for the socket.
API Stability:
Evolving.

PUBLIC RWait,* rGetSocketWait (RSocket *sp)

Get the socket wait handler.

Returns:
RWait reference.
API Stability:
Evolving.

PUBLIC int rGetState (void )

Get the current R state.

Returns:
Returns R_INITIALIZED, R_READY, R_STOPPING or R_STOPPED.
API Stability:
Evolving.

PUBLIC char,* rGetTempFile (cchar *dir, cchar *prefix)

Get a temp filename.

Description:
Create a temp file name in the given directory with the specified prefix.
Parameters:
dirDirectory to contain the temporary file. If null, use system default temp directory (/tmp).
prefixOptional filename prefix.
Returns:
An allocated string containing the file name. Caller must free.
API Stability:
Evolving.

PUBLIC Ticks rGetTicks (void )

Get the system time.

Description:
Get the system time in milliseconds. This is a monotonically increasing time counter. It does not represent wall-clock time.
Returns:
The system time in milliseconds.
API Stability:
Evolving.

PUBLIC Time rGetTime (void )

Get the time.

Description:
Get the date/time in milliseconds since Jan 1 1970.
Returns:
The time in milliseconds since Jan 1 1970.
API Stability:
Evolving.

PUBLIC bool rGetTimeouts (void )

Return true if timeouts are enabled.

Returns:
True if timeouts are enabled.
API Stability:
Evolving.

PUBLIC int rGetWaitFd (void )

Get the global wait descriptor.

Returns:
The wait file descriptor used by epoll and kqueue.
API Stability:
Evolving.

PUBLIC void rGlobalLock (void )

Globally lock the application.

Description:
This call asserts the application global lock so that other threads calling rGlobalLock will block until the current thread calls rGlobalUnlock. WARNING: Use this API very sparingly. This routine is THREAD SAFE.
API Stability:
Evolving.

PUBLIC void rGlobalUnlock (void )

Unlock the global mutex.

Description:
This call unlocks the global mutex previously locked via rGlobalLock. This routine is THREAD SAFE.
API Stability:
Evolving.

PUBLIC void rGracefulStop (void )

Gracefully stop the app.

Description:
Queued events will be serviced.
API Stability:
Evolving.

PUBLIC RBuf,* rHashToBuf (RHash *hash, cchar *join)

Convert a hash of strings to a single string in a buffer.

Parameters:
hashHash pointer returned from rCreateHash.
joinString to use as the element join string.
Returns:
Buffer consisting of the joined hash values. Caller must free with rFreeBuf.
API Stability:
Evolving.

PUBLIC char,* rHashToJson (RHash *hash, int pretty)

Convert a hash into JSON.

Parameters:
hashHash table to use for the result.
prettySet to true to have a prettier JSON representation.
Returns:
A JSON string. Caller must free.
API Stability:
Evolving.

PUBLIC RBuf,* rHashToJsonBuf (RHash *hash, RBuf *buf, int pretty)

Convert a hash into JSON in the given buffer.

Parameters:
hashHash table to use for the result.
bufRBuf instance to store the json text.
prettySet to true to have a prettier JSON representation.
Returns:
The given buffer.
API Stability:
Evolving.

PUBLIC char,* rHashToString (RHash *hash, cchar *join)

Convert a hash of strings to a single string.

Parameters:
hashHash pointer returned from rCreateHash.
joinString to use as the element join string.
Returns:
String consisting of the joined hash values. Caller must free.
API Stability:
Evolving.

PUBLIC int rInit (RFiberProc fn, cvoid *arg)

Initialize the runtime.

Description:
This routine should be called at startup from main().
Parameters:
fnFiber function to start.
argArgument to the fiber function.
Returns:
Zero if successful.
API Stability:
Evolving.

PUBLIC int rInitFibers (void )

Initialize the fiber coroutine module.

Returns:
Zero if successful.
API Stability:
Evolving.

PUBLIC int rInitFile (void )

Create and initialze the file subsystem.

API Stability:
Internal.

PUBLIC RLock,* rInitLock (RLock *mutex)

Initialize a statically allocated lock object.

Description:
This call initialized a lock object without allocation. The object can then be used used in rLock rTryLock and rUnlock calls. This routine is THREAD SAFE.
Parameters:
mutexReference to an RLock structure to initialize.
Returns:
A reference to the supplied mutex. Returns null on errors.
API Stability:
Evolving.

PUBLIC int rInitOs (void )

Create and initialze the O/S dependent subsystem.

Description:
Called internally by the RT. Should not be called by users.
API Stability:
Internal.

PUBLIC int rInitWait (void )

Initialize the I/O wait subsystem.

Returns:
Zero if successful.
API Stability:
Evolving.

PUBLIC bool rIsFileAbs (cchar *path)

Determine if a file path is an absolute path.

Parameters:
pathFilename path to test.
Returns:
True if the path is an absolute path.
API Stability:
Evolving.

PUBLIC bool rIsMain (void )

Test if a fiber is the main fiber.

Returns:
True if the fiber is the main fiber.
API Stability:
Evolving.

PUBLIC bool rIsSocketClosed (RSocket *sp)

Test if the socket has been closed.

Description:
Determine if rCloseSocket has been called.
Parameters:
spSocket object returned from rAllocSocket.
Returns:
True if the socket is at end-of-file.
API Stability:
Evolving.

PUBLIC bool rIsSocketConnected (RSocket *sp)

Determine if the socket has connected to a remote pper.

Parameters:
spSocket object returned from rAllocSocket.
Returns:
True if the socket is connected.
API Stability:
Evolving.

PUBLIC bool rIsSocketEof (RSocket *sp)

Test if the other end of the socket has been closed.

Description:
Determine if the other end of the socket has been closed and the socket is at end-of-file.
Parameters:
spSocket object returned from rAllocSocket.
Returns:
True if the socket is at end-of-file.
API Stability:
Evolving.

PUBLIC bool rIsSocketSecure (RSocket *sp)

Determine if the socket is secure.

Description:
Determine if the socket is using SSL to provide enhanced security.
Parameters:
spSocket object returned from rAllocSocket.
Returns:
True if the socket is using SSL, otherwise zero.
API Stability:
Evolving.

PUBLIC char,* rJoinFile (cchar *base, cchar *other)

Join file paths.

Description:
Join a path to a base path. If the other path is absolute, it will be returned.
Parameters:
baseDirectory filename to use as the base.
otherOther filename path to join to the base filename.
Returns:
Allocated string containing the resolved filename. Caller must free.
API Stability:
Evolving.

PUBLIC char,* rJoinFileBuf (char *buf, ssize bufsize, cchar *base, cchar *other)

Join paths into a buffer.

Description:
Join a path to a base path. If path is absolute, it will be returned.
Parameters:
bufDestination path buffer.
bufsizeSize of buf.
baseDirectory filename to use as the base.
otherOther filename path to join to the base filename.
Returns:
Allocated string containing the resolved filename.
API Stability:
Evolving.

PUBLIC void rLeave (bool *access)

Leave a fiber critical section.

Description:
This routine must be called on all exit paths from a fiber after calling rEnter.
Parameters:
accessPointer to a boolean initialized to false.
API Stability:
Prototype.

PUBLIC int rListenSocket (RSocket *sp, cchar *host, int port, RSocketProc handler, void *arg)

Listen on a server socket for incoming connections.

Description:
Open a server socket and listen for client connections. If host is null, then this will listen on both IPv6 and IPv4.
Parameters:
spSocket object returned via rAllocSocket.
hostHost name or IP address to bind to. Set to 0.0.0.0 to bind to all possible addresses on a given port.
portTCP/IP port number to connect to.
handlerFunction callback to invoke for incoming connections. The function is invoked on a new fiber coroutine.
argArgument to handler.
Returns:
Zero if successful.
API Stability:
Evolving.

PUBLIC void rLock (RLock *lock)

Lock access.

Description:
This call asserts a lock on the given lock mutex so that other threads calling rLock will block until the current thread calls rUnlock. This routine is THREAD SAFE.
Parameters:
lockobject.
API Stability:
Evolving.

PUBLIC bool rLookupEvent (REvent id)

Lookup an event ID.

Parameters:
idEvent id allocated by rStartEvent.
Returns:
True if the event exists.
API Stability:
Evolving.

PUBLIC void,* rLookupName (RHash *hash, cchar *name)

Lookup a symbol in the hash table.

Description:
Lookup a name and return the value associated with that name.
Parameters:
hashSymbol table returned via rAllocHash.
nameString name of the symbole entry to delete.
Returns:
Value associated with the name when the entry was insered via rInserSymbol.
API Stability:
Evolving.

PUBLIC RName,* rLookupNameEntry (RHash *hash, cchar *name)

Lookup a symbol in the hash table and return the hash entry.

Description:
Lookup a name and return the hash table descriptor associated with that name.
Parameters:
hashSymbol table returned via rAllocHash.
nameString name of the symbole entry to delete.
Returns:
RName for the entry.
API Stability:
Evolving.

PUBLIC bool rMatchFile (cchar *path, cchar *pattern)

Matach a file against a glob pattern.

Description:
This tests a filename against a file pattern. The pattern list may contain wildcards. The supported wildcard patterns are: "?" Matches any single character, "*" matches zero or more characters of the file or directory, "**"/ matches zero or more directories, "**" matches zero or more files or directories,and a trailing "/" matches directories only.

If the pattern is absolute.
Parameters:
pathFilename to test.
patternWild card patterns to match.
Returns:
True if the path matches the pattern.
API Stability:
Evolving.

PUBLIC void,* rMemdup (cvoid *ptr, size_t size)

Duplicate a block of memory.

Description:
Copy a block of memory into a newly allocated block.
Parameters:
ptrPointer to the block to duplicate.
sizeSize of the block to copy.
Returns:
Returns an allocated block.
API Stability:
Evolving.

PUBLIC void rMemoryBarrier (void )

Perform a memory barrier where all queued writes are flushed to memory.

Description:
Use this call before accessing data that is updated and read across multiple threads.
API Stability:
Evolving.

PUBLIC Time rParseIsoDate (cchar *when)

Parse an ISO date string.

Returns:
The time in milliseconds since Jan 1, 1970.
API Stability:
Evolving.

PUBLIC ssize rPrintf (cchar *fmt, ...)

Formatted print.

This is a secure verion of printf that can handle null args
Description:
This is a secure replacement for printf. It can handle null arguments without crashes.
Parameters:
fmtPrintf style format string.
...Variable arguments to format.
Returns:
The number of bytes written.
API Stability:
Evolving.

PUBLIC char,* rReadFile (cchar *path, ssize *lenp)

Read data from a file.

Description:
Reads data from a file.
Parameters:
pathFilename to read.
lenpPointer to receive the length of the file read.
Returns:
The contents of the file in an allocated string.
API Stability:
Evolving.

PUBLIC ssize rReadSocket (RSocket *sp, char *buf, ssize bufsize, Ticks deadline)

Read from a socket.

Description:
Read data from a socket. The read will return with whatever bytes are available. If none is available, this call will yield the current fiber and resume the main fiber. When data is available, the fiber will resume.
Must be called from a fiber.
Parameters:
spSocket object returned from rAllocSocket.
bufPointer to a buffer to hold the read data.
bufsizeSize of the buffer.
deadlineMaximum system time for connect to wait until completion. Use rGetTicks() + elapsed to create a deadline. Set to 0 for no deadline.
Returns:
A count of bytes actually read. Return a negative R error code on errors.
Returns:
Return -1 for EOF and errors. On success, return the number of bytes read. Use rIsSocketEof to distinguision between EOF and errors.
API Stability:
Evolving.

PUBLIC ssize rReadSocketSync (RSocket *sp, char *buf, ssize bufsize)

Read from a socket.

Description:
Read data from a socket. The read will return with whatever bytes are available. If none and the socket is in blocking mode, it will block until there is some data available or the socket is disconnected. Use rSetSocketBlocking to change the socket blocking mode. It is preferable to use rReadSocket which can wait without blocking via fiber coroutines.
Parameters:
spSocket object returned from rAllocSocket.
bufPointer to a buffer to hold the read data.
bufsizeSize of the buffer.
Returns:
A count of bytes actually read. Return a negative R error code on errors.
Returns:
Return -1 for EOF and errors. On success, return the number of bytes read. Use rIsSocketEof to distinguision between EOF and errors.
API Stability:
Evolving.

PUBLIC void,* rRealloc (void *ptr, size_t size)

Allocate a block of memory.

Description:
This is the lowest level of memory allocation routine. Memory is freed via rFree.
Parameters:
sizeSize of the memory block to allocate.
ptrPointer to the block. If ptr is null, the call is skipped.
Returns:
Returns a pointer to the reallocated block. If memory is not available the memory exhaustion handler will be invoked.
Remarks:
Do not mix calls to rRealloc and malloc.
API Stability:
Evolving.

PUBLIC int rRemoveName (RHash *hash, cchar *name)

Remove a symbol entry from the hash table.

Description:
Removes a symbol entry from the symbol table. The entry is looked up via the supplied name.
Parameters:
hashSymbol table returned via rAllocHash.
nameString name of the symbole entry to delete.
Returns:
Returns zero if successful, otherwise a negative RT error code is returned.
API Stability:
Evolving.

PUBLIC void rResetSocket (RSocket *sp)

Reset a socket.

Description:
Reset a socket by closing the underlying socket file descriptor. The Socket instance can be reused by rConnectSocket.
Parameters:
spSocket object returned from rAllocSocket.
API Stability:
Evolving.

PUBLIC void,* rResumeFiber (RFiber *fiber, void *result)

Resume a fiber.

Description:
Resume a fiber. If called from a non-main fiber or foreign-thread the target fiber is resumed via an event to the main fiber. THREAD SAFE.
Parameters:
fiberFiber object.
resultResult to pass to the fiber and will be the value returned from rYieldFiber.
API Stability:
Evolving.

PUBLIC void rResumeWait (RWait *wp, int mask)

Release a waiting fiber waiting for an event.

Description:
This call may be used to waken a fiber in response to external events.
Parameters:
wpRWait object.
maskEvent mask to pass to fiber on resume.
API Stability:
Evolving.

PUBLIC char,* rRun (cchar *command, int *status)

Run a command using the system shell.

Parameters:
commandCommand string to run using popen().
statusReturns the command exit status.
API Stability:
Evolving.

PUBLIC int rRunEvent (REvent id)

Run an event now.

Parameters:
idEvent id allocated by rStartEvent.
Returns:
Zero if the event is found and can be run.
API Stability:
Evolving.

PUBLIC Ticks rRunEvents (void )

Run due events.

Returns:
Time delay till the next event.
API Stability:
Evolving.

PUBLIC int rServiceEvents (void )

Service events.

Description:
This call blocks and continually services events on the event loop until the app is instructed to exit via $rStop. An app should call rServiceEvents from the main program.
Returns:
The current R state.
API Stability:
Evolving.

PUBLIC void rSetFiberLimits (int maxFibers)

Set the fiber limits.

Parameters:
maxFibersThe maximum number of fibers (stacks). Set to zero for no limit.
API Stability:
Evolving.

PUBLIC void rSetFiberStack (ssize size)

Set the default fiber stack size.

Parameters:
sizeSize of fiber stack in bytes.
API Stability:
Evolving.

PUBLIC void rSetMemHandler (RMemProc handler)

Define a global memory exhaustion handler.

Description:
The memory handler will be invoked for memory allocation errors.
Parameters:
handlerCallback function invoked with the signature: void fn(int cause, size_t size).
API Stability:
Evolving.

PUBLIC void rSetOsError (int error)

Set the O/S error code.

Description:
Set errno or equivalent.
API Stability:
Evolving.

PUBLIC void rSetSocketBlocking (RSocket *sp, bool on)

Set a socket into blocking I/O mode.

from a socket
Description:
Sockets are opened in non-blocking mode by default.
Parameters:
spSocket object returned from rAllocSocket.
onSet to true to enable blocking mode.
API Stability:
Evolving.

PUBLIC void rSetSocketCerts (RSocket *sp, cchar *ca, cchar *key, cchar *cert, cchar *revoke)

Configure the socket TLS certificates.

Description:
This call is a wrapper over rSetTLSCerts.
Parameters:
spSocket object returned from rAllocSocket.
caCertificate authority to use when verifying peer connections.
keyPrivate key for the certificate.
certCertificate to use for TLS.
revokeList of revoked certificates.
API Stability:
Evolving.

PUBLIC void rSetSocketCiphers (RSocket *sp, cchar *ciphers)

Set the ciphers to use for communications.

Parameters:
spSocket object returned from rAllocSocket.
ciphersString of suitable ciphers.
API Stability:
Evolving.

PUBLIC void rSetSocketCustom (RSocketCustom custom)

Set the socket custom configuration callback.

Parameters:
customCustom callback function.
Returns:
RWait reference.
API Stability:
Evolving.

PUBLIC void rSetSocketDefaultCerts (cchar *ca, cchar *key, cchar *cert, cchar *revoke)

Configure the default TLS certificates.

Description:
This call is a wrapper over rSetTLSCerts.
Parameters:
caCertificate authority to use when verifying peer connections.
keyPrivate key for the certificate.
certCertificate to use for TLS.
revokeList of revoked certificates.
API Stability:
Evolving.

PUBLIC void rSetSocketDefaultCiphers (cchar *ciphers)

Set the default TLS ciphers to use for communications.

Parameters:
ciphersString of suitable ciphers.
API Stability:
Evolving.

PUBLIC void rSetSocketDefaultVerify (int verifyPeer, int verifyIssuer)

Set the default TLS verification parameters.

Description:
This call is a wrapper over rSetTlsCerts.
Parameters:
verifyPeerSet to true to verify peer certificates.
verifyIssuerSet to true to verify the issuer of the peer certificate.
API Stability:
Evolving.

PUBLIC int rSetSocketError (RSocket *sp, cchar *fmt, ...)

Set the socket error message.

Parameters:
spSocket object returned from rAllocSocket.
fmtPrintf style format string.
...Args for fmt.
API Stability:
Evolving.

PUBLIC void rSetSocketVerify (RSocket *sp, int verifyPeer, int verifyIssuer)

Set the socket TLS verification parameters.

Description:
This call is a wrapper over rSetTlsCerts.
Parameters:
spSocket object returned from rAllocSocket.
verifyPeerSet to true to verify peer certificates.
verifyIssuerSet to true to verify the issuer of the peer certificate.
API Stability:
Evolving.

PUBLIC void rSetSocketWaitMask (RSocket *sp, int64 mask, Ticks deadline)

Update the wait mask for a socket.

Parameters:
spSocket object returned from rAllocSocket.
maskSet to R_READABLE or R_WRITABLE or both.
deadlineSystem time in ticks to wait until. Set to zero for no deadline.
API Stability:
Evolving.

PUBLIC void rSetState (int state)

Set the R state.

Description:
This API is thread safe and can be called from a foreign thread.
Parameters:
stateSet to R_INITIALIZED, R_READY, R_STOPPING or R_STOPPED.
API Stability:
Evolving.

PUBLIC void rSetTimeouts (bool on)

Control timeouts.

Parameters:
onSet to false to disable timeouts for debugging.
API Stability:
Evolving.

PUBLIC void rSetWaitHandler (RWait *wp, RWaitProc handler, cvoid *arg, int64 mask, Ticks deadline)

Define a wait handler function on a wait object.

Description:
This will run the designated handler on a coroutine fiber in response to matching I/O events.
Parameters:
wpRWait object.
handlerFunction handler to invoke as the entrypoint in the new coroutine fiber.
argParameter argument to pass to the handler.
maskSet to R_READABLE or R_WRITABLE or both.
deadlineOptional deadline to wait system time. Set to zero for no deadline.
API Stability:
Evolving.

PUBLIC void rSetWaitMask (RWait *wp, int64 mask, Ticks deadline)

Update the wait mask for a wait handler.

Parameters:
wpRWait object.
maskSet to R_READABLE or R_WRITABLE or both.
deadlineSystem time in ticks to wait until. Set to zero for no deadline.
API Stability:
Evolving.

PUBLIC void rSignal (cchar *name, cvoid *arg)

Signal watches of a named event.

Parameters:
nameNamed event.
argData argument to pass to the watch function.
API Stability:
Evolving.

PUBLIC void rSignalSync (cchar *name, cvoid *arg)

Signal watches of a named event synchronously (blocking).

Parameters:
nameNamed event.
argData argument to pass to the watch function.
API Stability:
Evolving.

PUBLIC void rSleep (Ticks ticks)

Sleep a fiber for the requested number of milliseconds.

Must be called from a fiber.
Description:
Pause a fiber for the requested duration and then resume via the main fiber. Other fibers continue to run.
Parameters:
ticksTime period in milliseconds to sleep.
API Stability:
Evolving.

PUBLIC char,* rSnprintf (char *buf, ssize maxsize, cchar *fmt, ...)

Format a string into a buffer.

Description:
This routine will format the arguments into a result. If a buffer is supplied, it will be used. Otherwise if the buf argument is NULL, a buffer will be allocated. The arguments will be formatted up to the maximum size supplied by the maxsize argument. A trailing NULL will always be appended.
Parameters:
bufOptional buffer to contain the formatted result.
maxsizeMaximum size of the result.
fmtPrintf style format string.
...Variable arguments to format.
Returns:
The original buffer if supplied or else an allocated string.
API Stability:
Prototype.

PUBLIC int rSpawnFiber (cchar *name, RFiberProc fn, void *arg)

Spawn a fiber coroutine.

Description:
This allocates a new fiber and resumes it.
Parameters:
nameFiber name.
fnFiber entry point.
argEntry point argument.
Returns:
Zero if successful.
API Stability:
Evolving.

PUBLIC void,* rSpawnThread (RThreadProc fn, void *arg)

Spawn an O/S thread and wait until it completes.

Description:
This creates a new thread and runs the given function. It then yields until the thread function returns and returns the function result.
Parameters:
fnThread main function entry point.
argArgument provided to the thread.
Returns:
Value returned from spawned thread function.
API Stability:
Evolving.

PUBLIC REvent rStartEvent (REventProc proc, void *data, Ticks delay)

Start a callback event.

Description:
This API is a wrapper for rAllocEvent with the fiber set to the current fiber. This schedules an event to run once. The event can be rescheduled in the callback by invoking rRestartEvent. This routine is THREAD SAFE.
Parameters:
procCallback procedure function. Signature is: void (*fn)(void *data, int id).
dataData reference to pass to the callback.
delayDelay in milliseconds in which to run the callback.
Returns:
A positive integer event ID.
API Stability:
Evolving.

PUBLIC void rStartFiber (RFiber *fiber, void *data)

Start a fiber coroutine.

Description:
This creates an event so that the main fiber can start the fiber. This routine is typically only called internally by the fiber module. This routine is THREAD SAFE and can be used to resume a yielded fiber.
Parameters:
fiberThe fiber object.
dataValue to pass to the fiber entry point.
API Stability:
Internal.

PUBLIC void rStop (void )

Immediately stop the app.

Description:
This API is thread safe and can be called from a foreign thread.
Description:
Queued events will not be serviced.
API Stability:
Evolving.

PUBLIC int rStopEvent (REvent id)

Stop an event.

Parameters:
idEvent id allocated by rStartEvent.
Returns:
Integer handle index. Otherwise return -1 on allocation errors.
API Stability:
Evolving.

PUBLIC void rTermFibers (void )

Terminate the fiber coroutine module.

API Stability:
Evolving.

PUBLIC void rTermFile (void )

Stop the file subsystem.

API Stability:
Internal.

PUBLIC void rTermLock (RLock *mutex)

Terminate a statically allocated lock object.

Description:
This routine is THREAD SAFE.
Parameters:
mutexReference to an RLock structure to initialize.
API Stability:
Evolving.

PUBLIC void rTermOs (void )

Stop the O/S dependent subsystem.

API Stability:
Internal.

PUBLIC void rTermWait (void )

Terminate the I/O wait subsystem.

API Stability:
Evolving.

PUBLIC bool rTryLock (RLock *lock)

Attempt to lock access.

Description:
This call attempts to assert a lock on the given lock mutex so that other threads calling rLock or rTryLock will block until the current thread calls rUnlock. This routine is THREAD SAFE.
Returns:
Returns zero if the successful in locking the mutex. Returns a negative error code if unsuccessful.
API Stability:
Evolving.

PUBLIC void rUnlock (RLock *lock)

Unlock a mutex.

Description:
This call unlocks a mutex previously locked via rLock or rTryLock. This routine is THREAD SAFE.
Parameters:
lockobject.
API Stability:
Evolving.

PUBLIC char,* rVsnprintf (char *buf, ssize maxsize, cchar *fmt, va_list args)

Format a string into a buffer.

Description:
This routine will format the arguments into a result. If a buffer is supplied, it will be used. Otherwise if the buf argument is NULL, a buffer will be allocated. The arguments will be formatted up to the maximum size supplied by the maxsize argument. A trailing NULL will always be appended.
Parameters:
bufOptional buffer to contain the formatted result.
maxsizeMaximum size of the result. If set to -1, thee will be no limit.
fmtPrintf style format string.
argsVariable arguments to format.
Returns:
The original buffer if supplied or else an allocated string.
API Stability:
Prototype.

PUBLIC int rWait (Ticks timeout)

Wait for an I/O event.

Description:
This is typically called by $rServiceEvents to wait for I/O events.
Parameters:
timeoutMaximum time in milliseconds to wait for an I/O event.
Returns:
Zero if successful.
API Stability:
Evolving.

PUBLIC int rWaitForIO (RWait *wp, int mask, Ticks deadline)

Wait for an IO event on a wait object.

Description:
Wait for an IO event by yielding the current coroutine fiber until the IO event arrives. When the IO event occurs, the wait handler will be invoked on the fiber.
Parameters:
wpRWait object.
maskSet to R_READABLE or R_WRITABLE or both.
deadlineSystem time in ticks to wait until. Set to zero for no deadline.
Returns:
A mask of I/O events with R_READABLE or R_WRITABLE or R_MODIFIED or R_TIMEOUT.
API Stability:
Evolving.

PUBLIC void rWakeup (void )

Wakeup the event loop.

API Stability:
Internal.

PUBLIC int rWalkDir (cchar *dir, cchar *pattern, RWalkDirProc callback, void *arg, int flags)

Walk a directory tree and invoke a callback for each path that matches a given pattern.

Description:
The pattern may contain wildcards. The supported wildcard patterns are: "?" Matches any single character, "*" matches zero or more characters of the file or directory, "**"/ matches zero or more directories, "**" matches zero or more files or directories.

Parameters:
dirBase directory from which to interpret the pattern.
patternWild card patterns to match.
callbackCallback function of the signature RWalkDirProc.
argArgument to callback function.
flagsSet to R_FILES_HIDDEN to include hidden files that start with ".". Set to R_FILES_DEPTH_FIRST to do a depth-first traversal, i.e. traverse subdirectories before considering adding the directory to the list. Set R_FILES_RELATIVE to return files relative to the given base. Set R_FILES_NO_DIRS to omit directories. Use R_FILES_DIRS_ONLY to omit regular files.
API Stability:
Evolving.

PUBLIC void rWatch (cchar *name, RWatchProc proc, void *data)

Watch for a named event to happen.

Parameters:
nameNamed event.
procFunction to call.
dataData argument to pass to the proc function as the first argument.
API Stability:
Evolving.

PUBLIC void rWatchOff (cchar *name, RWatchProc proc, void *data)

Stop watching for a named event to happen.

This will remove the watch for a previous rWatch call with exactly the same proc and data arguments
Parameters:
nameNamed event.
procFunction provided to a previous rWatch call.
dataData argument supplied to a previous rWatch call.
API Stability:
Evolving.

PUBLIC ssize rWriteFile (cchar *path, cchar *buf, ssize len, int mode)

Write data to a file.

Description:
Write data from a file. The file will be created if required.
Parameters:
pathFilename to write.
bufBuffer of data to write to the file.
lenLength of the buffer.
modeCreate file mode.
Returns:
The length of bytes written to the file. Should equal len.
API Stability:
Evolving.

PUBLIC int rWritePid (void )

Write the current process pid to /var/run.

Returns:
Zero on success, otherwise a negative status code.

PUBLIC ssize rWriteSocket (RSocket *sp, cvoid *buf, ssize bufsize, Ticks deadline)

Write to a socket.

Description:
Write a block of data to a socket. If the socket is in non-blocking mode (the default), the write may return having written less than the required bytes. If no data can be written, this call will yield the current fiber and resume the main fiber. When data is available, the fiber will resume.
Must be called from a fiber.
Parameters:
spSocket object returned from rAllocSocket.
bufReference to a block to write to the socket.
bufsizeLength of data to write. This may be less than the requested write length if the socket is in non-blocking mode. Will return a negative error code on errors.
deadlineSystem time in ticks to wait until. Set to zero for no deadline.
Returns:
A count of bytes actually written. Return a negative error code on errors and if the socket cannot absorb any more data. If the transport is saturated, will return a negative error and rGetError() returns EAGAIN or EWOULDBLOCK.
API Stability:
Evolving.

PUBLIC ssize rWriteSocketSync (RSocket *sp, cvoid *buf, ssize len)

Write to a socket.

Description:
Write a block of data to a socket. If the socket is in non-blocking mode (the default), the write may return having written less than the required bytes. It is preferable to use rWriteSocket which can wait without blocking via fiber coroutines.
Parameters:
spSocket object returned from rAllocSocket.
bufReference to a block to write to the socket.
lenLength of data to write. This may be less than the requested write length if the socket is in non-blocking mode. Will return a negative error code on errors.
Returns:
A count of bytes actually written. Return a negative error code on errors and if the socket cannot absorb any more data. If the transport is saturated, will return a negative error and rGetError() returns EAGAIN or EWOULDBLOCK.
API Stability:
Evolving.

PUBLIC void,* rYieldFiber (void *value)

Yield a fiber back to the main fiber.

Description:
Pause a fiber until resumed by the main fiber. the target fiber is resumed via an event to the main fiber.
Parameters:
valueValue to provide as a result to the main fiber that called rResumeFiber.
API Stability:
Evolving.

PUBLIC char,* scamel (cchar *str)

Create a camel case version of the string.

Description:
Copy a string into a newly allocated block and make the first character lower case.
Parameters:
strPointer to the block to duplicate.
Returns:
Returns a newly allocated string.
API Stability:
Evolving.

PUBLIC int scaselesscmp (cchar *s1, cchar *s2)

Compare strings ignoring case.

This is a r replacement for strcasecmp. It can handle NULL args
Description:
Compare two strings ignoring case differences. This call operates similarly to strcmp.
Parameters:
s1First string to compare.
s2Second string to compare.
Returns:
Returns zero if the strings are equivalent, < 0 if s1 sors lower than s2 in the collating sequence or > 0 if it sors higher.
API Stability:
Evolving.

PUBLIC bool scaselessmatch (cchar *s1, cchar *s2)

Compare strings ignoring case.

This is similar to scaselesscmp but it returns a boolean
Description:
Compare two strings ignoring case differences.
Parameters:
s1First string to compare.
s2Second string to compare.
Returns:
Returns true if the strings are equivalent, otherwise false.
API Stability:
Evolving.

PUBLIC char,* schr (cchar *str, int c)

Find a character in a string.

Description:
This is a r replacement for strchr. It can handle NULL args.
Parameters:
strString to examine.
cCharacter to search for.
Returns:
If the character is found, the call returns a reference to the character position in the string. Otherwise, returns NULL.
API Stability:
Evolving.

PUBLIC char,* sclone (cchar *str)

Clone a string.

Description:
Copy a string into a newly allocated block. This routine is null tolerant. It will return an allocated empty string if passed a NULL. Use scloneNull if you need to preserve NULLs.
Parameters:
strPointer to the block to duplicate.
Returns:
Returns a newly allocated string. Caller must free.
API Stability:
Evolving.

PUBLIC char,* scloneNull (cchar *str)

Clone a string and preserve NULLs.

Description:
Copy a string into a newly allocated block. If passed a NULL, this will return a NULL.
Parameters:
strPointer to the block to duplicate.
Returns:
Returns a newly allocated string or NULL. Caller must free.
API Stability:
Evolving.

PUBLIC int scmp (cchar *s1, cchar *s2)

Compare strings.

Description:
Compare two strings. This is a r replacement for strcmp. It can handle null args.
Parameters:
s1First string to compare.
s2Second string to compare.
Returns:
Returns zero if the strings are identical. Return -1 if the first string is less than the second. Return 1 if the first string is greater than the second.
API Stability:
Evolving.

PUBLIC char,* scontains (cchar *str, cchar *pattern)

Find a pattern in a string.

Description:
Locate the first occurrence of pattern in a string.
Parameters:
strPointer to the string to search.
patternString pattern to search for.
Returns:
Returns a reference to the start of the pattern in the string. If not found, returns NULL.
API Stability:
Evolving.

PUBLIC ssize scopy (char *dest, ssize destMax, cchar *src)

Copy a string.

Description:
R replacement for strcpy. Copy a string and ensure the destination buffer is not overflowed. The call returns the length of the resultant string or an error code if it will not fit into the target string. This is similar to strcpy, but it will enforce a maximum size for the copied string and will ensure it is always terminated with a null. It is null tolerant in that "src" may be null.
Parameters:
destPointer to a pointer that will hold the address of the allocated block.
destMaxMaximum size of the target string in characters.
srcString to copy. May be null.
Returns:
The number of characters in the target string.
API Stability:
Evolving.

PUBLIC cchar,* sends (cchar *str, cchar *suffix)

Test if the string ends with a given pattern.

Parameters:
strString to examine.
suffixPattern to search for.
Returns:
Returns a pointer to the start of the pattern if found. Otherwise returns NULL.
API Stability:
Evolving.

PUBLIC char,* sfmt (cchar *fmt, ...)

Format a string.

This is a secure verion of printf that can handle null args
Description:
Format the given arguments according to the printf style format. See rPrintf for a full list of the format specifies. This is a secure replacement for sprintf, it can handle null arguments without crashes.
Parameters:
fmtPrintf style format string.
...Variable arguments for the format string.
Returns:
Returns a newly allocated string.
API Stability:
Evolving.

PUBLIC char,* sfmtbuf (char *buf, ssize maxSize, cchar *fmt, ...)

Format a string into a static buffer.

Description:
This call format a string using printf style formatting arguments. A trailing null will always be appended. The call returns the size of the allocated string excluding the null.
Parameters:
bufPointer to the buffer.
maxSizeSize of the buffer.
fmtPrintf style format string.
...Variable arguments to format.
Returns:
The buffer.
API Stability:
Evolving.

PUBLIC char,* sfmtbufv (char *buf, ssize maxSize, cchar *fmt, va_list args)

Format a string into a statically allocated buffer.

Description:
This call format a string using printf style formatting arguments. A trailing null will always be appended. The call returns the size of the allocated string excluding the null.
Parameters:
bufPointer to the buffer.
maxSizeSize of the buffer.
fmtPrintf style format string.
argsVarargs argument obtained from va_start.
Returns:
The buffer;.
API Stability:
Evolving.

PUBLIC char,* sfmtv (cchar *fmt, va_list args)

Format a string.

This is a secure verion of printf that can handle null args
Description:
Format the given arguments according to the printf style format. See rPrintf for a full list of the format specifies. This is a secure replacement for sprintf, it can handle null arguments without crashes.
Parameters:
fmtPrintf style format string.
argsVarargs argument obtained from va_start.
Returns:
Returns a newly allocated string.
API Stability:
Evolving.

PUBLIC uint shash (cchar *str, ssize len)

Compute a hash code for a string.

Parameters:
strString to examine.
lenLength in characters of the string to include in the hash code.
Returns:
Returns an unsigned integer hash code.
API Stability:
Evolving.

PUBLIC uint shashlower (cchar *str, ssize len)

Compute a caseless hash code for a string.

Description:
This computes a hash code for the string after convering it to lower case.
Parameters:
strString to examine.
lenLength in characters of the string to include in the hash code.
Returns:
Returns an unsigned integer hash code.
API Stability:
Evolving.

PUBLIC char,* sitos (int64 value)

Convert an integer to a string.

Description:
This call convers the supplied 64 bit integer to a string using base 10.
Parameters:
valueInteger value to conver.
Returns:
An allocated string with the converted number. Caller must free.
API Stability:
Evolving.

PUBLIC char,* sitosbuf (char *buf, ssize size, int64 value, int radix)

Convert an integer to a string buffer.

Description:
This call convers the supplied 64 bit integer into a string formatted into the supplied buffer according to the specified radix.
Parameters:
bufPointer to the buffer that will hold the string.
sizeSize of the buffer. Must be at least 2 characters long.
valueInteger value to conver.
radixThe base radix to use when encoding the number. Supports 10 and 16.
Returns:
Returns a reference to the string.
API Stability:
Evolving.

PUBLIC char,* sitosradix (int64 value, int radix)

Convert an integer to a string.

Description:
This call convers the supplied 64 bit integer to a string according to the specified radix.
Parameters:
valueInteger value to conver.
radixThe base radix to use when encoding the number.
Returns:
An allocated string with the converted number.
API Stability:
Evolving.

PUBLIC char,* sjoin (cchar *str, ...)

Catenate strings.

Description:
This catenates strings together with an optional string separator. If the separator is NULL, not separator is used. This call accepts a variable list of strings to append, terminated by a null argument.
Parameters:
strFirst string to catentate.
...Variable number of string arguments to append. Terminate list with NULL.
Returns:
Returns an allocated string.
API Stability:
Evolving.

PUBLIC char,* sjoinArgs (int argc, cchar **argv, cchar *sep)

Join an array of strings.

Parameters:
argcnumber of strings to join.
argvArray of strings.
sepSeparator string to use. If NULL, then no separator is used.
Returns:
A single joined string. Caller must free.
API Stability:
Evolving.

PUBLIC ssize sjoinbuf (char *buf, ssize bufsize, cchar *str1, cchar *str2)

Catenate strings into a buffer.

Parameters:
bufDestination buffer.
bufsizeSize of the buffer.
str1First string.
str2Second string to append.
Returns:
Number of bytes in the destination buffer.
API Stability:
Evolving.

PUBLIC char,* sjoinfmt (cchar *str, cchar *fmt, ...)

Join a formatted string to an existing string.

Description:
This uses the format and args to create a string that is joined to the first string.
Parameters:
strFirst string to catentate.
fmtFirst string to catentate.
...Varargs argument obtained from va_start.
Returns:
Returns an allocated string.
API Stability:
Evolving.

PUBLIC char,* sjoinv (cchar *str, va_list args)

Catenate strings.

Description:
This catenates strings together.
Parameters:
strFirst string to catentate.
argsVarargs argument obtained from va_start.
Returns:
Returns an allocated string.
API Stability:
Evolving.

PUBLIC ssize slen (cchar *str)

Return the length of a string.

Description:
R replacement for strlen. This call returns the length of a string and tests if the length is less than a given maximum. It will return zero for NULL args.
Parameters:
strString to measure.
Returns:
The length of the string.
API Stability:
Evolving.

PUBLIC char,* slower (char *str)

Convert a string to lower case.

Description:
Convert a string to its lower case equivalent.
Parameters:
strString to conver.
API Stability:
Evolving.

PUBLIC bool smatch (cchar *s1, cchar *s2)

Compare strings.

Description:
Compare two strings. This is similar to scmp but it returns a boolean.
Parameters:
s1First string to compare.
s2Second string to compare.
Returns:
Returns true if the strings are equivalent, otherwise false.
API Stability:
Evolving.

PUBLIC int sncaselesscmp (cchar *s1, cchar *s2, ssize len)

Compare strings ignoring case.

Description:
Compare two strings ignoring case differences for a given string length. This call operates similarly to strncasecmp.
Parameters:
s1First string to compare.
s2Second string to compare.
lenLength of characters to compare.
Returns:
Returns zero if the strings are equivalent, < 0 if s1 sors lower than s2 in the collating sequence or > 0 if it sors higher.
API Stability:
Evolving.

PUBLIC char,* sncaselesscontains (cchar *str, cchar *pattern, ssize limit)

Find a pattern in a string with a limit using a caseless comparison.

Description:
Locate the first occurrence of pattern in a string, but do not search more than the given character limit. Use a caseless comparison.
Parameters:
strPointer to the string to search.
patternString pattern to search for.
limitCount of characters in the string to search.
Returns:
Returns a reference to the start of the pattern in the string. If not found, returns NULL.
API Stability:
Evolving.

PUBLIC char,* snclone (cchar *str, ssize len)

Clone a substring.

Description:
Copy a substring into a newly allocated block.
Parameters:
strPointer to the block to duplicate.
lenNumber of bytes to copy. The actual length copied is the minimum of the given length and the length of the supplied string. The result is null terminated.
Returns:
Returns a newly allocated string.
API Stability:
Evolving.

PUBLIC int sncmp (cchar *s1, cchar *s2, ssize len)

Compare strings.

Description:
Compare two strings for a given string length. This call operates similarly to strncmp.
Parameters:
s1First string to compare.
s2Second string to compare.
lenLength of characters to compare.
Returns:
Returns zero if the strings are equivalent, < 0 if s1 sors lower than s2 in the collating sequence or > 0 if it sors higher.
API Stability:
Evolving.

PUBLIC char,* sncontains (cchar *str, cchar *pattern, ssize limit)

Find a pattern in a string with a limit.

Description:
Locate the first occurrence of pattern in a string, but do not search more than the given character limit.
Parameters:
strPointer to the string to search.
patternString pattern to search for.
limitCount of characters in the string to search.
Returns:
Returns a reference to the start of the pattern in the string. If not found, returns NULL.
API Stability:
Evolving.

PUBLIC ssize sncopy (char *dest, ssize destMax, cchar *src, ssize len)

Copy characters from a string.

Description:
R replacement for strncpy. Copy bytes from a string and ensure the target string is not overflowed. The call returns the length of the resultant string or an error code if it will not fit into the target string. This is similar to strcpy, but it will enforce a maximum size for the copied string and will ensure it is terminated with a null.
Parameters:
destPointer to a pointer that will hold the address of the allocated block.
destMaxMaximum size of the target string in characters.
srcString to copy.
lenMaximum count of characters to copy.
Returns:
Returns a reference to the destination if successful or NULL if the string won't fit.
API Stability:
Evolving.

PUBLIC char,* spbrk (cchar *str, cchar *set)

Locate the a character from a set in a string.

Description:
This locates in the string the first occurence of any character from a given set of characters.
Parameters:
strString to examine.
setSet of characters to scan for.
Returns:
Returns a reference to the first character from the given set. Returns NULL if none found.
API Stability:
Evolving.

PUBLIC char,* sptok (char *str, cchar *pattern, char **nextp)

Tokenize a string.

Description:
Split a string into tokens using a string pattern as delimiters.
Parameters:
strString to tokenize.
patternString pattern to use for token delimiters.
nextpNext token pointer.
Returns:
Returns a pointer to the string.
API Stability:
Evolving.

PUBLIC char,* srchr (cchar *str, int c)

Find a character in a string by searching backwards.

Description:
This locates in the string the last occurence of a character.
Parameters:
strString to examine.
cCharacter to scan for.
Returns:
Returns a reference in the string to the requested character. Returns NULL if none found.
API Stability:
Evolving.

PUBLIC char,* srejoin (char *buf, ...)

Append strings to an existing string and reallocate as required.

Description:
Append a list of strings to an existing string. The list of strings is terminated by a null argument. The call returns the size of the allocated block.
Parameters:
bufExisting (allocated) string to reallocate. May be null. May not be a string literal.
...Variable number of string arguments to append. Terminate list with NULL.
Returns:
Returns an allocated string.
API Stability:
Evolving.

PUBLIC char,* srejoinv (char *buf, va_list args)

Append strings to an existing string and reallocate as required.

Description:
Append a list of strings to an existing string. The list of strings is terminated by a null argument. The call returns the size of the allocated block.
Parameters:
bufExisting (allocated) string to reallocate. May be null. May not be a string literal.
argsVarargs argument obtained from va_start.
Returns:
Returns an allocated string.
API Stability:
Evolving.

PUBLIC char,* ssplit (char *str, cchar *delim, char **last)

Split a string at a delimiter.

Description:
Split a string and return pars. The string is modified. This routiner never returns null. If there are leading delimiters, the empty string will be returned and *last will be set to the portion after the delimiters. If str is null, a managed reference to the empty string will be returned. If there are no characters after the delimiter, then *last will be set to the empty string.
Parameters:
strString to tokenize.
delimSet of characters that are used as token separators.
lastReference to the portion after the delimiters. Will return an empty string if is not trailing portion.
Returns:
Returns a pointer to the first par before the delimiters. If the string begins with delimiters, the empty string will be returned.
API Stability:
Evolving.

PUBLIC ssize sspn (cchar *str, cchar *set)

Find the end of a spanning prefix.

Description:
This scans the given string for characters from the set and returns an index to the first character not in the set.
Parameters:
strString to examine.
setSet of characters to span.
Returns:
Returns an index to the first character after the spanning set. If not found, returns the index of the first null.
API Stability:
Evolving.

PUBLIC bool sstarts (cchar *str, cchar *prefix)

Test if the string starts with a given pattern.

Parameters:
strString to examine.
prefixPattern to search for.
Returns:
Returns true if the pattern was found. Otherwise returns zero.
API Stability:
Evolving.

PUBLIC char,* ssub (cchar *str, ssize offset, ssize length)

Create a substring.

Parameters:
strString to examine.
offsetStaring offset within str for the beginning of the substring.
lengthLength of the substring in characters.
Returns:
Returns a newly allocated substring.
API Stability:
Evolving.

PUBLIC char,* stemplate (cchar *str, void *tokens)

Replace template tokens in a string with values from a lookup table.

Tokens are ${variable} references
Parameters:
strString to expand.
tokensHash table of token values to use.
Returns:
An expanded string. May return the original string if no "$" references are present.
API Stability:
Evolving.

PUBLIC char,* stitle (cchar *str)

Create a Title Case version of the string.

Description:
Copy a string into a newly allocated block and make the first character upper case.
Parameters:
strPointer to the block to duplicate.
Returns:
Returns a newly allocated string.
API Stability:
Evolving.

PUBLIC double stod (cchar *str)

Convert a string to a double floating point value.

Description:
This call convers the supplied string to a double.
Parameters:
strPointer to the string to parse. If passed null, returns NAN.
Returns:
The double equivalent value of the string.
API Stability:
Evolving.

PUBLIC double stof (cchar *str)

Convert a string to a double.

Description:
This call convers the supplied string to a double.
Parameters:
strPointer to the string to parse.
Returns:
The double equivalent value of the string.
API Stability:
Evolving.

PUBLIC int64 stoi (cchar *str)

Convert a string to an integer.

Description:
This call convers the supplied string to an integer using base 10.
Parameters:
strPointer to the string to parse.
Returns:
The integer equivalent value of the string.
API Stability:
Evolving.

PUBLIC int64 stoiradix (cchar *str, int radix, int *err)

Convert a string to an integer.

Description:
This call convers the supplied string to an integer using the specified radix (base).
Parameters:
strPointer to the string to parse.
radixBase to use when parsing the string.
errReturn error code. Set to 0 if successful.
Returns:
The integer equivalent value of the string.

PUBLIC char,* stok (char *str, cchar *delim, char **last)

Tokenize a string.

Description:
Split a string into tokens using a character set as delimiters.
Parameters:
strString to tokenize.
delimSet of characters that are used as token separators.
lastLast token pointer.
Returns:
Returns a pointer to the next token inside the original string. Caller must not free the result.
API Stability:
Evolving.

PUBLIC struct,RList,* stolist (cchar *src)

String to list.

This parses the string of space separated arguments. Single and double quotes are supported
Parameters:
srcSource string to parse.
Returns:
List of arguments.
API Stability:
Evolving.

PUBLIC char,* strim (char *str, cchar *set, int where)

Trim a string.

Description:
Trim leading and trailing characters off a string. The original string is modified and the return value point into the original string.
Parameters:
strString to trim.
setString of characters to remove.
whereFlags to indicate trim from the start, end or both. Use R_TRIM_START, R_TRIM_END, R_TRIM_BOTH.
Returns:
Returns a reference into the original string. Caller must not free.
API Stability:
Evolving.

PUBLIC char,* supper (char *str)

Convert a string to upper case.

Description:
Convert a string to its upper case equivalent.
Parameters:
strString to conver.
Returns:
Returns a pointer to the converted string. Will always equal str.
API Stability:
Evolving.

PUBLIC uint64 svalue (cchar *value)

Parse a value string.

Description:
Parse a textual number with unit suffixes. The following suffixes are supported: sec, secs, second, seconds, min, mins, minute, minutes, hr, hrs, hour, hours, day, days, week, weeks, month, months, year, years, byte, bytes, k, kb, m, mb, g, gb. Also supports the strings: unlimited, infinite, never, forever.
Returns:
A 64 bit unsigned number.
API Stability:
Evolving.

PUBLIC void szero (char *str)

Erase the contents of a string.

Parameters:
strString to erase.
API Stability:
Evolving.