/*
 * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
 *
 * This software is dual-licensed to you under the MIT License (MIT) and
 * the Universal Permissive License (UPL). See the LICENSE file in the root
 * directory for license terms. You may choose either license, or both.
 */


#ifndef UTIL_H
#define	UTIL_H

#ifdef	__cplusplus
extern "C" {
#endif

#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>

#ifndef ARRAY_SIZE
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
#endif

#ifndef MIN
#define MIN(a,b) ((a) < (b)) ? (a) : (b)
#endif

#ifndef UNUSED_ARG
#define UNUSED_ARG(_x) ((void)(_x))
#endif

#define UTIL__STRINGIFY(x) #x
#define UTIL_STRINGIFY(x) UTIL__STRINGIFY(x)

    /**
     * @brief Transforms input digest buffer into hexadecimal representation
     * @param hex_buffer output hex buffer (digest_length*2 + 1) bytes in size
     * @param digest input digest buffer
     * @param digest_length length of the digest buffer
     */
    void util_digest_to_hex(char* hex_buffer, unsigned char* digest, int digest_length);
    int util_safe_vsnprintf(char* buf, int buf_length, const char* format, va_list ap);
    int util_safe_snprintf(char* buf, int buf_length, const char* format, ...);
    int util_size_t_to_int(size_t val);

    int util_urlencode(const char *src, char *dest, int dest_sz);

    char* util_get_next_token(char** next, char separator);
    char* util_remove_symbol_from_str(char** str, char separator, int* entry_count);

    /**
     * @brief Copies source string into a newly allocated string.
     * If source is NULL, NULL will be return.
     * Works only with NULL-terminated strings.
     * @param source
     * @return pointer to a new string, NULL if OOM.
     */
    char* util_safe_strcpy(const char* source);

    /**
     * @brief Copies len characters of source string into a newly allocated string.
     * If source is NULL, nNULL will be return.
     * Works only with NULL-terminated strings.
     * @param source
     * @param len
     * @return pointer to a new string, NULL if OOM.
     */
    char* util_safe_strncpy(const char* source, int len);

    /**
     * @brief Replace NULL string with an empty one.
     * @param str
     * @retval Empty string ("") if src == NULL, original string otherwise.
     */
    const char* util_str_null(const char* str);

    /**
     * @brief check that number isn't NaN or INFINITY.
     * @param value
     * @return 1 if number is ok; 0 otherwise.
     */
    int util_is_valid_number(float value);


#ifdef	__cplusplus
}
#endif

#endif	/* UTIL_H */

