smax-clib v0.9
A C/C++ client library for SMA-X
Loading...
Searching...
No Matches
smax-util.c File Reference

A collection of commonly used functions for the SMA-X library. More...

Macros

#define _BSD_SOURCE
 strtoll() feature macro for glibc <= 2.19
 
#define _POSIX_C_SOURCE   199309
 For clock_gettime()
 

Functions

int smax2xField (XField *f)
 
int smax2xStruct (XStructure *s)
 
XFieldsmaxCreateField (const char *name, XType type, int ndim, const int *sizes, const void *value)
 
XMetasmaxCreateMeta ()
 
int smaxDeletePattern (const char *pattern)
 
int smaxError (const char *func, int errorCode)
 
const char * smaxErrorDescription (int code)
 
int smaxGetMetaCount (const XMeta *m)
 
char * smaxGetScriptSHA1 (const char *scriptName, int *status)
 
int smaxGetServerTime (struct timespec *t)
 
double smaxGetTime (const char *timestamp)
 
int smaxParseTime (const char *timestamp, time_t *secs, long *nanosecs)
 
void smaxResetMeta (XMeta *m)
 
int smaxScriptError (const char *name, int status)
 
int smaxScriptErrorAsync (const char *name, int status)
 
void smaxSetOrigin (XMeta *m, const char *origin)
 
int smaxStringToValues (const char *str, void *value, XType type, int eCount, int *pos)
 
char * smaxStringType (XType type)
 
int smaxTimestamp (char *buf)
 
__inline__ int smaxTimeToString (const struct timespec *time, char *buf)
 *‍/
 
void smaxTransmitErrorHandler (Redis *redis, enum redisx_channel channel, const char *op)
 
XType smaxTypeForString (const char *type)
 
int smaxUnpackStrings (const char *data, int len, int count, char **dst)
 
char * smaxValuesToString (const void *value, XType type, int eCount, char *trybuf, int trylength)
 
int x2smaxField (XField *f)
 
int x2smaxStruct (XStructure *s)
 

Detailed Description

A collection of commonly used functions for the SMA-X library.

Date
Jun 25, 2019
Author
Attila Kovacs

Function Documentation

◆ smax2xField()

int smax2xField ( XField f)

Converts SMA-X field with serialized string value storage to a standard xchange field with a native value storage.

Parameters
fPointer to field to convert
Returns
X_SUCCESS (0) if successful, or X_NULL if the input field or the deserialized value is NULL, X_TYPE_INVALID if the field is of a type that cannot be deserialized, or else an error code returned by smaxStringToValues().
See also
x2smaxField()
smax2xStruct()

References FALSE, XField::isSerialized, smax2xStruct(), smaxStringToValues(), XField::type, XField::value, x_error(), X_NULL, X_RAW, X_SIZE_INVALID, X_STRUCT, X_SUCCESS, x_trace(), X_TYPE_INVALID, xElementSizeOf(), and xGetFieldCount().

◆ smax2xStruct()

int smax2xStruct ( XStructure s)

Converts an SMA-X structure with serialized string value storage to a standard xchange structure with a native value storage.

Parameters
sPointer to structure to convert
Returns
X_SUCCESS (0) if successful, or X_STRUCT_INVALID if the structure is NULL, or had a NULL substructure, or else an error code returned by smax2xField().
See also
x2smaxStruct()
smax2xField()

References XStructure::firstField, XField::next, smax2xField(), x_error(), X_STRUCT_INVALID, and X_SUCCESS.

◆ smaxCreateField()

XField * smaxCreateField ( const char *  name,
XType  type,
int  ndim,
const int *  sizes,
const void *  value 
)

Creates a generic field of a given name and type and dimensions using the specified native values. It is like xCreateField() except that the field is created in serialized form for SMA-X.

Parameters
nameField name
typeStorage type, e.g. X_INT.
ndimNumber of dimensionas (1:20). If ndim < 1, it will be reinterpreted as ndim=1, size[0]=1;
sizesArray of sizes along each dimensions, with at least ndim elements, or NULL with ndim<1.
valuePointer to the native data location in memory. Unless it is of type X_STRUCT, the data stored in the field is a copy (for type X_RAW) or serialized string (otherwise).
Returns
A newly created field with the supplied data, or NULL if there was an error.
See also
xSetField()

References XField::isSerialized, smaxValuesToString(), TRUE, XField::value, X_RAW, X_STRING, X_STRUCT, x_trace_null(), xCreateField(), xGetElementCount(), and xStringElementSizeOf().

◆ smaxCreateMeta()

XMeta * smaxCreateMeta ( )

Creates a new SMA-X metadata object with defaults. Effectively the same as calling calloc() followed by xResetMeta().

