das2C
das core C utilities (v3)
Data Structures | Macros | Typedefs | Functions
util.h File Reference
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <das2/defs.h>
Include dependency graph for util.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  das_error_msg
 Structure returned from das_get_error(). More...
 

Macros

#define DASERR_DIS_EXIT   0
 Used to indicate that errors should trigger program exit.
 
#define DASERR_DIS_RET   1
 Used to indicate that errors should trigger library functions to return error values.
 
#define DASERR_DIS_ABORT   43
 Used to indicate that errors should trigger program abort with a core dump.
 
#define das_error(nErrCode, ...)    das_error_func(__FILE__, __func__, __LINE__, nErrCode, __VA_ARGS__ )
 Signal an error condition. More...
 
#define das_within(A, B, E)   (fabs(A - B) < E ? true : false)
 Check to see if two floating point values are within an epsilon of each other.
 
#define DAS_XML_BUF_LEN   1000000
 The limit on xml packet length, in bytes. More...
 
#define DAS_XML_NODE_NAME_LEN   256
 The limit of xml element name length, in bytes.
 
#define DAS_MAX_ID_BUFSZ   64
 The size of an char buffer large enough to hold valid object IDs.
 

Typedefs

typedef void(* das_log_handler_t) (int nLevel, const char *sMsg, bool bPrnTime)
 Definition of a message handler function pointer. More...
 

Functions

DAS_API void das_init (const char *sProgName, int nErrDis, int nErrBufSz, int nLevel, das_log_handler_t logfunc)
 Initialize any global structures in the Das2 library. More...
 
DAS_API void das_finish (void)
 A do nothing function on Unix, closes network sockets on windows.
 
DAS_API void das_abort_on_error (void)
 Error handling: Trigger Core Dumps. More...
 
DAS_API void das_exit_on_error (void)
 Error handling: Normal Exit Set the library to call exit(ErrorCode) when a problem is detected. More...
 
DAS_API void das_return_on_error (void)
 Error handling: Normal Return Set the library to return normally to the calling function with a return value that indicates a problem has occurred. More...
 
DAS_API int das_error_disposition (void)
 Error handling: get the library's error disposition. More...
 
DAS_API void das_errdisp_get_lock ()
 Used for co-operative locking of time-limited error disposition changse. More...
 
DAS_API void das_errdisp_release_lock ()
 Used for co-operative locking of time-limited error disposition changse. More...
 
DAS_API void das_error_setdisp (int nDisp)
 The inverse of das_error_disposition. More...
 
DAS_API void das_print_error (void)
 Error handling: Print formatted error to standard error stream Set the library to ouput formatted error messages to the processes standard error stream. More...
 
DAS_API bool das_save_error (int maxmsg)
 Error handling: Save formatted error in a message buffer. More...
 
DAS_API const char * das_lib_version (void)
 Get the library version. More...
 
DAS_API bool das_assert_valid_id (const char *sId)
 Check that a string is suitable for use as an object ID. More...
 
DAS_API void das_store_str (char **psDest, size_t *puLen, const char *sSrc)
 Store string in a buffer that is reallocated if need be. More...
 
DAS_API char * das_string (const char *fmt,...)
 Allocate a new string on the heap and format it. More...
 
DAS_API size_t das_tokncpy (char *dest, const char *src, size_t n)
 Copy string as an XML token. More...
 
DAS_API const char * das_xml_escape (char *dest, const char *src, size_t uOutLen)
 Translate unsafe characters for XML string output. More...
 
DAS_API char * das_strdup (const char *sIn)
 Copy a string into a new buffer allocated on the heap. More...
 
DAS_API uint8_t * das_memset (uint8_t *pDest, const uint8_t *pSrc, size_t uElemSz, size_t uCount)
 A memset that handles multi-byte items
More...
 
DAS_API char * das_vstring (const char *fmt, va_list ap)
 Store a formatted string in a newly allocated buffer. More...
 
DAS_API bool das_isdir (const char *path)
 Is the path a directory. More...
 
DAS_API DasErrCode das_mkdirsto (const char *path)
 Insure directories to a specific location exist. More...
 
DAS_API const char * das_userhome (void)
 Get the home directory for the current account. More...
 
DAS_API bool das_copyfile (const char *src, const char *dest, mode_t mode)
 Copy a file to a distination creating directories as needed. More...
 
DAS_API bool das_isfile (const char *path)
 Is the path a file. More...
 
DAS_API int das_dirlist (const char *sPath, char ppDirList[][256], size_t uMaxDirs, char cType)
 Get a sorted directory listing. More...
 
DAS_API double das_strtod_c (const char *nptr, char **endptr)
 A C locale string to double converter. More...
 

Macro Definition Documentation

◆ das_error

#define das_error (   nErrCode,
  ... 
)     das_error_func(__FILE__, __func__, __LINE__, nErrCode, __VA_ARGS__ )

