
#ifndef ETHERCAT_SUGAR_GENERIC_H
#define ETHERCAT_SUGAR_GENERIC_H

#include "../ethercat_types.h"
#include "../slave/coe.h"
#include <stdint.h>

#ifdef __cplusplus

extern "C" {
#endif

#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__cplusplus)
#  define EC_HAS_GENERIC 1
#else
#  define EC_HAS_GENERIC 0
#endif

#if EC_HAS_GENERIC

#define ec_byte_size(x) _Generic((x),                                    \
    int8_t:   1, uint8_t:   1,                                           \
    int16_t:  2, uint16_t:  2,                                           \
    int32_t:  4, uint32_t:  4,                                           \
    int64_t:  8, uint64_t:  8,                                           \
    float:    4, double:    8,                                           \
    default:  0)

#include <stdio.h>
#include <inttypes.h>

#define ec_print_value(label, v) _Generic((v),                           \
    int8_t:   printf("%s = %"PRId8"\n",  (label), (int8_t)(v)),          \
    uint8_t:  printf("%s = %"PRIu8"\n",  (label), (uint8_t)(v)),         \
    int16_t:  printf("%s = %"PRId16"\n", (label), (int16_t)(v)),         \
    uint16_t: printf("%s = %"PRIu16"\n", (label), (uint16_t)(v)),        \
    int32_t:  printf("%s = %"PRId32"\n", (label), (int32_t)(v)),         \
    uint32_t: printf("%s = %"PRIu32"\n", (label), (uint32_t)(v)),        \
    int64_t:  printf("%s = %"PRId64"\n", (label), (int64_t)(v)),         \
    uint64_t: printf("%s = %"PRIu64"\n", (label), (uint64_t)(v)),        \
    float:    printf("%s = %f\n",        (label), (double)(v)),          \
    double:   printf("%s = %f\n",        (label), (double)(v)),          \
    default:  printf("%s = <?>\n",       (label)))

#define ec_max(a, b)  ((a) > (b) ? (a) : (b))
#define ec_min(a, b)  ((a) < (b) ? (a) : (b))

#else

#define ec_byte_size(x)        ((int)sizeof(x))
#define ec_print_value(l, v)    ((void)0)
#define ec_max(a, b)           ((a) > (b) ? (a) : (b))
#define ec_min(a, b)           ((a) < (b) ? (a) : (b))

#endif

#ifdef __cplusplus
}
#endif

#endif