Returns
Pointer to a new metadata object initialized to defaults.
See also
X_META_INIT

References smaxResetMeta().

◆ smaxDeletePattern()

int smaxDeletePattern ( const char *  pattern)

Deletes variables and metadata from SMA-X.

Parameters
patternGlob variable name pattern
Returns
The number of variables deleted from the SQL DB

References smaxGetRedis(), x_error(), X_NULL, and X_SEP.

◆ smaxError()

int smaxError ( const char *  func,
int  errorCode 
)

Prints a descriptive error message to stderr, and returns the error code.

Parameters
funcString that describes the function or location where the error occurred.
errorCodeError code that describes the failure.
Returns
Same error code as specified on input.

References redisxError(), smaxErrorDescription(), X_NO_SERVICE, and xDebug.

◆ smaxErrorDescription()

const char * smaxErrorDescription ( int  code)

Returns a string description for one of the RM error codes.

Parameters
codeOne of the error codes defined in 'xchange.h' or in 'smax.h' (e.g. X_NO_PIPELINE)

References redisxErrorDescription().

◆ smaxGetMetaCount()

int smaxGetMetaCount ( const XMeta m)

Returns the number of elements stored from a metadata.

Parameters
mpointer to metadata that defines the dimension and shape of elements.
Returns
the total number of elements represented by the metadata

References XMeta::storeDim, XMeta::storeSizes, and xGetElementCount().

◆ smaxGetScriptSHA1()

char * smaxGetScriptSHA1 ( const char *  scriptName,
int *  status 
)

Gets the SHA1 script ID for the currently loaded script with the specified name.

Parameters
scriptNameCase-sensitive name of the script, e.g. "GetStruct".
statusPointer int which to return status, which is X_SUCCESS if the SHA1 id was successfully obtained, or else an appropriate error code.
Returns
String buffer with the SHA1 key or NULL if it could not be retrieved. (The caller is responsible freeing the buffer after use.)

References redisxCheckDestroyRESP(), redisxDestroyRESP(), redisxRequest(), RESP_BULK_STRING, SMAX_SCRIPTS, smaxGetRedis(), RESP::value, x_error(), X_NAME_INVALID, and x_trace_null().

◆ smaxGetServerTime()

int smaxGetServerTime ( struct timespec *  t)

Returns the current time on the Redis server instance.

Parameters
tPointer to a timespec structure in which to return the server time.
Returns
X_SUCCESS (0) if successful, or X_NO_INIT if not connected to SMA-X, or X_NULL if either argument is NULL, or X_PARSE_ERROR if could not parse the response, or another error returned by redisxCheckRESP().

References redisxGetTime(), smaxGetRedis(), and X_SUCCESS.

◆ smaxGetTime()

double smaxGetTime ( const char *  timestamp)

Returns the a sub-second precision UNIX time value for the given SMA-X timestamp

Parameters
timestampThe string timestamp returned by SMA-X
Returns
Corresponding UNIX time with sub-second precision, or NAN if the input could not be parsed.

References NAN, smaxParseTime(), x_error(), X_NULL, and x_trace().

◆ smaxParseTime()

int smaxParseTime ( const char *  timestamp,
time_t *  secs,
long *  nanosecs 
)

Parses a timestamp into broken-down UNIX time.

Parameters
[in]timestampTimestamp string as returned in redis queries;
[out]secsPointer to the returned UNIX time (seconds).
[out]nanosecsPointer to the retuned sub-second remainder as nanoseconds, or NULL if nor requested.
Returns
X_SUCCESS(0) if the timestamp was successfully parsed. X_NULL if there was no timestamp (empty or invalid string), or the secs argument is NULL. X_PARSE_ERROR if the seconds could not be parsed. 1 if there was an error parsing the nanosec part. X_NULL if the secs arhument is NULL

References x_error(), X_NULL, X_PARSE_ERROR, and X_SUCCESS.

◆ smaxResetMeta()

void smaxResetMeta ( XMeta m)

Set metadata to their default values. After resetting the supplied metadata will have exactly the same content as if it were initialized with the X_META_INIT macro.

Parameters
mPointer to the metadata that is to be cleared.
See also
X_META_INIT

References X_META_INIT.

◆ smaxScriptError()

int smaxScriptError ( const char *  name,
int  status 
)

SMA-X error handler for when the LUA scripts do not execute. It prints a message to stderr, then depending on whether SMA-X is in resilient mode, it will try to reconnect to SMA-X in the background, or else exits the program with X_NO_SERVICE. You must not call this function with a locked config mutex (via smaxConfigLock()). Instead use the async version of this function after smaxConfigLock().