Signal an error condition.

This routine is called throughout the code when an error condition arrises.

The default handler for error conditions prints the message provided to the standard error channel and then calls exit(nErrCode). To have the library call your handler instead use the das_set_error_handler() function. To have the library abort with a core dump on an error use das_abort_on_error().

Each source file in the code has it's own error code. Though it's probably not that useful to end users, the codes are provided here:

  • 8 : Not yet implemented - DASERR_NOTIMP
  • 9 : Assertion Failures - DASERR_ASSERT
  • 10 : das1.c - D1ERR
  • 11 : Lib initialization errors - DASERR_INIT
  • 12 : buffer.c - DASERR_BUF
  • 13 : util.c - DASERR_UTIL
  • 14 : encoding.c - DASERR_ENC
  • 15 : units.c - DASERR_UNITS
  • 16 : descriptor.c - DASERR_DESC
  • 17 : plane.c - DASERR_PLANE
  • 18 : packet.c - DASERR_PKT
  • 19 : stream.c - DASERR_STREAM
  • 20 : oob.c - DASERR_OOB
  • 21 : io.c - DASERR_IO
  • 22 : dsdf.c - DASERR_DSDF
  • 23 : dft.c - DASERR_DFT
  • 24 : log.c - DASERR_LOG
  • 25 : array.c - DASERR_ARRAY
  • 26 : variable.c - DASERR_VAR
  • 27 : dimension.c - DASERR_DIM
  • 28 : dataset.c - DASERR_DS
  • 29 : builder.c - DASERR_BLDR
  • 30 : http.c - DASERR_HTTP
  • 31 : datum.c - DASERR_DATUM
  • 32 : value.c - DASERR_VALUE
  • 34 : operater.c - DASERR_OP
  • 35 : credentials.c - DASERR_CRED
  • 36 : catalog.c - DASERR_CAT
  • 37 : property.c - DASERR_PROP

Application programs are recommended to use values 64 and above to avoid colliding with future das2 error codes.

Parameters
nErrCodeThe value to return to the shell, should be one of the above.
Returns
By default this function never returns but if the libdas2 error disposition has been set to DAS2_ERRDIS_RET then the value of nErrCode is returned.

◆ DAS_XML_BUF_LEN

#define DAS_XML_BUF_LEN   1000000

The limit on xml packet length, in bytes.

(ascii encoding.)

Typedef Documentation

◆ das_log_handler_t

typedef void(* das_log_handler_t) (int nLevel, const char *sMsg, bool bPrnTime)

Definition of a message handler function pointer.

Message handlers need to be prepared for any of the string pointers sMsg, sDataStatus, or sStackTrace to be null.

Parameters
nLevelThe message level. If nLevel is equal to or greater than das_log_getlevel() then the message should be logged.
sMsgThe message, usually not null.
bPrnTimeThe current system time should be included in the log output.

Function Documentation

◆ das_init()

DAS_API void das_init ( const char *  sProgName,
int  nErrDis,
int  nErrBufSz,
int  nLevel,
das_log_handler_t  logfunc 
)

Initialize any global structures in the Das2 library.

This should be the first function your program calls before using any libdas2 functions. In general libdas2 tries to avoid global structures but does use them in following areas:

  • Error and log handling - Since the error and logging disposition should be the same for all library calls handlers are set here
  • Unit conversions - Since das_unit varibles should be comparible using a simple equality test, a global registry of const char pointers is needed
  • TT2000 leapsecond table - To avoid rebuilding the library after each leapsocond is announced, an external table defined by the environment variable CDF_LEAPSECONDTABLE is loaded, if the variable is defined.
  • FFTW plan mutexes - Since the FFTW library unfortunatly uses global plan memory
  • OpenSSL Contex mutexes - The openssl library contex cannot be changed by multiple threads at the same time, a mutex is setup to prevent this from happening

This function initializes defaults for the items above.

Parameters
sProgNameThe name of the program using the library. Used in some error messages.
nErrDisSet the behavior the library takes when an error is encountered. May be one of DASERR_DIS_EXIT, call exit() when an error occurs; DASERR_DIS_RET, return with an error code; or DASERR_DIS_ABORT, call abort(). The value of DASERR_DIS_EXIT is 0 so you can use that for the default behavior. If DASERR_DIS_RET is used, the function das_get_error() can be used to retrieve the most recent error message.
nErrBufSzIf not zero, a global error message buffer will be allocated that is this many bytes long and error message will be saved into the buffer instead of being sent to the standard error channel. Messages can be retrieved via das_get_error(). If zero, these will be send to the standard error channel as soon as they occur. Saving errors is only useful if the error disposition is DAS2_ERRDIS_RET as otherwise the program exits before the message can be output.
nLevelSet the logging level to one of, DASLOG_TRACE, DASLOG_DEBUG, DASLOG_NOTICE, DASLOG_WARN, DASLOG_ERROR, DASLOG_CRITICAL.
logfuncA callback for handling log messages. The callback need not be thread safe as it will only be triggered inside mutual exclusion (mutex) locks. If NULL messages are printed to the stardard error channel.

