/*
 * Util functionality header
 *
 * Author : v.figol@samsung.com
 * Date	  : 15 Aug 2016
 *
 * Copyright (c) 2016 Samsung Electronics
 *
 */

#ifndef UTILS_H
#define UTILS_H

#include <openssl/platforms.h>

#define U32_SIZE_BYTES (4)

#define MEM_GET_U32(pt)          \
    (((uint32_t)(pt)[0] << 24) ^ \
     ((uint32_t)(pt)[1] << 16) ^ \
     ((uint32_t)(pt)[2] << 8)  ^ \
     ((uint32_t)(pt)[3]))

#define MEM_PUT_U32(ct, st)          \
{                                    \
    (ct)[0] = (uint8_t)((st) >> 24); \
    (ct)[1] = (uint8_t)((st) >> 16); \
    (ct)[2] = (uint8_t)((st) >> 8);  \
    (ct)[3] = (uint8_t)(st);         \
}

#if defined (DEBUG_LOG_MEM_TRACE_FIPS_BSSL)

/*
 * WARNING!! The following macros are to be used carefully
 * Due to at preprocessing they are unwrapped in complex code sequence
 * it should be taken care
 * about how they are used in expressions like if/then/else.
 * The best practice is to put them into brackets anyway.
 * For example: if (condition) { DEBUG_MEM_TRACE_START(block); }
*/

#define DEBUG_MEM_TRACE_PRINT()                             \
    LOGFIPS_D("Memory trace: (%s:%d) allocated: %d B ",    \
              __func__,                                     \
              __LINE__,                                     \
              FIPS_get_allocated_heap_size())

#define DEBUG_MEM_TRACE_START(block_name)                               \
    int block_name##_heap_start_status = FIPS_get_allocated_heap_size();             \
    const char* block_name##_memtrace_block_name = #block_name;                       \
    LOGFIPS_D("Memory trace START: \t %s block. ", block_name##_memtrace_block_name)

#define DEBUG_MEM_TRACE_STOP(block_name)                                          \
    int block_name##_heap_stop_status = FIPS_get_allocated_heap_size();              \
    LOGFIPS_D("Memory trace STOP: \t %s block. ", block_name##_memtrace_block_name); \
    LOGFIPS_D("Allocated: (start/stop) \t %d B / %d B",                 \
                block_name##_heap_start_status,                                      \
                block_name##_heap_stop_status);                                      \
    LOGFIPS_D("Difference: \t %d B",                                    \
                block_name##_heap_stop_status - block_name##_heap_start_status)

#else
#define DEBUG_MEM_TRACE_PRINT()
#define DEBUG_MEM_TRACE_START(block_name)
#define DEBUG_MEM_TRACE_STOP(block_name)
#endif /* End of DEBUG_LOG_MEM_TRACE_FIPS_BSSL */

void dump_bytes(unsigned char *bin, int len);
size_t __strnlen (register const char *s, size_t maxlen);

#endif  /* UTILS_H */