Parameters
nameThe name of the calling function or name of script (whichever is more informative).
statusAn approprioate error code from xchange.h to indicate the type of error.
See also
smaxScriptErrorAsync()
smaxSetResilient()

References smaxScriptErrorAsync().

◆ smaxScriptErrorAsync()

int smaxScriptErrorAsync ( const char *  name,
int  status 
)

Same as smaxScriptError(), but can be used after smaxConfigLock().

Parameters
nameThe name of the calling function or name of script (whichever is more informative).
statusAn approprioate error code from xchange.h to indicate the type of error.
See also
smaxScriptError()
smaxSetResilient()

References smaxErrorDescription(), smaxIsConnected(), smaxIsResilient(), TRUE, X_FAILURE, X_NO_SERVICE, and X_NULL.

◆ smaxSetOrigin()

void smaxSetOrigin ( XMeta m,
const char *  origin 
)

Sets the 'origin' field of an SMA-X metadata to the specified value, truncating as necessary to fit into the allotted fixed storage.

Parameters
originThe origination information, usually as hostname:progname
mPointer to metadata to set.

References XMeta::origin, and SMAX_ORIGIN_LENGTH.

◆ smaxStringToValues()

int smaxStringToValues ( const char *  str,
void *  value,
XType  type,
int  eCount,
int *  pos 
)

Deserializes a string to binary values.

Parameters
[in]strSerialized ASCII representation of the data (as stored by Redis).
[out]valuePointer to the buffer that will hold the binary values. The caller is responsible for ensuring the buffer is sufficiently sized for holding the data for the given variable.
[in]typeShare type, e.g. X_INT. The types X_RAW, X_STRUCT are not supported by this function.
[in]eCountNumber of elements to retrieve. Ignored for X_STRUCT.
[out]posParse position, i.e. the number of characters parsed from the input string...
Returns
Number of elements successfully parsed, or a negative error code:
                        X_NULL               If the value or str argument is NULL.
                        X_TYPE_INVALID       If the type is not supported.
                        X_SIZE_INVALID       If size is invalid (e.g. X_RAW, X_STRUCT)
                        X_PARSE_ERROR        If the tokens could not be parsed in the format expected

References smaxUnpackStrings(), X_BOOLEAN, X_BYTE, X_BYTE_HEX, X_DOUBLE, x_error(), X_FLOAT, X_INT, X_INT_HEX, X_LONG, X_LONG_HEX, X_NULL, X_RAW, X_SHORT, X_SHORT_HEX, X_SIZE_INVALID, X_STRING, X_STRUCT, x_trace(), X_TYPE_INVALID, xElementSizeOf(), xIsCharSequence(), xParseBoolean(), xParseDouble(), and xZero().

◆ smaxStringType()

char * smaxStringType ( XType  type)

Returns the string type for a given XType argument as a constant expression. For examples X_LONG -> "int64".

Parameters
typeSMA-X type, e.g. X_FLOAT
Returns
Corresponding string type, e.g. "float". (Default is "string" – since typically anything can be represented as strings.)
See also
smaxTypeForString()

References X_BOOLEAN, X_BYTE, X_BYTE_HEX, X_DOUBLE, x_error(), X_FLOAT, X_INT, X_INT_HEX, X_LONG, X_LONG_HEX, X_RAW, X_SHORT, X_SHORT_HEX, X_STRING, X_STRUCT, and X_UNKNOWN.

◆ smaxTimestamp()

int smaxTimestamp ( char *  buf)

Prints the current time into the supplied buffer with subsecond precision.

Parameters
[out]bufPointer to string buffer, must be at least X_TIMESTAMP_LENGTH in size.
Returns
Number of characters printed, not including the terminating '\0', or else an error code (<0) if the buf argument is NULL.

References smaxTimeToString().

◆ smaxTimeToString()

__inline__ int smaxTimeToString ( const struct timespec *  time,
char *  buf 
)

*‍/

Prints the given UNIX time into the supplied buffer with subsecond precision.

Parameters
[in]timePointer to time value.
[out]bufPointer to string buffer, must be at least X_TIMESTAMP_LENGTH in size.
Returns
Number of characters printed, not including the terminating '\0', or else an error code (<0) if the buf argument is NULL.

References x_error(), and X_NULL.

◆ smaxTransmitErrorHandler()

void smaxTransmitErrorHandler ( Redis redis,
enum redisx_channel  channel,
const char *  op 
)

The SMA-X error handler for Redis transmit (send or receive) errors. It prints a message to stderr, then depending on whether SMA-X is in resilient mode, it will try to reconnect to SMA-X in the background, or else exits the program with X_NO_SERVICE.