The error disposition does not affect any errors that are encountered within das_init. Errors should not occur during initialization, any that do trigger a call to exit()

◆ das_abort_on_error()

DAS_API void das_abort_on_error ( void  )

Error handling: Trigger Core Dumps.

Call this function to have the library exit via an abort() call instead of using exit(ErrorCode). On most systems this will trigger the generation of a core file that can be used for debugging.

Warning
: Calling this function prevents open file handles from being flushed to disk which will typically result in corrupted output.

◆ das_exit_on_error()

DAS_API void das_exit_on_error ( void  )

Error handling: Normal Exit Set the library to call exit(ErrorCode) when a problem is detected.

This is usually what you want and the library's default setting.

◆ das_return_on_error()

DAS_API void das_return_on_error ( void  )

Error handling: Normal Return Set the library to return normally to the calling function with a return value that indicates a problem has occurred.

This will be the new default, but is not yet tested.

◆ das_error_disposition()

DAS_API int das_error_disposition ( void  )

Error handling: get the library's error disposition.

Returns
one of the following integers:
  • DAS2_ERRDIS_EXIT - Library exits when there is a problem
  • DAS2_ERRDIS_ABORT - Library aborts, possibly with core dump on a problem
  • DAS2_ERRDIS_RET - Library returns normally with an error code

◆ das_errdisp_get_lock()

DAS_API void das_errdisp_get_lock ( )

Used for co-operative locking of time-limited error disposition changse.

Aquire this lock before your critical section, then release it. All code that want's to toggle the error disposition should use this, but it's not enforcable, except by code review.

YOU MUST BE SURE YOUR FUNCTION CAN'T EXIT BEFORE THE LOCK IS RELEASED!

◆ das_errdisp_release_lock()

DAS_API void das_errdisp_release_lock ( )

Used for co-operative locking of time-limited error disposition changse.

Release this lock before your critical section, then release it. All code that want's to toggle the error disposition should use this, but it's not enforcable, except by code review.

◆ das_error_setdisp()

DAS_API void das_error_setdisp ( int  nDisp)

The inverse of das_error_disposition.

Parameters
nDispOne of DAS2_ERRDIS_EXIT, DAS2_ERRDIS_ABORT, DAS2_ERRDIS_RET

◆ das_print_error()

DAS_API void das_print_error ( void  )

Error handling: Print formatted error to standard error stream Set the library to ouput formatted error messages to the processes standard error stream.

This is the default.

◆ das_save_error()

DAS_API bool das_save_error ( int  maxmsg)

Error handling: Save formatted error in a message buffer.

Set the library to save formatted error message to a message buffer.

Parameters
maxmsgmaximum message size. The buffer created will be maxmsg in length, meaning any formatted messages longer than the available buffer size will be truncated to maxmsg-1
Returns
true if error buffer setup was successful, false otherwise.

◆ das_lib_version()

DAS_API const char* das_lib_version ( void  )

Get the library version.

Returns
the version tag string for the das2 core library, or the string "untagged" if the version is unknown

◆ das_assert_valid_id()

DAS_API bool das_assert_valid_id ( const char *  sId)

Check that a string is suitable for use as an object ID.

Object ID strings are ascii strings using only characters from the set a-z, A-Z, 0-9, and _. They do not start with a number. They are no more than 63 bytes long. Basically they can be used as variable names in most programming languages.

If the das_error_disposition is set to exit this function never returns.

Parameters
sId
Returns
True if the string can be used as an ID, false otherwise.

◆ das_store_str()

DAS_API void das_store_str ( char **  psDest,
size_t *  puLen,
const char *  sSrc 
)

Store string in a buffer that is reallocated if need be.

Parameters
psDesta pointer to the storage location
puLena pointer to the size of the storage location
sSrcthe source string to store.

◆ das_string()

DAS_API char* das_string ( const char *  fmt,
  ... 
)

Allocate a new string on the heap and format it.

Except for using das_error on a failure, this is a copy of the code out of man 3 printf on Linux.

Returns
A pointer to the newly allocated and formatted string on the heap, or NULL if the function failed and the das2 error disposition allows for continuation after a failure

◆ das_tokncpy()

DAS_API size_t das_tokncpy ( char *  dest,
const char *  src,
size_t  n 
)

Copy string as an XML token.

Copy a string ignoring leading and traily spaces. Internal whitespace characters are converted to regular spaces and collapsed