Parameters
redisThe Redis instance in which the error occurred. In case of SMA-X this will always be the Redis instance used by SMA-X.
channelThe Redis channel index on which the error occured, such as REDIS_INTERAVTIVE_CHANNEL
opThe operation during which the error occurred, e.g. 'send' or 'read'.
See also
smaxSetResilient()
redisxSetTrasmitErrorHandler()

References smaxGetRedis(), smaxIsResilient(), TRUE, X_FAILURE, and X_NO_SERVICE.

◆ smaxTypeForString()

XType smaxTypeForString ( const char *  type)

Returns the XType for a given case-sensitive type string. For example "float" -> X_FLOAT. The value "raw" will return X_RAW.

Parameters
typeString type, e.g. "struct".
Returns
Corresponding XType, e.g. X_STRUCT. (The default return value is X_RAW, since all Redis values can be represented as raw strings.)
See also
smaxStringType()

References X_BOOLEAN, X_BYTE, X_DOUBLE, x_error(), X_FLOAT, X_INT, X_LONG, X_RAW, X_SHORT, X_STRING, X_STRUCT, and X_UNKNOWN.

◆ smaxUnpackStrings()

int smaxUnpackStrings ( const char *  data,
int  len,
int  count,
char **  dst 
)

Returns an array of dynamically allocated strings from a packed buffer of consecutive 0-terminated or '\r'-separated string elements.

Parameters
[in]dataPointer to the packed string data buffer.
[in]lenlength of packed string (excl. termination).
[in]countNumber of string elements expected. If fewer than that are found in the packed data, then the returned array of pointers will be padded with NULL.
[out]dstAn array of string pointers (of size 'count') which will point to dynamically allocated string (char*) elements. The array is assumed to be uninitialized, and elements will be allocated as necessary.
Returns
X_SUCCESS (0) if successful, or X_NULL if one of the argument pointers is NULL, or else X_INCOMPLETE if some of the components were too large to unpack (alloc error).

References x_error(), X_INCOMPLETE, X_NULL, and X_SUCCESS.

◆ smaxValuesToString()

char * smaxValuesToString ( const void *  value,
XType  type,
int  eCount,
char *  trybuf,
int  trylength 
)

Serializes binary values into a string representation (for Redis).

Parameters
[in]valuePointer to an array of values, or NULL to produce all zeroes. If type is X_STRING value should be a pointer to a char** (array of string pointers), as opposed to X_CHAR(n), which expects a contiguous char* buffer with [n * eCount] length (Note, a char[eCount][n] is equivalent to such a char* buffer).
[in]typeShare type, e.g. X_DOUBLE. All type except X_STRUCT are supported.
[in]eCountNumber of elements (ignored for X_RAW).
[in,out]trybuf(optional) An optional pointer to a buffer that will be used if sufficient (can be NULL).
[in]trylength(optional) Size of the optional buffer.
Returns
The pointer to the string buffer holding the ASCII values. It may be the supplied buffer (if sufficient), the input value (if type is X_RAW) or else a dynamically allocated buffer, or NULL if the key is malformed. If the returned value is neither the input value nor trybuf, then the caller is responsible for calling free() on the dynamically allocated buffer after use.

References X_BOOLEAN, X_BYTE, X_BYTE_HEX, X_DOUBLE, x_error(), X_FLOAT, X_INT, X_INT_HEX, X_LONG, X_LONG_HEX, X_RAW, X_SHORT, X_SHORT_HEX, X_STRING, X_STRUCT, x_trace_null(), X_UNKNOWN, xElementSizeOf(), xIsCharSequence(), xPrintDouble(), xPrintFloat(), and xStringElementSizeOf().

◆ x2smaxField()

int x2smaxField ( XField f)

Converts a standard xchange field (with a native value storage) to an SMA-X field with serialized string value storage.

Parameters
[in,out]fPointer to field to convert
Returns
X_SUCCESS (0) if successful, or X_NULL if the input field or the serialized value is NULL.
See also
smax2xField()
x2smaxStruct()

References XField::isSerialized, smaxValuesToString(), TRUE, XField::type, XField::value, x2smaxStruct(), x_error(), X_NULL, X_RAW, X_STRUCT, X_SUCCESS, x_trace(), and xGetFieldCount().

◆ x2smaxStruct()

int x2smaxStruct ( XStructure s)

Converts a standard xchange structure (with a native value storage) to an SMA-X structure with serialized string value storage.

Parameters
sPointer to structure to convert
Returns
X_SUCCESS (0) if successful, or X_STRUCT_INVALID if the structure is NULL, or had a NULL substructure. X_NULL if there was a field that could not be converted.
See also
smax2xStruct()
x2smaxField()

References XStructure::firstField, XField::next, x2smaxField(), x_error(), X_STRUCT_INVALID, and X_SUCCESS.