Parameters
destThe buffer to receive string data, may be UTF-8 if desired The output string is always null terminated if n > 1
srcthe source string, may be UTF-8 if desired
nthe size of the dest buffer
Returns
the equivalent of strlen(dest).

◆ das_xml_escape()

DAS_API const char* das_xml_escape ( char *  dest,
const char *  src,
size_t  uOutLen 
)

Translate unsafe characters for XML string output.

At present only the characters set [ " < > & ] are translated. All white space characters are preserved. So long as dest is at least one byte long the result is null terminated.

Parameters
destThe buffer to receive the output
srcThe data source
uOutLenthe size of the dest buffer.
Returns
the parameter dest cast to a constant pointer.

◆ das_strdup()

DAS_API char* das_strdup ( const char *  sIn)

Copy a string into a new buffer allocated on the heap.

Parameters
sInthe string to copy
Returns
a pointer to the newly allocated buffer containing the same characters as the input string or NULL if the input length was zero

◆ das_memset()

DAS_API uint8_t* das_memset ( uint8_t *  pDest,
const uint8_t *  pSrc,
size_t  uElemSz,
size_t  uCount 
)

A memset that handles multi-byte items

Uses memcpy because the amount of data written in each call goes up exponentially and memcpy is freaking fast, much faster than a linear write loop for large arrays.

Parameters
pDestThe destination area must not overlap with pSrc
pSrcA location for an individual element to repeat in pDest
uElemSzThe size in bytes of a single element
uCountThe number of elements to repeat in pDest
Returns
The input pDest pointer. There is no provision for a NULL return as this function should not fail since the memory is pre-allocated by the caller

◆ das_vstring()

DAS_API char* das_vstring ( const char *  fmt,
va_list  ap 
)

Store a formatted string in a newly allocated buffer.

This version is suitable for calling from variable argument functions.

Except for using das_error on a failure, this is a copy of the code out of man 3 printf on Linux.

Parameters
fmt- a printf format string
apA va_list list, see vfprintf or stdarg.h for details
Returns
A pointer to the newly allocated and formatted string on the heap, or NULL if the function failed and the das2 error disposition allows for continuation after a failure

◆ das_isdir()

DAS_API bool das_isdir ( const char *  path)

Is the path a directory.

Parameters
pathThe directory in question, passed to stat(2)
Returns
true if path can be determined to be a directory, false otherwise

◆ das_mkdirsto()

DAS_API DasErrCode das_mkdirsto ( const char *  path)

Insure directories to a specific location exist.

Parameters
sPatha full path to a file. If this string contains no path separators, the function does nothing.
Returns
true if directories up to the final location either exist, or could be generated, false otherwise.

◆ das_userhome()

DAS_API const char* das_userhome ( void  )

Get the home directory for the current account.

Returns
A pointer to a global string that is the current user's home directory, or other likely writable location if the home directory could not be determined.

◆ das_copyfile()

DAS_API bool das_copyfile ( const char *  src,
const char *  dest,
mode_t  mode 
)

Copy a file to a distination creating directories as needed.

If the files exists at the destination it in overwritten. Directories are created as needed. Directory permissions are are the same as the file with the addition that for each READ permission in the mode, directory EXEC permission is added.

Parameters
src- name of file to copy
dest- name of destination
mode- the permission mode of the destitation file, 0664 is recommened if you can descide on the output permissions mode. (mode argument not present in WIN32 version)
Returns
- true if the copy was successful, false otherwise.

◆ das_isfile()

DAS_API bool das_isfile ( const char *  path)

Is the path a file.

Parameters
pathThe file in question, passed to stat(2)
Returns
true if path can be determined to be a file, false otherwise

◆ das_dirlist()

DAS_API int das_dirlist ( const char *  sPath,
char  ppDirList[][256],
size_t  uMaxDirs,
char  cType 
)

Get a sorted directory listing.

Parameters
sPathThe path to the directory to read.
ppDirListA pointer to a 2-D character array where the first index is the directory item and the second index is the character position. The max value of the second index must be = NAME_MAX - 1. The value NAME_MAX is defined in the POSIX header limits.h
uMaxDirsThe maximum number of directory entries that may be stored
cTypeMay be used to filter the items returned. If cType = 'f' only files will be return, if cType = 'd' then only directories will be returned. Any other value, including 0 will return both.
Returns
On success the number of items in the directory not counting '.' and '..' are returned, on failure a negative error code is returned. Item names are sorted before return.

◆ das_strtod_c()

DAS_API double das_strtod_c ( const char *  nptr,
char **  endptr 
)

A C locale string to double converter.

This is essentially the same as the C-lib function strtod, except it always evaluates strings in the "C" locale no matter the current locale of the program. It does not alter the current program's locale.

Parameters
nptrThe starting point of the string to convert
endptrWhere to store a pointer to the last item converted
Returns
The converted value

Notes: Errno is set as normal for the underlying strtod implementation.